1

I have two dataframes

df1:

Person    Value
Jack        6
Jill        9
Sam         4
Tony        3


df2:

Home    Away
Jill    Sam
Tony    Jack

I wish to make a 3rd dataframe which grabs the number in the Value column from df1 and matches them to the names in df2

Goal output:

df3:

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

Is there a simple merge function I can perform on this?

Thanks

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
Michael
  • 343
  • 2
  • 7

1 Answers1

2

Use Series.map for both columns:

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

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

Or use DataFrame.assign for new 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

Solution with double DataFrame.merge and rename columns:

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
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252