3

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)?

0

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
0

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

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?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.