Argsort DataFrame according to columns

Viewed 953

I have the following DataFrame:

userId column_1 column_2 column_3
A 4.959 3.231 1.2356
B 0.632 0.963 2.4556
C 3.234 7.445 5.3435
D 1.454 0.343 2.2343

I would like to argsort w.r.t columns from the previous one:

userId first second third
A column_3 column_2 column_1
B column_1 column_2 column_3
C column_1 column_3 column_2
D column_2 column_1 column_3
2 Answers

You can use np.argsort over axis 1. Then convert df.columns to numpy array using pd.Index.to_numpy and use numpy indexing.

df = df.set_index('userId') # If userId is not index already.
idx = df.values.argsort(axis=1)
out = pd.DataFrame(df.columns.to_numpy()[idx], index=df.index)

               0         1         2
userId
A       column_3  column_2  column_1
B       column_1  column_2  column_3
C       column_1  column_3  column_2
D       column_2  column_1  column_3

another method would be be to use stack() with sort_values() and map to set your custom colum headings.

mapper_ = {1 : 'first', 2 : 'second', 3 : 'third', 4 : 'fourth'}
s = (df.set_index('userId').stack().sort_values().groupby(level=0).cumcount() + 1).map(mapper_)

s.reset_index(1).set_index(0,append=True).unstack(0)




        level_1                    
0          first    second     third
userId                              
A       column_3  column_2  column_1
B       column_1  column_2  column_3
C       column_1  column_3  column_2
D       column_2  column_1  column_3
Related