0

What is a nice way of sorting every column alphabetically in a pandas DataFrame?

Example:

df = DataFrame({'A':['Bob','Rob','Dob'],'B':['Dob','Bob','Rob'],'C':['Rob','Bob','Dob']})

df

     A   B   C
0   Bob Dob Rob
1   Rob Bob Bob
2   Dob Rob Dob

I want:

     A   B   C
0   Bob Bob Bob
1   Dob Dob Dob
2   Rob Rob Rob
2
  • @miradulo Really, the top voted answer there uses apply + sort_values... for shame Commented Apr 21, 2018 at 2:35
  • @cᴏʟᴅsᴘᴇᴇᴅ This is another with your answer at the top: stackoverflow.com/questions/43280322/… Commented Apr 21, 2018 at 2:35

1 Answer 1

2

Use np.sort along the first axis.

df[:] = np.sort(df, axis=0)

Or, even simpler,

df.values.sort(axis=0)

df
     A    B    C
0  Bob  Bob  Bob
1  Dob  Dob  Dob
2  Rob  Rob  Rob
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.