【问题标题】:Sorting a table values based on index and non-indexed columns using python使用python根据索引和非索引列对表值进行排序
【发布时间】:2016-11-29 05:40:23
【问题描述】:

如何根据索引和非索引列对数据框中的值进行排序?

数据框:

ID  Colour  A   B   C
45356   Green   1   34  4
34455   Yellow  23  0   1
53443   Brown   3   4   3
45555   Green   5   5   2

表有两个索引列(ID 和颜色)。我想根据 ID(升序)、A(降序)和 C(升序)对表格进行排序。

需要的输出是:

ID  Colour  A   B   C
34455   Yellow  23  0   1
45356   Green   1   34  4
45555   Green   5   5   2
53443   Brown   3   4   3

我试过这个:

df.set_index(inplace=True)
df.sort_values(['ID', 'A', 'C'], ascending=['True','False','True'])

这不起作用,因为“ID”无法识别列。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你想要的

    df.reset_index().sort_values(
        ['ID', 'A', 'C'],
        ascending=['True','False','True']
    ).set_index(['ID', 'Colour'])
    

    【讨论】:

      【解决方案2】:

      您可以调用sort_values() 对列AC 进行排序,然后调用sort_index() 对索引ID 进行排序:

      (df.sort_values(['A', 'C'], ascending=[False, True])
         .sort_index(level=0, sort_remaining=False, kind='mergesort'))
      

      【讨论】:

      • 我觉得这超级危险:根据文档,mergesort 是唯一稳定的算法。默认是快速排序,所以容易出错。
      • 非常感谢大家。很棒的解决方案。问题解决了。
      猜你喜欢
      • 2018-07-08
      • 1970-01-01
      • 2017-03-24
      • 2012-09-07
      • 1970-01-01
      • 2013-12-15
      • 2020-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多