1

I want to help yours

if i have a pandas dataframe merge

first dataframe is

D = { Year, Age, Location, column1, column2... }
      2013, 20 , america, ..., ...
      2013, 35, usa, ..., ...
      2011, 32, asia, ..., ...
      2008, 45, japan, ..., ...

shape is 38654rows x 14 columns

second dataframe is

D = { Year, Location, column1, column2... }
      2008, usa, ..., ...
      2008, usa, ..., ...
      2009, asia, ..., ...
      2009, asia, ..., ...
      2010, japna, ..., ...

shape is 96rows x 7 columns

I want to merge or join two different dataframe. How can I do it?

thanks

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
GrayHash
  • 297
  • 2
  • 9

1 Answers1

4

IIUC you need merge with parameter how='left' if need left join on column Year and Location:

print (df1)
   Year  Age Location  column1  column2
0  2013   20  america        7        5
1  2008   35      usa        8        1
2  2011   32     asia        9        3
3  2008   45    japan        7        1

print (df2)
   Year Location  column1  column2
0  2008      usa        8        9
1  2008      usa        7        2
2  2009     asia        8        2
3  2009     asia        0        1
4  2010    japna        9        3

df = pd.merge(df1,df2, on=['Year','Location'], how='left')
print (df)
   Year  Age Location  column1_x  column2_x  column1_y  column2_y
0  2013   20  america          7          5        NaN        NaN
1  2008   35      usa          8          1        8.0        9.0
2  2008   35      usa          8          1        7.0        2.0
3  2011   32     asia          9          3        NaN        NaN
4  2008   45    japan          7          1        NaN        NaN

You can also check documentation.

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252