pandas 如何在熊猫上按键转置数据帧组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39107512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do a transpose a dataframe group by key on pandas?
提问by Murilo Azevedo
I have this table from my database and I need a transpose group by survey_id
我的数据库中有这个表,我需要一个通过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
Like this:
像这样:
Survey P01 P02 P03 P04 P05
69 1 1 2 2 1
The cell is the answer and the column is format "P{question_number}"
单元格是答案,列格式为“P{question_number}”
I'm using pandas 0.18.1.
我正在使用Pandas 0.18.1。
How can I do that?
我怎样才能做到这一点?
回答by jezrael
You can use pivot
, add_prefix
and reset_index
:
您可以使用pivot
,add_prefix
和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