Sort pandas dataframe both on values of a column and index?

Pandas 0.23 finally gets you there :-D

You can now pass index names (and not only column names) as parameters to sort_values. So, this one-liner works:

df = df.sort_values(by = ['MyCol', 'MyIdx'], ascending = [False, True])

And if your index is currently unnamed:

df = df.rename_axis('MyIdx').sort_values(by = ['MyCol', 'MyIdx'], ascending = [False, True])

In pandas 0.23+ you can do it directly - see OmerB's answer. If you don't yet have 0.23+, read on.


I'd venture that the simplest way is to just copy your index over to a column, and then sort by both.

df['colFromIndex'] = df.index
df = df.sort(['count', 'colFromIndex'])

I'd also prefer to be able to just do something like df.sort(['count', 'index']), but of course that doesn't work.


As of pandas version 0.22.

You can temporarily set the column as an index, sort the index on that column and then reset. By default it will maintain the order of the existing index:

df = df.set_index('column_name', append=True).sort_index(level=1).reset_index(level=1)

I think the above could be done with 'inplace' options but I think it's easier to read as above.