根据匹配的列值将元素从一个数据框映射到另一个数据框

时间:2019-02-27 19:36:16

标签: python pandas

我有2个数据框:

Reference_DF:

root_cause_level3   root_cause_level2   root_cause_level1
NA                  NA                  NA
Natural Disaster    Natural Disaster    Natural Disaster
Other               Other               Other
Communications      Misunderstood       Long Message

Actual_DF:

incident_id        root_cause_level3       root_cause_level2   root_cause_level1
XXXXXXXX-1         Communications       
XXXXXXXX-2         NA       
XXXXXXXX-3         NA       
XXXXXXXX-4         Other        
XXXXXXXX-1         Natural Disaster 

我的目标是将从参考DF映射到实际DF 级别2和级别1的根本原因。我想根据匹配的level3根本原因来映射它。我不知道该怎么办,有关如何解决此问题的任何建议?

预期输出:

incident_id        root_cause_level3       root_cause_level2   root_cause_level1
XXXXXXXX-1         Communications          Misunderstood       Long Message
XXXXXXXX-2         NA                      NA                  NA
XXXXXXXX-3         NA                      NA                  NA       
XXXXXXXX-4         Other                   Other               Other        
XXXXXXXX-1         Natural Disaster        Natural Disaster    Natural Disaster

1 个答案:

答案 0 :(得分:0)

您应该可以像这样使用.merge()

new_df = pandas.merge(actual_df, reference_df, on='root_cause_level3', how='left')

更干净的方法可能是执行以下操作:

new_df = pandas.merge(actual_df[['incident_id','root_cause_level3']], reference_df, on='root_cause_level3', how='left')

那么您不会在new_df

中获得重复的列名