如何使用pandas旋转数据框,使可变列成为行? [英] How to pivot a dataframe with pandas so variable columns become rows?

查看:104
本文介绍了如何使用pandas旋转数据框,使可变列成为行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有以下数据框:

当前df:

Current 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

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

I want to pivot the table, and get the following outcome:

预期df:

Expected 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

问题:

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

How do I pivot a dataframe to get this output?

我尝试过的事情:

  • How to pivot a dataframe in Pandas? [duplicate]
  • Reshaping and Pivot Tables
  • Make DataFrame.pivot index argument truly optional
  • Reshaping in Pandas - Pivot, Pivot-Table, Stack and Unstack explained with Pictures

推荐答案

我不认为这是关键

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  

这篇关于如何使用pandas旋转数据框,使可变列成为行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆