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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:52:58  来源:igfitidea点击:

How to do a transpose a dataframe group by key on pandas?

pythonpandasdataframeanalytics

提问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_prefixand reset_index:

您可以使用pivot,add_prefixreset_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