使用python根据索引和非索引列对表值进行排序 [英] Sorting a table values based on index and non-indexed columns using python

查看:283
本文介绍了使用python根据索引和非索引列对表值进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I sort values in a dataframe based on an index and non-indexed columns?

数据框:

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(升序)对表格进行排序.

Table has two index columns (ID and Colour). I will like to sort the table based on ID(ascending), A (Descending) and C (ascending).

必需的输出是:

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",因为无法识别列.

This didn't work as "ID" as a column was not recognized.

推荐答案

您想要的

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

这篇关于使用python根据索引和非索引列对表值进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆