Skip to content Skip to sidebar Skip to footer

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

Solution 1:

you want

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

enter image description here

Solution 2:

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

Post a Comment for "Sorting A Table Values Based On Index And Non-indexed Columns Using Python"