我有一个包含调查答案的数据框。每人回答3个问题。遗憾的是,数据帧的每一行对应于一个问题的答案,而不是人员条目。
如何重新格式化?
目前我有一个数据帧,其列设置为:
person_id
、person_name
、person_age
、question
、answer
。
此数据帧中的每个条目都是一个人对单个问题的回答。
我希望每个条目都是那个人的所有答案。所以列会更像
person_id
、person_name
、person_age
、question1
、question2
、question3
我没有太多的代码或错误要分享,因为我几乎不知道我应该如何解决这个问题,或者我应该如何使用该逻辑。
但是,而不是具有如下所示的数据帧:
001___james___20___Question1____maybe
001___james___20___Question2____sure
001___james___20___Question3____no
003___anne___22___Question2____sure
003___anne___22___Question3____no
我希望它看起来像:
001___james___20___maybe___sure___no
003___anne___22___[BLANK]___sure___no
更简单的方法是将unstack
与set index
一起使用:
df = pd.DataFrame([
[1,'James', 20, 'question 1', 'Yes'],
[1,'James', 20, 'question 2', 'No'],
[1,'James', 20, 'question 3', 'Maybe'],
[2,'Elle', 20, 'question 1', 'No'],
[2,'Elle', 20, 'question 2', 'Yes'],
[2,'Elle', 20, 'question 3', 'Maybe']
], columns = ['person_id', 'person_name','person_age','question', 'answer'])
df = df.set_index(['person_id','person_name','person_age','question'])['answer'].unstack()
输出
question question 1 question 2 question 3
person_id person_name person_age
1 James 20 Yes No Maybe
2 Elle 20 No Yes Maybe
步骤 1( 将数据帧拆分为"问题"和"____"(四个下划线,以便您有一个包含 3 列的数据帧。
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html
步骤2(使用 jtweed 提到的数据透视表功能。
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html