如何在Pandas分组聚合中添加行列级别的占比计算?
问题:如何为聚合后的DataFrame添加占比字段?
原始DataFrame
| Customer ID | Country | Is True |
|---|---|---|
| 123 | China | 1 |
| 124 | China | 1 |
| 125 | Colombia | 0 |
| 126 | Bangladesh | 0 |
| 127 | Bangladesh | 1 |
| 128 | China | 0 |
| 129 | Colombia | 0 |
| 130 | Bangladesh | 0 |
| 131 | Bangladesh | 0 |
| 132 | China | 1 |
目标透视表结果
| Country | Count Customers | % of population | # True | True Ratio (of Country) |
|---|---|---|---|---|
| Bangladesh | 4 | 40% | 1 | 25% |
| China | 4 | 40% | 3 | 75% |
| Colombia | 2 | 20% | 0 | 0% |
计算逻辑说明
% 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
相关产品推荐
相关产品推荐

