I am facing this problem involving dataframes, so after spending a lot of time on Google, I am opening a question here. I am having a Dataframe -
df
A B C D
0 8 3 6 2
1 1 -3 5 2
2 4 9 5 10
3 2 -4 -8 -2
I want to sort every row in descending order, but instead of saving the values, I want to save the corresponding column name.
Sorted dataframe would look like this -
df
A B C D
0 8 6 3 2
1 5 2 1 -3
2 10 9 5 4
3 2 -2 -4 -8
What I ultimately want is this structure below, which corresponds to the column indices of the sorted dataframe df
-
df_col
1 2 3 4
0 A C B D
1 C D A B
2 D B C A
3 A D B C
I am sure there will be a simpler one liner solution to this problem, without coding an explicit for loop
Here's another way, using
argsort
andapply
You can use
numpy.argsort
:Or pandas solution with
apply
:Apply
np.argsort
, sort the indices, and then index intodf.columns
.Here is a solution similar to @COLDSPEED's solution - it uses
Series.argsort
: