简体   繁体   中英

Merging dataframes by column values in two columns

I have two dataframes, df1 and df2:

df1 = pandas.DataFrame({'w':['a','b','c'], 'x':['d','e','f']})


df2 = pandas.DataFrame({'w':['b','a','g','c'], 'x':['h','d','i','f'],'y':['j','k','l','m'],'z':['n','o','p','q']})

In [106]: df1
Out[106]: 
   w  x
0  a  d
1  b  e
2  c  f

In[107]: df2
Out[107]: 
   w  x  y  z
0  b  h  j  n
1  a  d  k  o
2  g  i  l  p
3  c  f  m  q

Both dataframes have same columns df1 and df2. I need to add columns 'y' and 'z' on df2 to df1 such that the values in columns 'w' and 'x' are identical.

The end result would be:

  w  x  y  z
0 a  d  k  o
1 c  f  m  q

You can use .merge() .

df1.merge(df2)

Output :

    w   x   y   z
0   a   d   k   o
1   c   f   m   q

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM