'Sort_values Pandas to sort by index?

I know that sort_index() lets me sort a df by the index, but I am wondering if sort_values() can sort by the index too (without resetting the index)?



Solution 1:[1]

No, sort_values can't sort the by index without converting first converting the index to a column (possibly with reset_index). The typical way to sort by index, as you have mentioned, is via the sort_index method. Links to the documentation for the relevant methods is given below.

Solution 2:[2]

Hope this helps, as balast mentioned, you would need to convert the index to a column:

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

More info on earlier answer

Solution 3:[3]

As mentioned in a comment above, you can give the index a name and use that in sort_values:

> import pandas as pd
> df = pd.DataFrame([2,1,3], index=[2,1,3])   
> df.index.name='myindex'
> df.sort_values('myindex') 
myindex   
1        1
2        2
3        3

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 balast
Solution 2 inverzeio
Solution 3 aless80