在多列上合并两个 pandas 数据框 [英] Merging two pandas dataframes on multiple columns

查看:47
本文介绍了在多列上合并两个 pandas 数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数据框:

<预><代码>>>>df1[输出]:col1 col2 col3 col4a abc 10 str1b abc 20 str2c def 20 str2d abc 30 str2>>>df2[输出]:col1 col2 col3 col5 col6d abc 30 str6 47b abc 20 str5 66c def 20 str7 53a abc 10 str5 21

以下是我想要生成的:

<预><代码>>>>df_merged[输出]:col1 col2 col5abc str5b abc str5c def str7d abc str6

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

解决方案

通过子选择正确的列并使用 col1 使用 .merge &col2 作为关键列:

df1[['col1', 'col2']].merge(df2[['col1', 'col2', 'col5']], on=['col1', 'col2'])col1 col2 col50 a abc str51 b abc str52 c def str73 d abc str6

I have two dataframes:

>>> 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

Below is what I want to generate:

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

I don't want to generate more than 4 rows and that is usually what happens when I try to merge the dataframes. Thanks for the tips!

解决方案

Use .merge by subselecting the correct columns and using col1 & col2 as key columns:

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

这篇关于在多列上合并两个 pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆