【问题标题】:How to pivot multilabel table in pandas如何在熊猫中旋转多标签表
【发布时间】:2018-08-04 21:11:29
【问题描述】:

我正在尝试导入有关不同商品价格变化的数据。数据保存在 MySQL 中。我以类似于以下的堆叠格式导入了输入数据框df

 ID    Type      Date      Price1   Price2
0001    A     2001-09-20    30       301
0002    A     2001-09-21    31       278
0003    A     2001-09-22    28       299
0004    B     2001-09-18    18       159
0005    B     2001-09-20    21       157
0006    B     2001-09-21    21       162
0007    C     2001-09-19    58       326
0008    C     2001-09-20    61       410
0009    C     2001-09-21    67       383

而且,为了进行时间序列分析,我想转换成另一种格式,类似于:

               A               B              C
             Price1  Price2  Price1  Price2  Price1  Price2
Date   
2001-09-18   NULL     NULL    18       159    NULL    NULL
2001-09-19   NULL     NULL   NULL     NULL     58     326
2001-09-20   30       301    21        157     61     410
2001-09-21   31       278    21        168     67     383
2001-09-22   28       299    NULL     NULL    NULL    NULL

我看过this question。这两种建议的方式都不是我想要实现的。关于 pivot 的 pandas 文档似乎也没有提及任何相关内容。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以通过pivotset_indexunstack 进行整形,但随后需要swaplevelsort_index 以在列中获得预期的Multiindex

    df1 = (df.drop('ID', axis=1)
             .pivot('Date','Type')
             .swaplevel(0,1, axis=1)
             .sort_index(axis=1))
    

    df1 = (df.drop('ID', axis=1)
             .set_index(['Date','Type'])
             .unstack()
             .swaplevel(0,1, axis=1)
             .sort_index(axis=1))
    

    df1 = (df.set_index(['Date','Type'])[['Price1','Price2']]
             .unstack()
             .swaplevel(0,1, axis=1)
             .sort_index(axis=1))
    

    print (df1)
    Type            A             B             C       
               Price1 Price2 Price1 Price2 Price1 Price2
    Date                                                
    2001-09-18    NaN    NaN   18.0  159.0    NaN    NaN
    2001-09-19    NaN    NaN    NaN    NaN   58.0  326.0
    2001-09-20   30.0  301.0   21.0  157.0   61.0  410.0
    2001-09-21   31.0  278.0   21.0  162.0   67.0  383.0
    2001-09-22   28.0  299.0    NaN    NaN    NaN    NaN
    

    【讨论】:

      猜你喜欢
      • 2015-11-21
      • 2023-01-24
      • 2020-02-24
      • 2021-10-01
      • 2019-09-09
      • 2015-05-28
      • 2020-02-01
      • 1970-01-01
      相关资源
      最近更新 更多