对每个级别的 Pandas 中的多索引进行不同排序

Lis*_*sle 2 python sorting multi-index dataframe pandas

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

有一个数据框 ( df) 为:

                     other columns
color shape    count              
red   circle   1                 x
      triangle 3                 x
               2                 x
blue  circle   4                 x
      triangle 2                 x
Run Code Online (Sandbox Code Playgroud)

我希望有一个新的df地方color进行排序ascendingshapedescendingcountascending

                     other columns
color shape       count              
blue  triangle    2                 x
      circle      4                 x
red   triangle    2                 x
                  3                 x
      circle      1                 x
Run Code Online (Sandbox Code Playgroud)

Sco*_*ton 6

使用ascending带有布尔值列表的参数:

df.sort_index(ascending=[True, False, True])
Run Code Online (Sandbox Code Playgroud)

输出:

                     other columns
color shape    count              
blue  triangle 2                 x
      circle   4                 x
red   triangle 2                 x
               3                 x
      circle   1                 x
Run Code Online (Sandbox Code Playgroud)