如何在Python的Pivot表中循环所有问题?
我正在研究调查,数据看起来像这样:
ID Q1 Q2 Q3 Gender Age Dep Ethnicity
001 Y N Y F 22 IT W
002 N Y Y M 35 HR W
003 Y N N F 20 IT A
004 Y N Y M 54 OPRE B
005 Y N Y M 42 OPRE B
现在,我想添加两个索引dep和性别来创建一个表:
Question Dep Response #M #F %M %F
Q1 IT Y 0 2 0 100
IT N 0 0 0 0
HR Y 0 0 0 0
HR N 1 0 100 0
OPRE Y 2 0 100 0
OPRE N 0 0 0 0
Q2 IT Y 0 0 0 0
IT N 0 2 0 100
HR Y 1 0 100 0
HR N 0 0 0 0
OPRE Y 0 0 0 0
OPRE N 2 0 100 0
Q3 ......
我的代码是这样的:
df2=df[['ID','Gender','Dep', 'Q1', 'Q2', 'Q3' ]].melt(
['ID','Gender', 'Dep'], var_name='question', value_name='response').pivot_table(
index=[ 'question','Dep','response'],
columns='Gender',
values='ID', aggfunc='count').fillna(0)
如果我有更多问题,我不想复制并粘贴数据框中的所有Q,而是想有一个可以解决所有问题的循环。 谁能帮忙?
I am working on a survey and the data looks like this:
ID Q1 Q2 Q3 Gender Age Dep Ethnicity
001 Y N Y F 22 IT W
002 N Y Y M 35 HR W
003 Y N N F 20 IT A
004 Y N Y M 54 OPRE B
005 Y N Y M 42 OPRE B
Now, I'd like to add two indexes Dep and Gender to create a table like:
Question Dep Response #M #F %M %F
Q1 IT Y 0 2 0 100
IT N 0 0 0 0
HR Y 0 0 0 0
HR N 1 0 100 0
OPRE Y 2 0 100 0
OPRE N 0 0 0 0
Q2 IT Y 0 0 0 0
IT N 0 2 0 100
HR Y 1 0 100 0
HR N 0 0 0 0
OPRE Y 0 0 0 0
OPRE N 2 0 100 0
Q3 ......
My codes are like this:
df2=df[['ID','Gender','Dep', 'Q1', 'Q2', 'Q3' ]].melt(
['ID','Gender', 'Dep'], var_name='question', value_name='response').pivot_table(
index=[ 'question','Dep','response'],
columns='Gender',
values='ID', aggfunc='count').fillna(0)
If I have more questions, I don't want to copy and paste all the Qs in the dataframe, instead I'd like to have a loop which can go over all the questions.
Can anyone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
iiuc,您可以使用
pd.wide_to_long
:输出:
IIUC, you can use
pd.wide_to_long
:Output:
这是一种通过按照您进行的融化,将响应转换为pd.categorical,然后将
Here's a way to keep the 0 rows by melting to long form as you're doing, converting the Response to a pd.Categorical, and then groupbing and aggregating