Pandas - Finding percent contributed by each group

雨燕双飞 提交于 2021-02-05 09:26:18

问题


I am trying to find the percentage contribution made by each date group. Given below is how my data looks like.

Expecting to find contribution of each product for a given date.

date, product, quantity
2020-01, prod_a, 100
2020-01, prod_b, 200
2020-01, prod_c, 20
2020-01, prod_d, 50
2020-02, prod_a, 30
2020-02, prod_b, 30
2020-02, prod_c, 40

My expected output would be as below:

date, product, quantity, prct_contributed
2020-01, prod_a, 100, 27%
2020-01, prod_b, 200, 54%
2020-01, prod_c, 20, 5%
2020-01, prod_d, 50, 14%
2020-02, prod_a, 30, 30%
2020-02, prod_b, 30, 30%
2020-02, prod_c, 40, 40%

回答1:


Use groupby().transform():

df['quantity'] / df.groupby('date')['quantity'].transform('sum')


来源:https://stackoverflow.com/questions/65597313/pandas-finding-percent-contributed-by-each-group

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!