如何在 pandas 上按键转置数据帧组? [英] How to do a transpose a dataframe group by key on pandas?
本文介绍了如何在 pandas 上按键转置数据帧组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的数据库中有这张表,我需要一个通过survey_id的转置组
I have this table from my database and I need a transpose group by 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}"
The cell is the answer and the column is format "P{question_number}"
我使用的是 Pandas 0.18.1.
I'm using pandas 0.18.1.
我该怎么做?
推荐答案
您可以使用 pivot
, add_prefix
和 reset_index
:
You can use 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
这篇关于如何在 pandas 上按键转置数据帧组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文