首页 > 解决方案 > 根据 2 个数据帧 (df1, df2) 之间的匹配列更新一个 DF (df1) 的行

问题描述

我有两个数据框

DF1:

EmployeeID CollectiveBargainingUnit BusinessGroup ProfitCenter Eligible
1          12A                      A12           UGZ.         
2          17A                      B12           MGZ.         
3          18A                      C12           DGZ.         
4          19A                      D12           XGZ.         

DF2:

CollectiveBargainingUnit BusinessGroup ProfitCenter Eligible
12A                      A12           UGZ.         True
17A                      B12           MGZ.         False
18A                      C12           DGZ.         False
19A                      D12           XGZ.         True
12A                      A13           UGZ.         False
27A                      C12           MKZ.         True
32A                      C22           DGZ.         True
19A                      D99           XGZ.         False

我想要完成的是这个

EmployeeID CollectiveBargainingUnit BusinessGroup ProfitCenter Eligible
1          12A                      A12           UGZ.         True
2          17A                      B12           MGZ.         False
3          18A                      C12           DGZ.         False
4          19A                      D12           XGZ.         True

基于两个数据框(CollectiveBargainingUnit BusinessGroup ProfitCenter)之间的多列,我想在 DF2 中访问它的资格并在 DF1 中更新它

我离开的地方是:

eligibility_map=df2.groupby(["BusinessGroup","ProfitCenter","CollectiveBargainingUnit"]).first()["Eligible"]

df1["Eligible"] = df1["BargainingUnit"].map(eligibility_map).fillna(df1["Eligible"])

我不能只将它映射到一列。我需要一次映射到多个列。

标签: pandasdataframepandas-groupby

解决方案


您可以merge df1基于df2所需的列。此外,您必须Eligible在合并之前放入 df1,因为它不是必需的。

(df1.drop('Eligible', axis=1)
 .merge(df2, on=['CollectiveBargainingUnit', 'BusinessGroup','ProfitCenter'], how='inner'))

在此处输入图像描述


推荐阅读