如何将数据切片并创建引用其他列值的新列中的Python中的Pivot?
我正在进行调查,数据看起来像这样:
ID Q1 Q2 Q3 Gender Age Dep Ethnicity
001 Y N Y M 22 IT W
002 N Y Y M 35 HR W
003 Y N N M 20 IT A
004 Y N Y M 54 OPRE B
005 Y N Y M 42 OPRE B
现在,我想添加群体种族和性别来创建一个表:
Question Dep Response #White Man #Diverse Man %White Man %Diverse Man
Q1 IT Y 1 1 50 50
IT N 0 0 0 0
HR Y 0 0 0 0
HR N 1 0 100 0
OPRE Y 0 2 0 100
OPRE N 0 0 0 0
Q2 IT Y 0 0 0 0
IT N 1 1 50 50
HR Y 1 0 100 0
HR N 0 0 0 0
OPRE Y 0 0 0 0
OPRE N 0 2 0 0
Q3 ......
我的代码是这样的:
df['White Man'] = df[df[Gender] == 'Man']&df[Ethnicity] = 'White']
但是我不知道是否包含功能是否python。我上面做的只是过滤,它不会在结果中添加1个。 谁能帮忙?
I am working on a survey and the data looks like this:
ID Q1 Q2 Q3 Gender Age Dep Ethnicity
001 Y N Y M 22 IT W
002 N Y Y M 35 HR W
003 Y N N M 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 group ethnicity and Gender to create a table like:
Question Dep Response #White Man #Diverse Man %White Man %Diverse Man
Q1 IT Y 1 1 50 50
IT N 0 0 0 0
HR Y 0 0 0 0
HR N 1 0 100 0
OPRE Y 0 2 0 100
OPRE N 0 0 0 0
Q2 IT Y 0 0 0 0
IT N 1 1 50 50
HR Y 1 0 100 0
HR N 0 0 0 0
OPRE Y 0 0 0 0
OPRE N 0 2 0 0
Q3 ......
My codes are like this:
df['White Man'] = df[df[Gender] == 'Man']&df[Ethnicity] = 'White']
But I don't know if there is a Contains function in Python or not. What I did above is only filtering, it will not add 1 in the results.
Can anyone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定这是解决您的问题的最有效方法,但是它至少可以
从这里看到它可以完全解决您想要的东西。
I'm not sure this is the most efficient way of solving your problem, but it solves it as far as I can see
At least from here it should be easy for you to fully reach what you want