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

Pandas按col1分组统计col2唯一值数量,.value_counts输出不符合预期

解决方案

你需要在分组后调用nunique()方法统计去重后的数值个数,核心代码如下:

df.groupby('col1')['col2'].nunique()

方法说明

value_counts()的作用是统计分组下每个值的出现频次,无法直接得到去重后的总个数,nunique()是pandas专门用于统计序列中唯一值数量的方法,完全匹配需求。

完整测试代码

import pandas as pd

# 构造示例数据
data = {
    "col1": ["A", "A", "A", "B", "B", "c", "c", "c"],
    "col2": ["x", "y", "x", "x", "x", "x", "y", "z"]
}
df = pd.DataFrame(data)

# 统计结果
res = df.groupby('col1')['col2'].nunique()
print(res)

运行输出:

col1
A    2
B    1
c    3
Name: col2, dtype: int64

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 19:24:11