简体   繁体   中英

How to copy a column from a pandas dataframe to another while matching values of common columns in both?

I have following 2 dfs. I want to copy df2's column C to df1's column C, where df1's columns A and B match df2's columns A and B.

df1
A    B    C    F   G ...
1   12   NaN  52  50
2   14   NaN  62  60
3   15   NaN  72  70
2   14   NaN  82  80

df2

A   B  C   D    E  ...
2  14  0  abc  xyz
3  15  1  efg  pqr
1  12  1  hij  stu

Now I want my df1 to look like:

df1
A   B  C   F    G  ...
1  12  1  52   50
2  14  0  62   60
3  15  1  72   70
2  14  0  82   80

How can I achieve this in pandas? Any help would be appreciated.

First remove column C , then DataFrame.merge with left join only by filtered columns - A , B columns are for join and C is new added columns, last reorder columns by original df1 with DataFrame.reindex :

df = (df1.drop('C', 1)
         .merge(df2[['A','B', 'C']], on=['A','B'], how='left')
         .reindex(columns=df1.columns))
print (df)
   A   B  C   F   G
0  1  12  1  52  50
1  2  14  0  62  60
2  3  15  1  72  70
3  2  14  0  82  80

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM