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!
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
                        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)
                        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