根据python pandas中的行值合并两个数据框 [英] Merging two data frames based on row values in python pandas

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

问题描述

我在熊猫中有两个数据框,如下所示:

I have two dataframes in pandas like the following:

df1:                                 df2:

      Column1  Column2  Column3           ColumnA  ColumnB ColumnC
    0    a        x        x            0    c        y       y
    1    c        x        x            1    e        z       z
    2    e        x        x            2    a        s       s
    3    d        x        x            3    d        f       f

我现在要做的是将Column1与ColumnA进行比较,并将df2的行附加到df1的行中,这些行在Column1中的值与df2在Column A中的值相同,以便结果如下所示:

What I want to do now is to compare Column1 with ColumnA and append the rows of df2 to the rows of df1 that have the same value in Column1 as df2 has in Column A, so that the result looks like this:

df1:
    Column1  Column2  Column3  ColumnB  ColumnC
  0    a        x        x        s        s
  1    c        x        x        y        y
  2    e        x        x        z        z
  3    d        x        x        f        f

我当时正在考虑使用pandas .groupby()函数并将第1列和第A列设置为键,比较它们,然后合并键相同的分组对象,但是我找不到一种比较键的有效方法2个数据帧的分组对象的集合.有谁知道如何做到这一点?

I was thinking of using pandas .groupby() function and set the columns 1 and A as keys,compare them and then merge the grouped objects where the keys are identical, but I could not find an efficient way to compare the keys of grouped objects of 2 dataframes. Does anybody have a good idea how to do this?

推荐答案

您可以指定要

You can specify which columns to merge for the lhs and rhs dfs:

In [159]:
df1.merge(df2, left_on='Column1', right_on='ColumnA')

Out[159]:
  Column1 Column2 Column3 ColumnA ColumnB ColumnC
0       a       x       x       a       s       s
1       c       x       x       c       y       y
2       e       x       x       e       z       z
3       d       x       x       d       f       f

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

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