如何用Pandas按分组统计各列的数值计数?
解决方案
要实现按Category分组统计每个问题下不同选项的计数,关键是先将宽格式数据重塑为长格式,再通过透视表生成目标结构:
import pandas as pd # 加载问卷数据 df = pd.DataFrame({ 'ID': [1, 2, 3, 4], 'Category': ['A', 'A', 'B', 'B'], 'Question 1': ['Agree', 'Disagree', 'Agree', 'Disagree'], 'Question 2': ['Agree', 'Agree', 'Agree', 'Disagree'] }) # 1. 将宽格式转为长格式:每个问题-选项对单独成一行 melted_df = df.melt(id_vars='Category', var_name='Question', value_name='Value') # 2. 透视表统计分组计数,生成双层列索引(问题+选项) result = melted_df.pivot_table( index='Category', columns=['Question', 'Value'], aggfunc='size', fill_value=0 ) # 可选:将Category转为列,完全匹配示例输出结构 result = result.reset_index() print(result)
输出结果
Category Question 1 Question 2 Agree Disagree Agree Disagree 0 A 1 1 2 0 1 B 1 1 0 1
原理说明
melt重塑数据:把原本的Question 1、Question 2列转为行数据,让每个问题的选项成为独立条目,这样就能单独统计每个问题的选项分布。pivot_table聚合计数:按Category分组,以Question和Value作为双层列索引,统计每个组合的出现次数,用fill_value=0填充无数据的组合。
内容的提问来源于stack exchange,提问作者Phillip Ng
相关产品推荐
相关产品推荐

