Pandas:根据分组获取每列的值计数

问题描述 投票:0回答:1

我的调查结果如下:

身份证 类别 问题1 问题2
1 A 同意 同意
2 A 不同意 同意
3 B 同意 同意
4 B 不同意 不同意

我想使用

pandas
来获取基于分组的值计数:

问题 问题1 问题1 问题2 问题2
价值 同意 不同意 同意 不同意
类别
A 1 1 2 0
B 1 1 0 1

我已经尝试过:

数据透视表

df.pivot_table(index='Category', 
   columns=["Question 1","Question 2"],
   aggfunc='size',
   fill_value=0)

但这并没有将问题分开,它使每个问题成为多级索引中的一层。

分组依据

好吧,

groupby
不起作用,因为它最后会生成一列。

谢谢!

python pandas group-by pivot-table
1个回答
0
投票

这样做:

import pandas as pd

data = {
    "ID": [1, 2, 3, 4],
    "Category": ["A", "A", "B", "B"],
    "Question 1": ["Agree", "Disagree", "Agree", "Disagree"],
    "Question 2": ["Agree", "Agree", "Agree", "Disagree"]
}
df = pd.DataFrame(data)

df_long = df.melt(id_vars=["ID", "Category"], value_vars=["Question 1", "Question 2"],
                  var_name="Question", value_name="Value")

result = df_long.pivot_table(index="Category", columns=["Question", "Value"], aggfunc="size", fill_value=0)

print(result)

这给出了

Question Question 1          Question 2         
Value         Agree Disagree      Agree Disagree
Category                                        
A                 1        1          2        0
B                 1        1          1        1
© www.soinside.com 2019 - 2024. All rights reserved.