You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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的结果完全符合预期:

groupcategorysalessales_pct
Azero5022.22
Afirst10044.44
Asecond7533.33
Afirst+second17577.78
Atotal225100.00

错误原因说明

  • 第一次计算错误:分母取了分组下所有category的销售额总和,包含了first+second和total的汇总值,导致整体分母偏大,占比结果偏低。
  • 第二次计算错误:仅为zero/first/second三类计算了分母,first+second和total行没有匹配到对应的分母值,所以返回NaN。

内容的提问来源于stack exchange,提问作者Jonas Palačionis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 05:06:03