【问题标题】:How to do a transpose a dataframe group by key on pandas?如何在熊猫上按键转置数据框组?
【发布时间】:2016-08-24 02:11:12
【问题描述】:

我的数据库中有这张表,我需要一个按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}”

我正在使用熊猫 0.18.1。

我该怎么做?

【问题讨论】:

  • 你需要print (df.pivot(index='survey_id', columns='question_number', values='answer').add_prefix('P'))吗?
  • 谢谢!快到了.. 但是我怎样才能添加一个 Survey_id 作为第一列?我试图堆叠,但不完全是我需要的。重要的是它使用survey_id 与另一个表合并。

标签: python pandas dataframe analytics


【解决方案1】:

您可以使用pivotadd_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

【讨论】:

    猜你喜欢
    • 2018-05-11
    • 1970-01-01
    • 2022-12-16
    • 2018-07-19
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    相关资源
    最近更新 更多