pandas分组计算子类别百分比时处理汇总类得到正确占比的问题
解决方案
你要的计算逻辑可以通过提取每个分组下category=total对应的销售额作为统一分母实现,代码如下:
import pandas as pd # 原始DataFrame df = pd.DataFrame({'group':['A','A','A','A','A', 'B','B','B','B','B', 'C','C','C','C','C'], 'category': ['zero','first', 'second', 'first+second', 'total', 'zero', 'first', 'second', 'first+second', 'total', 'zero','first', 'second', 'first+second', 'total'], 'sales': [50,100,75,175,225, 5,10,15,25,30, 1000,2000,3000,3000,4000]}) # 构造分组与对应total销售额的映射关系 group_total_map = df[df['category'] == 'total'].set_index('group')['sales'] # 计算占比,可根据需要调整保留的小数位数 df['sales_pct'] = (df['sales'] / df['group'].map(group_total_map) * 100).round(2)
结果验证
计算后group=A的结果完全符合预期:
| group | category | sales | sales_pct |
|---|---|---|---|
| A | zero | 50 | 22.22 |
| A | first | 100 | 44.44 |
| A | second | 75 | 33.33 |
| A | first+second | 175 | 77.78 |
| A | total | 225 | 100.00 |
错误原因说明
- 第一次计算错误:分母取了分组下所有
category的销售额总和,包含了first+second和total的汇总值,导致整体分母偏大,占比结果偏低。 - 第二次计算错误:仅为
zero/first/second三类计算了分母,first+second和total行没有匹配到对应的分母值,所以返回NaN。
内容的提问来源于stack exchange,提问作者Jonas Palačionis
相关产品推荐
相关产品推荐

