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

如何在Pandas分组聚合中添加行列级别的占比计算?

问题:如何为聚合后的DataFrame添加占比字段?

原始DataFrame

Customer IDCountryIs True
123China1
124China1
125Colombia0
126Bangladesh0
127Bangladesh1
128China0
129Colombia0
130Bangladesh0
131Bangladesh0
132China1

目标透视表结果

CountryCount Customers% of population# TrueTrue Ratio (of Country)
Bangladesh440%125%
China440%375%
Colombia220%00%

计算逻辑说明

  • % of population:该国客户数占总客户数的比例(列级别计算)
  • True Ratio (of Country):该国Is True为1的数量占该国客户数的比例(行级别计算)

用户已完成基础聚合,代码如下:

Country = df.groupby('Country').agg(Count_Customers=('Customer ID', 'count'), TrueCount=('Is True','sum'))

(注:原代码列名存在空格与大小写不一致问题,此处调整为规范命名避免后续报错)


解决方案:添加占比字段

你可以直接在聚合后的DataFrame上扩展计算两个占比字段,完整代码如下:

# 基础聚合(修正列名格式)
Country = df.groupby('Country').agg(
    Count_Customers=('Customer ID', 'count'),
    TrueCount=('Is True','sum')
).reset_index()  # 将Country从索引转为普通列,方便后续操作

# 计算总客户数
total_customers = Country['Count_Customers'].sum()

# 添加% of population字段(转为百分比格式)
Country['% of population'] = (Country['Count_Customers'] / total_customers).apply(lambda x: f"{x:.0%}")

# 添加True Ratio (of Country)字段(转为百分比格式)
Country['True Ratio (of Country)'] = (Country['TrueCount'] / Country['Count_Customers']).apply(lambda x: f"{x:.0%}")

# 调整列名与顺序,匹配目标结果
Country = Country.rename(columns={'TrueCount': '# True'})
Country = Country[['Country', 'Count_Customers', '% of population', '# True', 'True Ratio (of Country)']]

# 可选:将Country重新设为索引
Country = Country.set_index('Country')

代码细节说明

  • reset_index():解决聚合后Country作为索引无法直接参与列计算的问题
  • f"{x:.0%}":将小数格式化为无小数位的百分比(如0.4→40%)
  • 最后通过列重命名与顺序调整,让输出完全匹配目标透视表结构

内容的提问来源于stack exchange,提问作者Hana

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 01:41:31