user27976
user27976

Reputation: 903

Sorting a table values based on index and non-indexed columns using 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.

Upvotes: 3

Views: 2150

Answers (2)

akuiper
akuiper

Reputation: 215067

You can call sort_values() to sort columns A and C and then call sort_index() to sort index ID:

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

enter image description here

Upvotes: 4

piRSquared
piRSquared

Reputation: 294498

you want

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

enter image description here

Upvotes: 5

Related Questions