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 |
You can create a conditional column in pandas DataFrame by using np. where() , np. select() , DataFrame. map() , DataFrame.
(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'
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With