首页 > 解决方案 > 根据列的组合添加两个表的值

问题描述

我有两张桌子:

df1 = pd.DataFrame({
    "c_id": [2000,3000,3000], 
    "cloud":["GCP","GCP","Azure"], 
    "invoice":[100,100,300]
})

c_id    cloud   invoice
2000    GCP     100
3000    GCP     100
3000    Azure   300

df2 = pd.DataFrame({
    "c_id": [1000,2000,2000,3000,3000], 
    "cloud":["Azure","GCP","Azure","AWS","Azure"], 
    "invoice":[200,200,300,100,100]
})

c_id    cloud   invoice
1000    Azure   200
2000    GCP     200
2000    Azure   300
3000    AWS     100
3000    Azure   100

我想根据列c_idcloud. 我正在寻找的结果是:

c_id    cloud   invoice
1000    Azure   200
2000    Azure   300
2000    GCP     300
3000    AWS     100
3000    Azure   400
3000    GCP     100

在我的示例中,我只显示了 column invoice。在我的实际数据集中,实际上有 40 多列具有更多约束。一些列仅在cloudisAzure时才具有值,而其他列仅在cloudisAzure或时才具有值GCP

有没有一种干净的方法来添加df1df2

标签: pandas

解决方案


您还可以使用df.set_index

df1.set_index(['c_id', 'cloud']).add(df2.set_index(['c_id', 'cloud']), fill_value=0).reset_index()

输出:

    c_id  cloud  invoice
0  1000  Azure   200.00
1  2000  Azure   300.00
2  2000    GCP   300.00
3  3000    AWS   100.00
4  3000  Azure   400.00
5  3000    GCP   100.00

推荐阅读