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
相关产品推荐
相关产品推荐

