1

I'm trying to join 2 dataframes in a kind of strange way and was wondering if anyone has any advice.

My first data frame looks like this, call it df1:

teamStatsDF

2nd one looks like, call it df2:

teamGames

I want my final output to merge each team's stats next to their respective names in the games dataframe. A brute force way I thought of doing this was to change the name of the TEAM column in df1 to Home, join it on that. Then, change the TEAM column to Visitor and join it on that too but I feel their should be an easier way. Can anyone give me advice on this, thanks!

Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
Brandon
  • 11
  • 1
  • 3
  • 2
    Welcome to SO! Can you please provide samples of your data as text rather than images. `df.head().to_dict()` for each dataframe should suffice. This way we can easily test and propose solutions. – jpp Mar 02 '18 at 21:35
  • 1
    In addition, please read how to produce a [mcve]. It's a help us help you scenario. – piRSquared Mar 02 '18 at 21:39

1 Answers1

2

You can use left_on and right_on parameters from pd.merge.

df1 = pd.DataFrame({'col1' : ['a','b','c','d','e','b'], 'val2': [31,43,23,54,65,23]})
df2 = pd.DataFrame({'col2': ['a','b','c'], 'val1': [11,22,33]})

df3 = pd.merge(df1, df2, left_on='col1', right_on='col2', how='left')
print(df3)

  col1 val2 col2 val1
0   a   31   a   11.0
1   b   43   b   22.0
2   c   23   c   33.0
3   d   54  NaN  NaN
4   e   65  NaN  NaN
5   b   23   b   22.0
YOLO
  • 20,181
  • 5
  • 20
  • 40