pandas - 根据列的组合添加两个表的值
问题描述
我有两张桌子:
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_id
和cloud
. 我正在寻找的结果是:
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 多列具有更多约束。一些列仅在cloud
isAzure
时才具有值,而其他列仅在cloud
isAzure
或时才具有值GCP
有没有一种干净的方法来添加df1
和df2
?
解决方案
您还可以使用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
推荐阅读
- android - 如何在“自定义”工具栏的菜单项上使用 setOnClickListner?
- swift - 下拉表格视图 - 斯威夫特
- flutter - 如何使用 firebase_auth 和 provider 检测身份验证更改
- java - 仅使用一个 if 条件找到两个中的最大数?
- pandas - 如何在循环 Python 中修改数据框列表元素?
- wordpress - 使用 Wordpress 中的 add_rewrite_rule 将 GET 变量从 url 转换为路径
- php - 重用的对象不会调用`__destruct`?
- java - 从 JAR 读取音频时出现 NullPointerException
- html - HTML嵌套表不嵌套
- java - 片段内的选项卡式布局无法正常工作