简体   繁体   English

在pandas中水平和垂直组合多个pivot表

[英]Combining multiple pivot tables horizontally and vertically in pandas

I have a dataset that looks like this:我有一个如下所示的数据集:

raw data原始数据

and I need to get this output: desired output我需要得到这个 output:想要的 output

Is using pivot tables (in python pandas) first for each Q, then appending over each column, and then merging the resulting dataframes for reach Q the best way to do it?是否首先为每个 Q 使用 pivot 表(在 python 熊猫中),然后附加到每列,然后合并生成的数据帧以达到 Q 的最佳方法? Any suggestion on how to do that to get the right format?关于如何获得正确格式的任何建议?

Try this:尝试这个:

df1 = pd.melt(df, id_vars=["gender",'region'], value_vars=['q1','q2'], value_name='ques')
df2 = pd.melt(df1, id_vars='ques', value_vars=["gender",'region'], value_name='col')
df3 = pd.pivot_table(df2,index='ques',columns=['col'], aggfunc='count').fillna(0)
print(df3)

    col                             EE   LA   WE female male
ques                                                         
1'Agree + strongly agree            5.0  1.0  4.0    6.0  4.0
2'neither agree nor disagree        0.0  0.0  1.0    1.0  0.0
3'disagree + strongly disagree      0.0  3.0  0.0    3.0  0.0
no                                  5.0  3.0  4.0    8.0  4.0
yes                                 0.0  1.0  1.0    2.0  0.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM