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

Python使用groupby.agg结合value_counts实现多列分组百分比统计

实现方案

你无需逐个手写列的聚合规则,只需要两步调整即可实现需求,代码改动量极小:

  1. 把原本agg里的字符串'value_counts'替换为带normalize参数的匿名函数
  2. 用字典推导式自动生成所有非分组列的聚合配置,适配多列场景

完整可运行代码

import pandas as pd

df = pd.DataFrame({'Country': ['FR', 'FR', 'GER','GER'],
               'Foo': ['1', '2', '3', '1'],
               'Bar': ['5', '5', '3', '1'],
               'Baz': ['5', '1', '3', '4']})

# 定义分组列
group_col = 'Country'
# 自动生成所有非分组列的聚合规则,无需手动列名
agg_config = {col: lambda x: x.value_counts(normalize=True) for col in df.columns if col != group_col}

df2 = df.groupby(group_col).agg(agg_config)

可选优化

如果需要输出百分比格式(保留2位小数),直接修改匿名函数即可:

agg_config = {col: lambda x: x.value_counts(normalize=True).mul(100).round(2) for col in df.columns if col != group_col}

如果需要把索引转为普通列方便后续处理,后续追加一行即可:

df2 = df2.rename_axis([group_col, 'scale_value']).reset_index()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 19:21:01