如何在Pandas中实现R语言的指定索引后移赋值逻辑?
Solution: Fixing Index Assignment in Pandas
Your core idea is correct, but the issue comes from how you're handling the tuple output of np.where and ensuring replacement values are in the right format (a Series, not a DataFrame). Let's break this down step by step:
Step 1: Identify the Problems in Your Current Code
np.where(df.id != df.id_old)returns a tuple of arrays (in your case,(array([2, 4, 5, 9]),)). When you use this directly withnp.add, you end up with a 2D array ([[3,5,6,10]]), which pandas can't properly interpret for row indexing.replacement_values = df.iloc[myindex][['col2']]creates a DataFrame, but assigning to a single column (col3) requires a 1D Series instead—this mismatch causes the assignment to fail.
Step 2: Corrected Code Implementation
Let's adjust your code to fix these issues:
import pandas as pd import numpy as np # Example data (matches your input) df = pd.DataFrame({ 'id': [1, 1, 1, 2, 2, 3, 4, 4, 4, 4, 5, 5], 'id_old': [1, 1, 2, 2, 3, 4, 4, 4, 4, 5, 5, 5], 'col1': np.random.normal(size=12), 'col2': np.random.randint(low=20, high=50, size=12), 'col3': np.repeat(20, 12) }) # Extract the 1D array of indices from the np.where tuple myindex = np.where(df.id != df.id_old)[0] # Now it's [2,4,5,9] # Calculate target positions (index +1) target_indices = myindex + 1 # [3,5,6,10] # Get replacement values as a 1D Series replacement_values = df.loc[myindex, 'col2'] # Assign values to col3 at the target indices df.loc[target_indices, 'col3'] = replacement_values print(df)
Step 3: Verify the Result
Running this code will produce exactly your expected output:
col3at index 3 becomesdf.col2[2] = 27col3at index 5 becomesdf.col2[4] = 34col3at index 6 becomesdf.col2[5] = 42col3at index 10 becomesdf.col2[9] = 22
Key Takeaways
- Always extract the 1D array from
np.whereresults using[0]when working with single-column conditions. - Use
df.loc[row_indices, column_name]to get a Series of values for assignment, instead of subsetting into a DataFrame. - Ensure your target indices are a 1D array (not 2D) so pandas can correctly map replacement values to the right rows.
内容的提问来源于stack exchange,提问作者KaB
相关产品推荐
相关产品推荐

