如何按Person统计各Choice的计数与占比并生成指定格式DataFrame
问题描述
给定如下Pandas DataFrame:
person choice 0 A 1 1 A 2 2 A 1 3 B 3 4 B 3 5 B 2 6 B 1 7 C 2
需要实现:
- 统计每个
person对应各choice的计数,生成包含计数与总数的中间结果 - 基于中间结果计算各
choice的占比,最终结果需便于排序、绘图及进一步分析
中间计数结果示例:
person choice_1_count choice_2_count choice_3_count total A 2 1 0 3 B 1 1 2 4 C 0 1 0 1
最终占比结果示例:
person choice_1_percent choice_2_percent choice_3_percent A 66.67 33.33 0.00 B 25.00 25.00 50.00 C 0.00 100.00 0.00
解决方法
1. 生成中间计数结果
利用pd.crosstab()实现交叉统计,再添加总数列:
import pandas as pd # 构造原始数据 df = pd.DataFrame({ 'person': ['A', 'A', 'A', 'B', 'B', 'B', 'B', 'C'], 'choice': [1, 2, 1, 3, 3, 2, 1, 2] }) # 交叉统计各person的choice数量 count_df = pd.crosstab(df['person'], df['choice']).reset_index() # 重命名列名以匹配要求格式 count_df.columns = ['person', 'choice_1_count', 'choice_2_count', 'choice_3_count'] # 计算每个person的总选择数 count_df['total'] = count_df.iloc[:, 1:4].sum(axis=1) print(count_df)
运行后即可得到符合要求的中间计数表。
2. 生成最终占比结果
基于计数表计算占比,保留两位小数,最后整理列:
# 复制计数表用于计算占比 percent_df = count_df.copy() # 计算各choice的占比(百分比形式) percent_df['choice_1_percent'] = round((percent_df['choice_1_count'] / percent_df['total']) * 100, 2) percent_df['choice_2_percent'] = round((percent_df['choice_2_count'] / percent_df['total']) * 100, 2) percent_df['choice_3_percent'] = round((percent_df['choice_3_count'] / percent_df['total']) * 100, 2) # 筛选出需要的列 percent_df = percent_df[['person', 'choice_1_percent', 'choice_2_percent', 'choice_3_percent']] print(percent_df)
最终得到的宽表格式非常适合后续排序(如percent_df.sort_values('choice_1_percent', ascending=False))、绘图(如用seaborn绘制分组柱状图)和其他分析操作。
内容的提问来源于stack exchange,提问作者Ivo Treszka
相关产品推荐
相关产品推荐

