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)?
3 Answers
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.
1 Comment
Bart Spoon
This is incorrect as of Pandas 0.23. As long as the index has a name it can be included in the list of columns to sort by.
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
1 Comment
Tartaglia
Wait a minute, but you are showing that you don't have to convert the index to a column. Your approach just gives the index a name, you are still using sort values, right?