Dance Party2
Dance Party2

Reputation: 7536

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!

Upvotes: 4

Views: 4841

Answers (3)

beatriz de otto
beatriz de otto

Reputation: 41

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)

Upvotes: 3

piRSquared
piRSquared

Reputation: 294218

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

Upvotes: 3

hilberts_drinking_problem
hilberts_drinking_problem

Reputation: 11602

Here is a variation that does not involve transposition:

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

Upvotes: 2

Related Questions