我有这个数据框
df
month merchant sales
11 M1 10
11 M1 6
11 M2 7
12 M3 8
12 M4 9
12 M2 6
10 M5 11
我想按每个月对每个商人进行分组month, merchant
并取平均值(四舍五入到小数点后两位)sales
。
例如,如下所示,对month 11
,对M1
它可以计算((10+6)/(10+6+7))
用于M2
计算如下(7/(10+6+7))
。并且它们在特定月份的平均总和不应大于1。例如,month 11
它们的总和为0.69+0.30 ~ 1
。
我正在寻找的输出是:
month merchant sales average
11 M1 16 0.69
11 M2 7 0.30
12 M3 8 0.30
12 M4 9 0.39
12 M2 6 0.26
10 M5 11 1
我已经尝试过了,但是无法获得想要的东西。
df =df.groupby('month')[['merchant', 'sales']].agg(list).reset_index()
谁能在python pandas上提供帮助吗?
您可以按月分组并汇总销售额,然后按销售额除以:
df2 = df.groupby(['month', 'merchant'])['sales'].sum().reset_index()
df2['average'] = df2['sales'] / df2.groupby(['month'])['sales'].transform(sum)
df2
month merchant sales average
0 10 M5 11 1.000000
1 11 M1 16 0.695652
2 11 M2 7 0.304348
3 12 M2 6 0.260870
4 12 M3 8 0.347826
5 12 M4 9 0.391304
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句