如何基于条件筛选将DataFrame指定列替换至另一DataFrame对应位置
How to Replace Specific Columns in df2 with Rows from df1 Where
name == "A" Got it, let's walk through how to solve this problem step by step. The core goal is to filter rows in df1 where the name column equals "A", then overwrite the specified columns in df2 at those exact index positions.
Step 1: Set Up the Sample Data
First, let's import pandas and create the sample DataFrames as you provided:
import pandas as pd # Create df1 first_data={"col1":[2,3,4,5,7], "col2":[4,2,4,6,4], "col3":[7,6,9,11,2], "col4":[14,11,22,8,5], "name":["A","A","V","A","B"], "n_roll":[8,2,1,3,9]} df1=pd.DataFrame.from_dict(first_data) # Create df2 sec_df={"col1":[55,0,57,1,3], "col2":[55,0,4,4,53], "col3":[55,33,9,0,2], "col4":[55,0,22,4,5], "name":["A","A","V","A","B"], "n_roll":[8,2,1,3,9]} df2=pd.DataFrame.from_dict(sec_df)
Step 2: Implement the Replacement Logic
Here's the straightforward code to get the job done. We'll break it down into simple parts:
- Identify which indices in
df1havename == "A" - Define the columns we want to update in
df2 - Overwrite those columns in
df2using values from the matching indices indf1
# Specify the columns you want to replace (adjust this list as needed) columns_to_replace = ["col1", "col2", "col3", "col4"] # Or use ["col1","col2","n_roll"] # Get the indices in df1 where name is "A" target_indices = df1[df1["name"] == "A"].index # Replace the specified columns in df2 with values from df1 at the target indices df2.loc[target_indices, columns_to_replace] = df1.loc[target_indices, columns_to_replace].values
Step 3: Check the Result
After running the code, print df2 to verify the changes:
print(df2)
This will output:
col1 col2 col3 col4 name n_roll 0 2 4 7 14 A 8 1 3 2 6 11 A 2 2 57 4 9 22 V 1 3 5 6 11 8 A 3 4 3 53 2 5 B 9
Quick Notes
- Using
.valuesensures we bypass pandas' automatic index alignment, so we directly assign values based on position (this is optional here since our sample DataFrames have identical indices, but it's a safe practice for general cases). - You can easily swap the
columns_to_replacelist with any subset of columns you need to update—just adjust the list to match your requirements.
内容的提问来源于stack exchange,提问作者matan
相关产品推荐
相关产品推荐

