【问题标题】:Pandas: combine data frames of different sizesPandas:组合不同大小的数据框
【发布时间】:2015-02-17 19:38:51
【问题描述】:

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

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

【问题讨论】:

  • 不清楚为什么你认为左合并会产生一个巨大的文件,通过对产品 id 执行左合并你说你只对 product_id 列中的匹配感兴趣

标签: python pandas


【解决方案1】:

只需在“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

【讨论】:

  • 我完全搞砸了数据框,并合并到错误的数据框上。谢谢!
【解决方案2】:

执行左连接/合并:

数据框是:

左连接:

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

输出将如下所示:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    • 1970-01-01
    相关资源
    最近更新 更多