gpt4 book ai didi

python - 使用 Groupby 对象进行计算 Pandas

转载 作者:太空宇宙 更新时间:2023-11-04 09:49:11 25 4
gpt4 key购买 nike

我想检索两个 groupby 系列对象并相互计算。

下面的系列对象:

Cost
ID yy
312 13 102429.610000
361 15 170526.000000
373 14 400000.000000
403 13 165000.000000
14 165000.000000
15 183558.720000
16 133763.760980
17 121301.930160

Percentage
ID yy
312 13 21.687500
361 15 33.181818
373 14 12.439024
403 13 22.966667
14 22.966667
15 24.142857
16 23.333333
17 36.666667

cost=df.groupby(['ID', 'yy'])['cost']
percentage=df.groupby(['ID', 'yy'])['percentage']

我主要想计算成本 * 百分比。

这是如何正确完成的?错误是“* 不支持的操作数类型:‘SeriesGroupBy’和‘SeriesGroupBy’”。

最佳答案

您使用的 groupby 没有任何聚合函数,它返回为 groupby 对象,而不是一个系列。

你需要

cost = df1.set_index(['ID', 'yy'])['cost']
pct = df2.set_index(['ID', 'yy'])['cost']
cost.mul(pct/100)

ID yy
312 13 22214.421669
361 15 56583.626963
373 14 49756.096000
403 13 37895.000550
14 37895.000550
15 44316.319281
16 31211.543783
17 44477.374796

关于python - 使用 Groupby 对象进行计算 Pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48551370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com