Pandas:组合不同大小的数据框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27556377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:46:30  来源:igfitidea点击:

Pandas: combine data frames of different sizes

pythonpandas

提问by Anastasia

I have 2 data frames:

我有 2 个数据框:

df1 has ID and count of white products

df1 有白色产品的 ID 和数量

product_id, count_white
12345,4
23456,7
34567,1

df2 has IDs and counts of all products

df2 拥有所有产品的 ID 和数量

product_id,total_count
0009878,14
7862345,20
12345,10
456346,40
23456,30
0987352,10
34567,90

df2 has more products than df1. I need to search df2 for products that are in df1 and add total_count column to df1:

df2 的产品比 df1 多。我需要在 df2 中搜索 df1 中的产品并将 total_count 列添加到 df1:

product_id,count_white,total_count
12345,4,10
23456,7,30
34567,1,90

I could do a left merge, but I would end up with a huge file. Is there any way to add specific rows from df2 to df1 using merge?

我可以进行左合并,但最终会得到一个巨大的文件。有没有办法使用合并将特定行从 df2 添加到 df1?

采纳答案by EdChum

Just perform a left mergeon 'product_id' column:

只需merge在“product_id”列上执行左操作:

In [12]:

df.merge(df1, on='product_id', how='left')
Out[12]:
   product_id  count_white  total_count
0       12345            4           10
1       23456            7           30
2       34567            1           90

回答by Yogesh

Perform left join/merge:

执行左连接/合并:

Data frames are:

数据框是:

enter image description here

在此处输入图片说明

left join:

左连接:

df1=df1.merge(df2, on='product_id', how='left') 

The output will look like this:

输出将如下所示:

enter image description here

在此处输入图片说明