Python 熊猫用几乎相同的值求和行
我试图组织一个电子表格来跟踪项目流程 目标是对具有相同操作、价格和日期的项目的金额列求和 例如:Python 熊猫用几乎相同的值求和行,python,pandas,Python,Pandas,我试图组织一个电子表格来跟踪项目流程 目标是对具有相同操作、价格和日期的项目的金额列求和 例如: Item action amount price date socks buy 10 $20 5/1 socks buy 5 $20 5/1 socks sell 5 $20 5/1 shoes sell 7 $25 5/2 shoes sell 2 $25 5/2 shoes sell
Item action amount price date
socks buy 10 $20 5/1
socks buy 5 $20 5/1
socks sell 5 $20 5/1
shoes sell 7 $25 5/2
shoes sell 2 $25 5/2
shoes sell 8 $30 5/2
--会变成--
使用pandas是否可以这样做?使用将数据框分组到'Item'、'action'、'price'、'date'
上,然后使用agg函数计算每个分组的金额
列的总和,然后使用重置分组数据框的索引:
df = df.groupby(['Item', 'action', 'price', 'date']).sum().reset_index().reindex(columns=df.columns)
结果:
# print(df)
Item action amount price date
0 shoes sell 9 $25 5/2
1 shoes sell 8 $30 5/2
2 socks buy 15 $20 5/1
3 socks sell 5 $20 5/1
谢谢你的回答。你能详细说明一下.sum()之后的函数是做什么的吗?“.reset_index().reindex(columns=df.columns)”@llssff
groupby.sum
计算组值之和在本例中,它计算金额
列之和,reset_index
用于重置数据帧的索引。在这里,我使用了reindex,它是完全可选的,如果列的顺序不重要,您可以跳过它。尽管我建议你阅读熊猫文档以了解更多信息。
# print(df)
Item action amount price date
0 shoes sell 9 $25 5/2
1 shoes sell 8 $30 5/2
2 socks buy 15 $20 5/1
3 socks sell 5 $20 5/1