如何在 pandas 上按键转置数据帧组?
How to do a transpose a dataframe group by key on pandas?
我的数据库中有这个 table,我需要一个 survey_id
的转置组
id answer survey_id question_number questionid
216 0.0 69 3 2.0
217 3.0 69 4 3.0
218 0.0 69 5 4.0
219 0.0 69 6 5.0
221 0.0 69 8 7.0
像这样:
Survey P01 P02 P03 P04 P05
69 1 1 2 2 1
单元格是答案,列是格式 "P{question_number}"
我正在使用 pandas 0.18.1.
我该怎么做?
您可以使用 pivot
, add_prefix
and reset_index
:
print (df.pivot(index='survey_id', columns='question_number', values='answer')
.add_prefix('P')
.reset_index())
question_number survey_id P3 P4 P5 P6 P8
0 69 0.0 3.0 0.0 0.0 0.0
我的数据库中有这个 table,我需要一个 survey_id
的转置组id answer survey_id question_number questionid
216 0.0 69 3 2.0
217 3.0 69 4 3.0
218 0.0 69 5 4.0
219 0.0 69 6 5.0
221 0.0 69 8 7.0
像这样:
Survey P01 P02 P03 P04 P05
69 1 1 2 2 1
单元格是答案,列是格式 "P{question_number}"
我正在使用 pandas 0.18.1.
我该怎么做?
您可以使用 pivot
, add_prefix
and reset_index
:
print (df.pivot(index='survey_id', columns='question_number', values='answer')
.add_prefix('P')
.reset_index())
question_number survey_id P3 P4 P5 P6 P8
0 69 0.0 3.0 0.0 0.0 0.0