简体   繁体   English

通过两列中的列值合并数据框

[英]Merging dataframes by column values in two columns

I have two dataframes, df1 and df2: 我有两个数据框df1和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. 两个数据帧具有相同的列df1和df2。 I need to add columns 'y' and 'z' on df2 to df1 such that the values in columns 'w' and 'x' are identical. 我需要将df2上的列“ y”和“ z”添加到df1,以使列“ w”和“ x”中的值相同。

The end result would be: 最终结果将是:

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

You can use .merge() . 您可以使用.merge()

df1.merge(df2)

Output : 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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