首页 > 解决方案 > 为每个级别对 Pandas 中的多索引进行不同的排序

问题描述

我有一个索引为 3 级的数据框。我需要按每个级别对索引进行排序,但方式不同。有什么可以做到这一点?

有一个数据框 ( df) 为:

                     other columns
color shape    count              
red   circle   1                 x
      triangle 3                 x
               2                 x
blue  circle   4                 x
      triangle 2                 x

我想要一个新的dfwhere coloris sorted ascending, shapeisdescendingcountis ascending

                     other columns
color shape       count              
blue  triangle    2                 x
      circle      4                 x
red   triangle    2                 x
                  3                 x
      circle      1                 x

标签: pythonpandassortingdataframemulti-index

解决方案


ascending参数与布尔值列表一起使用:

df.sort_index(ascending=[True, False, True])

输出:

                     other columns
color shape    count              
blue  triangle 2                 x
      circle   4                 x
red   triangle 2                 x
               3                 x
      circle   1                 x

推荐阅读