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

Python/Pandas按数值列分组统计分类列各分类出现次数问题

解决方案

方案1:使用pd.crosstab(最简洁)

你之前调用crosstab报错是因为传入的是列名字符串,而非实际的列数据,正确写法如下:

import pandas as pd
desiredDF = pd.crosstab(
    index=inputdf['UNIQUE_ID'],
    columns=inputdf['prediction']
).reset_index().rename_axis(columns=None)

运行后输出和你要求的结果完全一致,reset_index()是为了把UNIQUE_ID从索引变回普通列,rename_axis(columns=None)是去掉列名上方自动生成的prediction索引名。

方案2:使用pivot_table

你用pivot报错是因为pivot不支持重复的索引+列组合,换成支持自定义聚合函数的pivot_table即可:

desiredDF = inputdf.pivot_table(
    index='UNIQUE_ID',
    columns='prediction',
    values='pt_ID',
    aggfunc='count',
    fill_value=0
).reset_index().rename_axis(columns=None)

aggfunc='count'指定按计数聚合,fill_value=0把缺省的分类值设为0。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 14:24:05