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

Posted

技术标签:

【中文标题】为每个级别对 Pandas 中的多索引进行不同的排序【英文标题】:Sorting Multi Index in Pandas differently for each level 【发布时间】:2018-11-27 16:51:27 【问题描述】:

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

有一个数据框 (df) 为:

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

我想要一个新的df,其中color 排序为ascendingshapedescendingcountascending

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

【问题讨论】:

【参考方案1】:

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

【讨论】:

以上是关于为每个级别对 Pandas 中的多索引进行不同的排序的主要内容,如果未能解决你的问题,请参考以下文章