计算Pandas Groupby百分比
我有一个带有4列的数据框:“ id”(clients),'item','tier'(高/低),“单位”(数字)。现在,对于每个项目和每个层,我都想找到总单位,以及每层至少一个项目的客户。我要做的
df.groupby(['item','tier']).agg(
ID_amount=('ID', 'size'),
total_units=('units', 'sum'))
item tier ID_amount total_units
100010001 high 83 178,871.00
low 153 1,450,986.00
100010002 high 722 10,452,778.00
low 911 5,505,136.00
100020001 high 400 876,490.00
low 402 962,983.00
100020002 high 4933 61,300,403.00
low 13759 1,330,932,723.00
100020003 high 15063 176,846,161.00
low 24905 288,232,057.00
是要拥有另一列代表“ total_units”列的百分比。当我尝试时,
df.groupby(['item','tier']).agg(
ID_amount=('ID', 'size'),
total_units=('units', 'sum'),
percen_units=('units', lambda x: 100*x/x.sum())
它给出了错误必须产生汇总值。如何修改代码以给我这些百分比?
I have a Dataframe with 4 columns: 'ID' (clients), 'item', 'tier' (high/low), 'units' (number). Now for each item and each tier I would like to find the total units and how many clients bough at least one item for each tier. I do this with
df.groupby(['item','tier']).agg(
ID_amount=('ID', 'size'),
total_units=('units', 'sum'))
item tier ID_amount total_units
100010001 high 83 178,871.00
low 153 1,450,986.00
100010002 high 722 10,452,778.00
low 911 5,505,136.00
100020001 high 400 876,490.00
low 402 962,983.00
100020002 high 4933 61,300,403.00
low 13759 1,330,932,723.00
100020003 high 15063 176,846,161.00
low 24905 288,232,057.00
What I would like is to have another column that represents the percentage of the 'total_units' column. When I try
df.groupby(['item','tier']).agg(
ID_amount=('ID', 'size'),
total_units=('units', 'sum'),
percen_units=('units', lambda x: 100*x/x.sum())
it gives the error Must produce aggregated value. How can I modify my code to give me those percentages?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想你想要这个:
I think you want this: