【问题标题】:Pivot Pandas DataFrame into hierarchical columns/change column hierarchy将 Pandas DataFrame 转换为分层列/更改列层次结构
【发布时间】:2025-12-16 13:50:02
【问题描述】:

我想旋转一个数据框,例如:

       dim1   Value_V     Value_y   instance
0      A_1     50.000000        0   instance200
1      A_2   6500.000000        1   instance200
2      A_3     50.000000        0   instance200
3      A_4   4305.922313        1   instance200

进入具有这样分层列的数据框:

              A_1               A_2               A_3                .....
              Value_V  Value_y  Value_V  Value_y  Value_V  Value_y
instance200   50       0        6500     1        50       0

我试过df = df.pivot(index = "instance", columns = "dim1"),但它只会给我一个这样的框架:

              Value_V               Value_y                              
              A_1   A_2   A_3 ....  A_1  A_2  A_3 ....
instance200   50    6500  50        0    1    0

如何更改列的层次结构?

【问题讨论】:

    标签: python pandas pivot


    【解决方案1】:

    我自己想出来的:

    df = df.swaplevel(0,1,axis = 1).sort(axis = 1)
    

    会的

    【讨论】:

    • 附带说明,swaplevel 适合在 2 之间进行交换,而 reorder_levels 可以同时执行多个,如果有帮助的话:)跨度>
    • 你在读我的心思:我只是想知道 swaplevelreorder_levels 之间的区别可能是什么:)
    【解决方案2】:

    您需要的是 reorder_levels,然后对列进行排序,如下所示:

    import pandas as pd
    
    df = pd.read_clipboard()
    
    df
    Out[8]:
    dim1    Value_V Value_y instance
    0   A_1 50.000000   0   instance200
    1   A_2 6500.000000 1   instance200
    2   A_3 50.000000   0   instance200
    3   A_4 4305.922313 1   instance200
    In [9]:
    
    df.pivot('instance', 'dim1').reorder_levels([1, 0], axis=1).sort(axis=1)
    Out[9]:
    dim1        A_1             A_2             A_3             A_4
                Value_V Value_y Value_V Value_y Value_V Value_y Value_V Value_y
    instance                                
    instance200 50      0       6500    1       50      0       4305.922313 1
    

    【讨论】: