【问题标题】:Multiindex Re-indexing - custom sort多索引重新索引 - 自定义排序
【发布时间】:2021-02-19 09:20:58
【问题描述】:

如何重新索引多索引?我有 2 个索引,第一个索引需要手动排序,第二个索引是按降序排列的。

下面index1需要自定义排序为:Cat-B、Cat-A、Cat-C; index2 按降序排列。

Index1 Index2
Cat-A  Apple
       Orange
       Banana
Cat-B  Mango
       Lychee
Cat-C  Kiwi
       Nectarine

到:

Index1 Index2
Cat-B  Mango
       Lychee
Cat-A  Orange
       Banana
       Apple
Cat-C  Nectarine
       Kiwi

谢谢!

【问题讨论】:

    标签: python pandas dataframe sorting


    【解决方案1】:

    您需要pd.CategoricalIndex,但是由于这个订单是单向的,我们需要手动反转订单。

    cati = pd.CategoricalIndex(
        df.index.get_level_values(0).unique(), ["Cat-C", "Cat-A", "Cat-B"], ordered=True
    )
    #note 'Cat-C' is first but will be last when we sort the index.
    
    df.index = df.index.set_levels(cati,level=0)
    
    print(df.sort_index(0,level=[0,1],ascending=False))
                       A
    Index1 Index2       
    Cat-B   Mango      0
            Lychee     0
    Cat-A   Orange     0
            Banana     0
            Apple      0
    Cat-C   Nectarine  0
            Kiwi       0
    

    【讨论】:

      猜你喜欢
      • 2017-06-16
      • 2021-12-20
      • 2019-02-05
      • 1970-01-01
      • 2018-07-08
      • 1970-01-01
      • 2021-08-10
      • 2018-08-25
      • 2021-10-03
      相关资源
      最近更新 更多