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

如何让pandas的value_counts输出带Age、Count表头的统计结果?

解决DataFrame Age列统计结果带表头的问题

我懂你的需求——用value_counts()统计Age列分布时,默认输出的Series没有你想要的Age和Count表头。问题根源在于value_counts()返回的是Series对象,它只有索引(对应Age的分组)和值(对应计数),自然不会显示列名。下面给你两种简单可行的解决方法:

方法一:转成DataFrame并设置列名(推荐)

直接把Series转换成DataFrame,同时重置索引并指定列名,输出就会自带规范表头:

df.columns=['index','District','Group','Age','Holders','Claims']
df.set_index('index',inplace=True)

# 核心修改部分
df_count = df.Age.value_counts().reset_index()
df_count.columns = ['Age', 'Count']

print(df_count)

输出结果如下:

Age  Count
0  25-29     16
1    <25     16
2  30-35     16
3    >35     16

方法二:更紧凑的链式调用

用rename_axis和reset_index一步完成索引命名和列名设置,写法更简洁:

df.columns=['index','District','Group','Age','Holders','Claims']
df.set_index('index',inplace=True)

df_count = df.Age.value_counts().rename_axis('Age').reset_index(name='Count')

print(df_count)

这个方法和方法一效果完全一致,只是代码更凝练。

如果你想完全匹配示例格式(含末尾dtype信息)

如果一定要保留示例里的Name: Age, dtype: int64行,可以手动拼接输出内容:

df.columns=['index','District','Group','Age','Holders','Claims']
df.set_index('index',inplace=True)

df_count = df.Age.value_counts()
# 先打印自定义表头
print("Age Count")
# 打印统计结果(隐藏Series默认索引名)
print(df_count.to_string(name=False))
# 手动添加dtype信息
print(f"Name: Age, dtype: {df_count.dtype}")

这样输出就和你给出的示例完全一致:

Age Count
25-29 16
<25 16
30-35 16
>35 16
Name: Age, dtype: int64

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:06:00