Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argsort DataFrame according to columns

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
like image 794
Javier Monsalve Avatar asked Dec 28 '20 17:12

Javier Monsalve


People also ask

How do I create a conditional column in pandas?

You can create a conditional column in pandas DataFrame by using np. where() , np. select() , DataFrame. map() , DataFrame.

How do you give a DataFrame a condition?

(1) IF condition – Set of numbers Suppose that you created a DataFrame in Python that has 10 numbers (from 1 to 10). You then want to apply the following IF conditions: If the number is equal or lower than 4, then assign the value of 'True' Otherwise, if the number is greater than 4, then assign the value of 'False'

How do I order a DataFrame in pandas?

In order to sort the data frame in pandas, function sort_values() is used. Pandas sort_values() can sort the data frame in Ascending or Descending order.


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
like image 56
Ch3steR Avatar answered Oct 17 '22 05:10

Ch3steR


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
like image 28
Umar.H Avatar answered Oct 17 '22 06:10

Umar.H