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.

Oldboz14
  • 77
  • 4
  • please post the df not an image, also what is the expected output after the sorting? – Kenan Dec 14 '20 at 16:07
  • Please update your question following these guidelines and someone will be able to help you: https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples – robertwest Dec 14 '20 at 16:12
  • I edited the post to include the code and expected output – Oldboz14 Dec 14 '20 at 16:17

1 Answers1

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
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74