如何使用Python进行循环执行内部功能?
我正在进行调查,数据看起来像:
ID Q1 Q2 Q3 Gender Age Dept
001 Y N Y F 22 IT
002 N Y Y M 35 HR
003 Y N N F 20 IT
004 Y N Y M 54 OPRE
005 Y N Y M 42 OPRE
代码是:
out = df.pivot_table(index='Q1', columns=['Gender'], values=['ID'], aggfunc='count', fill_value=0)
out = (out.join(out[['ID']].div(out['ID'].sum(axis=1).values, axis=0)
.mul(100)
.rename(columns={'ID':'%Respondents'})))
out
我创建的表是这样的:
Q1 #Res %Rep
M F M F
Y 2 2 50 50
N 1 0 100 0
但是我希望所有问题结果都执行,就像
Q1 #Res %Rep
M F M F
Y 2 2 50 50
N 1 0 100 0
Q2 #Res %Rep
M F M F
Y 1 0 100 0
N 2 2 50 50
Q3 #Res %Rep
M F M F
Y 2 2 50 50
N 0 1 0 100
我想编写创建创建的函数桌子,并使用一个用于循环来解决问题。谁能帮忙?
I am working on a survey and the data looks like this:
ID Q1 Q2 Q3 Gender Age Dept
001 Y N Y F 22 IT
002 N Y Y M 35 HR
003 Y N N F 20 IT
004 Y N Y M 54 OPRE
005 Y N Y M 42 OPRE
The codes are:
out = df.pivot_table(index='Q1', columns=['Gender'], values=['ID'], aggfunc='count', fill_value=0)
out = (out.join(out[['ID']].div(out['ID'].sum(axis=1).values, axis=0)
.mul(100)
.rename(columns={'ID':'%Respondents'})))
out
And the table I created is like this:
Q1 #Res %Rep
M F M F
Y 2 2 50 50
N 1 0 100 0
But I'd like all the Questions results be at one execution, like
Q1 #Res %Rep
M F M F
Y 2 2 50 50
N 1 0 100 0
Q2 #Res %Rep
M F M F
Y 1 0 100 0
N 2 2 50 50
Q3 #Res %Rep
M F M F
Y 2 2 50 50
N 0 1 0 100
I want to write a function of creating the tables, and use a for loop to go over the questions. Can anyone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一种方法
Here is one way to do it
您可以使用此功能:
image
You could use this function:
Image