使用熊猫合并两个数据框

时间:2019-10-23 08:22:49

标签: python pandas

我有两个数据框

df1:

Person    Value
Jack        6
Jill        9
Sam         4
Tony        3


df2:

Home    Away
Jill    Sam
Tony    Jack

我希望制作第3个数据框,该数据框从df1的Value列中获取数字并将其与df2中的名称匹配

目标输出:

df3:

Home    Away    Value1    Value2
Jill    Sam       9         4
Tony    Jack      3         6    

有没有可以执行的简单合并功能?

谢谢

1 个答案:

答案 0 :(得分:2)

对两列都使用Series.map

s = df1.set_index('Person')['Value']

df2['Value1'] = df2['Home'].map(s)
df2['Value2'] = df2['Away'].map(s)

或将DataFrame.assign用于新的DataFrame

s = df1.set_index('Person')['Value']
df3 = df2.assign(Value1 = df2['Home'].map(s),
                 Value2 = df2['Away'].map(s))
print (df3)
   Home  Away  Value1  Value2
0  Jill   Sam       9       4
1  Tony  Jack       3       6

具有双DataFrame.mergerename列的解决方案:

df3 = (df2.merge(df1.rename(columns={'Person':'Home','Value':'Value1'}), how='left')
          .merge(df1.rename(columns={'Person':'Away','Value':'Value2'}), how='left'))
print (df3)
   Home  Away  Value1  Value2
0  Jill   Sam       9       4
1  Tony  Jack       3       6