输出
我有作为垂直数据框架导出的调查数据。意思是一个人每次回答调查中的3个问题,他们的行将重复3次,除了问题的内容和他们的答案。我试图转置/枢轴此数据,以便所有3个问题都显示在一个唯一的列中,以便他们的回答也显示在每列中,而不是另一行,以及他们的详细信息,如ID,全名,位置等…
现在是这样的:
ID Full Name Location Question Multiple Choice Question Answers
12345 John Smith UK 1. It was easy to report my sickness. Agree
12345 John Smith UK 2. I felt ready to return from Quarantine. Neutral
12345 John Smith UK 3. I am satisfied with the adjustments made. Disagree
.. ... ... ... ...
67891 Jane Smith UK 1. It was easy to report my sickness. Agree
67891 Jane Smith UK 2. I felt ready to return from Quarantine. Agree
67891 Jane Smith UK 3. I am satisfied with the adjustments made. Agree
,这是我想要的:
ID Full Name Location 1. It was easy to report my sickness. 2. I was satisfied with the support I received. 3. I felt ready to return from Quarantine.
12345 John Smith UK Agree Neutral Disagree
67891 Jane Smith UK Agree Agree Disagree
目前我正试图使用此代码来获得我想要的输出,但我只能获得id和全名隔离而不复制和其他列只是显示为单独的行。
column_indices1 = [2,3,4]
df5 = df4.pivot_table(index = ['ID', 'Full Name'], columns = df4.iloc[:, column_indices1],
values = 'Multiple Choice Question Answer',
fill_value = 0)
概念
在这个场景中,我们应该考虑使用:pivot()
:主没有聚合可以处理非数字数据.
练习
准备数据data = {'ID':[12345,12345,12345,67891,67891,67891],
'Full Name':['John Smith','John Smith','John Smith','Jane Smith','Jane Smith','Jane Smith'],
'Location':['UK','UK','UK','UK','UK','UK'],
'Question':['Q1','Q2','Q3','Q1','Q2','Q3'],
'Answers':['Agree','Neutral','Disagree','Agree','Agree','Agree']}
df = pd.DataFrame(data=data)
df
输出
<表类>ID 全名 位置 问题答案 tbody><<tr>0 12345 约翰·史密斯道明> Q1 同意 112345 约翰·史密斯 英国 Q2 中性 212345 约翰·史密斯 英国 第三季度 不同意 3 67891 简·史密斯道明> Q1 同意 467891 简·史密斯道明> Q2 同意 567891 简·史密斯道明> 第三季度 同意 表类>