【问题标题】:ordering the multiindex level manually手动订购多索引级别
【发布时间】:2019-12-27 18:31:51
【问题描述】:

我有一个列顺序不正确的数据透视表,我需要按我的意愿排列列

以下代码用于数据透视表:

data_frame1 = pd.pivot_table(data_frame, index=['PC', 'Geo', 'Comp'], values=['Bill', 'Bill2'], columns=['Month'], fill_value=0 )

代码输出

               Bill1              Bill2
 Month       Jan    Feb        Jan    Feb     
PC Geo Comp
A  Ind  OP    1     1.28        1    1.28
B  US   OS    1     1.28        1    1.28
C  Can  OV    1     1.28        1    1.28

预期输出

                Bill2              Bill1
 Month       Jan    Feb        Jan    Feb     
PC Geo Comp
A  Ind  OP    1     1.28        1    1.28
B  US   OS    1     1.28        1    1.28
C  Can  OV    1     1.28        1    1.28

【问题讨论】:

    标签: python-3.x pandas pivot-table


    【解决方案1】:

    MultiIndex的第一级使用DataFrame.reindex

    df = df.reindex(['Bill2','Bill1'], axis=1, level=0)
    print (df)
          Bill2       Bill1      
            Feb   Jan Month   Jan
    A Ind     1  1.28     1  1.28
    B US      1  1.28     1  1.28
    C Can     1  1.28     1  1.28
    

    或者如果可能的话按降序排序:

    df = df.sort_index(axis=1, level=0, ascending=False)
    

    【讨论】:

    • 兄弟我正在使用下面的代码,但它没有工作...new_order = ['Bill2', 'Bill1']df = df.reindex([new_order, axis=1, level=0)
    • @PraveenSnowy - 不明白,你必须更具体。
    • ..如果 Bill1 & Bill2 处于 1 级,那么 df = df.reindex(['Bill2','Bill1'], axis=1, level=1) 是否正确?
    • @PraveenSnowy - 是的,确切地说 - axis=1 表示列,levels=1 表示第二级(在这个答案中它是第一级)
    猜你喜欢
    • 2013-08-10
    • 1970-01-01
    • 2011-06-27
    • 2021-12-03
    • 2020-04-29
    • 2018-07-09
    • 2019-05-03
    • 2018-04-20
    • 2021-01-28
    相关资源
    最近更新 更多