1

I have a DataFrame, df, that I want to sort by both columns and rows at the same time.

data = {'c2': ['4.0', '2.0', '1.0', '3.0'],
       'c1': ['200', '100', '300', '400'],
       'c3': ['aa', 'cc', 'dd', 'ee']}
df = pd.DataFrame(data)
df.index = ['d', 'b', 'c', 'a']
df

I have no problem sorting by either of them, but I cannot figure out how to get them sorted at the same time. I would like the output to have the columns sorted by 'c1', 'c2', 'c3' and the rows to be 'a', 'b', 'c', 'd'. Don't think it is very difficult but I cannot figure out how to do it.

3
  • please post the df not an image, also what is the expected output after the sorting? Commented Dec 14, 2020 at 16:07
  • Please update your question following these guidelines and someone will be able to help you: stackoverflow.com/questions/20109391/… Commented Dec 14, 2020 at 16:12
  • I edited the post to include the code and expected output Commented Dec 14, 2020 at 16:17

1 Answer 1

1

You can chain sort_index:

df.sort_index().sort_index(axis=1)

Output:

    c1   c2  c3
a  400  3.0  ee
b  100  2.0  cc
c  300  1.0  dd
d  200  4.0  aa
Sign up to request clarification or add additional context in comments.

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.