Pandas: How to swap a row's cell values so that they are in alphabetical order

1635 views python
3

I have the following dataframe:

  COL1 |  COL2  | COL3
 'Mary'| 'John' | 'Adam'

How can I reorder this row so that 'Mary', 'John', and 'Adam' are ordered alphabetically in COL1, COL2, and COL3, like so:

  COL1 |  COL2  | COL3
 'Adam'| 'John' | 'Mary'

answered question

2 Answers

7

You can assign values via np.sort:

df.iloc[:] = pd.DataFrame(np.sort(df.values, axis=1))

# also works, performance not yet tested
# df[:] = pd.DataFrame(np.sort(df.values, axis=1))

print(df)

   COL1  COL2  COL3
0  Adam  John  Mary

posted this
3

Using sort

df.values.sort()
df
Out[256]: 
     COL1     COL2       COL3
0   'Adam'   'John'    'Mary'

posted this

Have an answer?

JD

Please login first before posting an answer.