熊猫:结合不同大小的数据框架

时间:2014-12-18 21:53:44

标签: python pandas

我有2个数据框:

df1有白色产品的ID和数量

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

df2具有所有产品的ID和计数

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

df2的产品数量超过df1。我需要在df2中搜索df1中的产品,并将total_count列添加到df1:

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

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

2 个答案:

答案 0 :(得分:4)

只需在'product_id'列上执行左merge

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

答案 1 :(得分:1)

执行左联接/合并:

数据帧是:

enter image description here

左联接:

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

输出将如下所示:

enter image description here

相关问题