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

两盒软妹~` 提交于 2020-01-04 11:03:06

问题


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 

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}"

I'm using pandas 0.18.1.

How can I do that?


回答1:


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


来源:https://stackoverflow.com/questions/39107512/how-to-do-a-transpose-a-dataframe-group-by-key-on-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!