Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Sort Order of Columns by Row

Given the following data frame:

df = pd.DataFrame({'A' : ['1','2','3','7'],
                   'B' : [7,6,5,4],
                   'C' : [5,6,7,1],
                   'D' : [1,9,9,8]})
df=df.set_index('A')
df

    B   C   D
A           
1   7   5   1
2   6   6   9
3   5   7   9
7   4   1   8

I want to sort the order of the columns descendingly on the bottom row like this:

    D   B   C
A           
1   1   7   5
2   9   6   6
3   9   5   7
7   8   4   1

Thanks in advance!

like image 640
Dance Party2 Avatar asked Mar 12 '23 06:03

Dance Party2


2 Answers

Easiest way is to take the transpose, then sort_values, then transpose back.

df.T.sort_values('7', ascending=False).T

or

df.T.sort_values(df.index[-1], ascending=False).T

Gives:

   D  B  C
A         
1  1  7  5
2  9  6  6
3  9  5  7
7  8  4  1

Testing

my solution

%%timeit
df.T.sort_values(df.index[-1], ascending=False).T

1000 loops, best of 3: 444 µs per loop

alternative solution

%%timeit
df[[c for c in sorted(list(df.columns), key=df.iloc[-1].get, reverse=True)]]

1000 loops, best of 3: 525 µs per loop
like image 184
piRSquared Avatar answered Mar 21 '23 07:03

piRSquared


You can use sort_values (by the index position of your row) with axis=1:

df.sort_values(by=df.index[-1],axis=1,inplace=True)
like image 34
beatriz de otto Avatar answered Mar 21 '23 08:03

beatriz de otto