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

Pandas调用value_counts()统计时如何同时输出各类别占比百分比

Pandas value_counts 同时输出计数与占比的实现方法

你可以通过拼接计数序列和归一化后的占比序列快速实现需求,以下是可直接复用的代码:

方法1:分步骤实现(可读性更高)

# 1. 统计各分类计数
count_ser = df['goal'].value_counts()
# 2. 计算占比,转换为带%、逗号为小数分隔符的格式
pct_ser = (count_ser / count_ser.sum() * 100).round(1).astype(str).str.replace('.', ',') + '%'
# 3. 拼接为结果表
result = pd.concat([count_ser, pct_ser], axis=1, keys=['count', 'percentage'])

输出的result格式如下:

count percentage
0   1000      66,7%
1    500      33,3%

方法2:一行代码实现

如果你偏好更短的写法,可直接链式调用完成:

result = df['goal'].value_counts().to_frame('count').assign(percentage=lambda x: (x['count']/x['count'].sum()*100).round(1).astype(str).str.replace('.', ',') + '%')

提示:如果不需要逗号作为小数分隔符,去掉.str.replace('.', ',')这段即可;调整round()内的数字可以修改百分比保留的小数位数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 06:24:04