Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: Sort column by maximum values

Suppose we have following dataframe:

A  B  C  D

1  5  16 1
5  30 45 10
2  40 60 5
4  15 40 7

Here, we need to sort the columns according to their maximum values. Accordingly, the columns should be sorted like:

C B D A

because max(C)=60, max(B)=40, max(D)=10, max(A)=5.

What's the best way to automate this?

like image 257
RPacker Avatar asked Mar 11 '23 21:03

RPacker


1 Answers

You can sort the result from df.max and use this to reindex the df:

In [64]:
df.ix[:, df.max().sort_values(ascending=False).index]

Out[64]:
    C   B   D  A
0  16   5   1  1
1  45  30  10  5
2  60  40   5  2
3  40  15   7  4

breaking the above down:

In [66]:
df.max()

Out[66]:
A     5
B    40
C    60
D    10
dtype: int64

In [67]:
df.max().sort_values(ascending=False)

Out[67]:
C    60
B    40
D    10
A     5
dtype: int64
like image 138
EdChum Avatar answered Mar 21 '23 01:03

EdChum