【问题标题】:How to pivot a dataframe with pandas so variable columns become rows?如何使用 pandas 旋转数据框,以便可变列变为行?
【发布时间】:2018-08-17 12:49:42
【问题描述】:

我目前有以下数据框:

当前df

            type       part number    part description  waiting period  hours  
0   service item     SOME-X1R-1807                SOME           1 day     24  
1     CONSUMABLE   RANDOM-462-1171         DESCRIPTION          6 days    144  
2          wheel      PART-7W-2326           ABOUT THE          7 days    168  
3           tyre    NUMBER-1R-0762      PARTS FROM THE          8 days    192  
4          other    NUMBER-XL-0747     PREVIOUS COLUMN          9 days    216

我想旋转表格,得到以下结果:

预计df:

                        SOME-X1R-1807    RANDOM-462-1171    PART-7W-2326     NUMBER-1R-076     NUMBER-XL-0747 
part description                 SOME        DESCRIPTION       ABOUT THE    PARTS FROM THE    PREVIOUS COLUMN
            type         service item         CONSUMABLE           wheel              tyre              other
  waiting period                1 day             6 days          7 days            8 days             9 days 
           hours                   24                144             168               192                216

问题:

如何旋转数据框以获取此输出?

我尝试过的事情:

【问题讨论】:

  • 链接本身不会向我们展示您现有的代码以及它可能失败的地方。请提供minimal reproducible example
  • @jpp 我在尝试pivot,这是错误的方法,应该是set_index
  • “将列转换为行” = 转置
  • 这应该在你提到的 pandas doc 和 SO 规范中作为单行来提及。
  • 相比之下 pivot 保持垂直列布局,它只是将指定变量的级别展开/折叠到新列中。

标签: python pandas dataframe transpose


【解决方案1】:

我不认为这是支点

df.set_index('part number').T
Out[214]: 
part number         SOME-X1R-1807  RANDOM-462-1171     PART-7W-2326  \
            type     service item       CONSUMABLE            wheel   
part description             SOME       ESCRIPTION        ABOUT THE   
waiting period              1 day           6 days           7 days   
hours                          24              144              168   
part number        NUMBER-1R-0762   NUMBER-XL-0747  
            type             tyre            other  
part description   PARTS FROM THE  PREVIOUS COLUMN  
waiting period             8 days           9 days  
hours                         192              216  

【讨论】:

  • .T在命令末尾有什么作用df.set_index('part number').T
  • @3kstc 转置索引和列来自 pandas api :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-22
  • 2017-07-01
  • 1970-01-01
  • 2013-09-23
  • 2017-12-15
相关资源
最近更新 更多