我有两个数据框:

>>> 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行,通常是在尝试合并数据框时发生的情况。感谢您的提示!

最佳答案

通过选择正确的列并使用.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

关于python - 在多列上合并两个 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57173240/

10-14 23:49