首页 > 解决方案 > 合并具有重复条目的列上的两个数据框

问题描述

我有两个看起来像的数据框:

col1   col2   
1      a
1      b
2      c

col1   col3   
1      d
1      e
3      f

如何合并它们(在 col1 上)以获得以下内容?

col1   col2   col3
1      a      d
1      b      e
2      c      Nan
3      Nan    f

我试过 pd.merge 但它没有给出预期的结果。

标签: pandasdataframe

解决方案


你可以这样做:

df1['key'] = df1.groupby('col1').cumcount()
df2['key'] = df2.groupby('col1').cumcount()

res = df1.merge(df2, on=['col1', 'key'], how='outer').drop('key', 1)
print(res)

输出

   col1 col2 col3
0     1    a    d
1     1    b    e
2     2    c  NaN
3     3  NaN    f

的想法groupby('col1').cumcount()是为重复的元素创建一个唯一的键。


推荐阅读