2

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'
jpp
  • 159,742
  • 34
  • 281
  • 339
JavaNewb
  • 155
  • 1
  • 7

2 Answers2

2

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
jpp
  • 159,742
  • 34
  • 281
  • 339
  • Actually `df[:]` should suffice. ++ – cs95 Nov 05 '18 at 22:47
  • @coldspeed, Yeh I think it should. I've never really understood when copies are triggered versus overwriting values. E.g. I've seen significant [performance differentials](https://stackoverflow.com/questions/51486063/what-is-the-big-o-complexity-of-reversing-the-order-of-columns-in-pandas-datafra) doing `df[df.columns[::-1]]` vs `df.iloc[:, ::-1]`. Would you know if they are equivalent for *setting* in general case? – jpp Nov 05 '18 at 22:50
  • 1
    Good question.... from my experience I've always found assigning to df[:], df.values, or df.iloc[:] yield similar results... not sure if the underlying mechanism is the same... it should be, if it is directly updating the underlying numpy arrays. – cs95 Nov 05 '18 at 22:52
2

Using sort

df.values.sort()
df
Out[256]: 
     COL1     COL2       COL3
0   'Adam'   'John'    'Mary'
BENY
  • 317,841
  • 20
  • 164
  • 234