python将索引升序_使用python根据索引和非索引列对表值进行排序

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

Dataframe:

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

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

Required output is :

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

I have tried this:

df.set_index(inplace=True)

df.sort_values([‘ID’, ‘A’, ‘C’], ascending=[‘True’,’False’,’True’])

This didn’t work as “ID” as a column was not recognized.

解决方案

you want

df.reset_index().sort_values(

[‘ID’, ‘A’, ‘C’],

ascending=[‘True’,’False’,’True’]

).set_index([‘ID’, ‘Colour’])

Original: https://blog.csdn.net/weixin_34293588/article/details/112903964
Author: 左耳余音
Title: python将索引升序_使用python根据索引和非索引列对表值进行排序

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/756760/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球