简体   繁体   English

如何将 pandas dataframe 中的列复制到另一个列,同时匹配两者中公共列的值?

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

I have following 2 dfs.我有以下 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.我想将 df2 的列 C 复制到 df1 的列 C,其中 df1 的 A 和 B 列与 df2 的 A 和 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 看起来像:

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?如何在 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 : 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将一列中的值映射到另一个数据帧的另外两列并提取两列上的匹配值? - How to map values in a column to two other column of another dataframe and extract matching values on both columns? Pandas 将 1 列值与另一个数据框列进行比较,找到匹配的行 - Pandas compare 1 columns values to another dataframe column, find matching rows Pandas - 将一个数据框中的列与另一个数据框中的多个列匹配,并从原始数据框创建新列 - Pandas - matching values from a column in one dataframe to several columns in another dataframe and creating new columns from the original dataframe 如果其他两个列在Pandas中具有匹配的值,如何用另一个数据框的值填充空列的值? - How to fill empty column values with another dataframe's value if two other columns have matching values in Pandas? 如何通过匹配来自另一个数据帧熊猫的值来填充数据帧中的列的值 - How to fill in values for a column in a dataframe by matching values from another dataframe pandas 基于匹配来自另一个数据帧pandas的值的新列 - New column based on matching values from another dataframe pandas 根据 Pandas 中的列值将内容从一个 Dataframe 复制到另一个 Dataframe - Copy contents from one Dataframe to another based on column values in Pandas 如何根据 pandas 中两个不同列的条件将值从一列复制到另一列? - how to copy values from one column into another column based on conditions of two different columns in pandas? 如何基于与熊猫匹配的列值将数据从一个数据帧移动到另一个数据帧? - How to move data from one dataframe to another based on matching column values with pandas? 将Pandas DataFrame列值与另一个DataFrame列匹配 - Matching Pandas DataFrame Column Values with another DataFrame Column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM