大熊猫合并匹配不同的行

时间:2019-01-24 03:35:59

标签: python python-3.x pandas

我有两个数据帧,其中某些项目(a,b,c ..)的名称以旧版本和新版本以不同的顺序排列。这里old_a和new_a是不同的词(例如old_a='cat', new_a='dog')。非常简化;

enter image description here

我想在下面获取数据框;

enter image description here

我可以通过以下方式找到相应的索引

df= pd.merge(df1.reset_index(), df2.reset_index(), on=['names'])

但是这给了我下面的df,我如何从这里转到期望的上面的数据帧?

enter image description here

1 个答案:

答案 0 :(得分:1)

您应该使用pd.concat

In [829]: df1
Out[829]: 
   names
0  old_a
1  old_b
2  old_c
3  old_d

In [828]: df2
Out[828]: 
   names
0  new_a
1  new_b
2  new_c
3  new_d

In [830]: df = pd.concat([df1.rename(columns={'names':'old_names'}),df2.rename(columns={'names':'new_names'})], axis=1)

In [833]: df
Out[833]: 
  old_names new_names
0     old_a     new_a
1     old_b     new_b
2     old_c     new_c
3     old_d     new_d
相关问题