比较两个大小不同的 pandas 数据框 [英] Compare two pandas dataframe with different size

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

问题描述

我有一个具有这种结构的大熊猫数据框:

I have one massive pandas dataframe with this structure:

df1:
    A   B
0   0  12
1   0  15
2   0  17
3   0  18
4   1  45
5   1  78
6   1  96
7   1  32
8   2  45
9   2  78
10  2  44
11  2  10

还有第二个,像这样较小:

And a second one, smaller like this:

df2
   G   H
0  0  15
1  1  45
2  2  31

我想按照以下规则在我的第一个数据框中添加一列:column df1.C = df2.H when df1.A == df2.G

I want to add a column to my first dataframe following this rule: column df1.C = df2.H when df1.A == df2.G

我设法通过for循环来做到这一点,但是数据库庞大且代码运行非常缓慢,因此我正在寻找Pandas方式或numpy来实现.

I manage to do it with for loops, but the database is massive and the code run really slowly so I am looking for a Pandas-way or numpy to do it.

非常感谢,

鲍里斯

推荐答案

您可能想使用合并:

df=df1.merge(df2,left_on="A",right_on="G")

将为您提供一个包含3列的数据框,但第三个名称为H

will give you a dataframe with 3 columns, but the third one's name will be H

df.columns=["A","B","C"]

然后将为您提供所需的列名

will then give you the column names you want

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

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