在多列上合并两个熊猫数据框

时间:2019-07-23 23:05:36

标签: python pandas merge

我有两个数据框:

>>> df1
[Output]: col1   col2   col3   col4
           a     abc     10    str1
           b     abc     20    str2
           c     def     20    str2
           d     abc     30    str2

>>> df2
[Output]: col1   col2   col3   col5   col6
           d     abc     30    str6    47
           b     abc     20    str5    66
           c     def     20    str7    53
           a     abc     10    str5    21

以下是我要生成的内容:

>>> df_merged
[Output]: col1   col2   col5
           a     abc    str5
           b     abc    str5 
           c     def    str7
           d     abc    str6

我不想生成多于4行,这通常是我尝试合并数据帧时发生的情况。感谢您的提示!

2 个答案:

答案 0 :(得分:1)

df_merged = pd.DataFrame()
df_merged['col1'] = df1['col1'][0:3]
df_merged['col2'] = df1['col2'][0:3]
df_merged['col5'] = df2['col5'][0:3]

这对您要寻找的内容有帮助吗?

答案 1 :(得分:1)

通过子选择正确的列并使用.mergecol1作为关键列来使用col2

df1[['col1', 'col2']].merge(df2[['col1', 'col2', 'col5']], on=['col1', 'col2'])

  col1 col2  col5
0    a  abc  str5
1    b  abc  str5
2    c  def  str7
3    d  abc  str6