【发布时间】:2022-06-13 23:57:49
【问题描述】:
我有一个包含 4 列的数据框:“ID”(客户)、“项目”、“层”(高/低)、“单位”(数字)。现在对于每个项目和每一层,我想找到总单位以及有多少客户为每一层购买至少一个项目。我这样做
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())
它给出了错误必须产生聚合值。如何修改我的代码以提供这些百分比?
【问题讨论】:
标签: pandas pandas-groupby aggregate percentage