yensheng
yensheng

Reputation: 1325

How to sort dataframe by a row?

I have a dataframe:

import pandas as pd

df = pd.DataFrame(data={'x':[7,1,9], 'y':[4,5,6],'z':[1,8,3]}, index=['a', 'b', 'c'])

It shows:

enter image description here

How to sort this dataframe by row['a']: After sort the dataframe, it might be:

enter image description here

Upvotes: 1

Views: 9992

Answers (4)

user2285236
user2285236

Reputation:

In v0.19 you can sort by rows:

pd.__version__
Out: '0.19.0rc1'

df.sort_values(by='a', axis=1)
Out: 
   z  y  x
a  1  4  7
b  8  5  1
c  3  6  9

Upvotes: 2

unutbu
unutbu

Reputation: 880937

In [7]: df.iloc[:, np.argsort(df.loc['a'])]
Out[7]: 
   z  y  x
a  1  4  7
b  8  5  1
c  3  6  9

np.argsort returns the indices one would use to sort the a row, df.loc['a']:

In [6]: np.argsort(df.loc['a'])
Out[6]: 
x    2
y    1
z    0
Name: a, dtype: int64

Once you have those indices, you can use them to reorder the columns of df (by using df.iloc).

Upvotes: 4

taras
taras

Reputation: 6915

You can use reindex_axis method:

>>> df.reindex_axis(sorted(df.columns, key=lambda x: df[x]['a']), axis=1)
   z  y  x
a  1  4  7
b  8  5  1
c  3  6  9

Upvotes: 2

DeepSpace
DeepSpace

Reputation: 81684

You can use axis=1 when calling sort:

df.sort(axis=1, ascending=False)   

>>       z  y  x
      a  1  4  7
      b  8  5  1
      c  3  6  9

Note that sort is not inplace by default, so either reassign its return value or use inplace=True.

Upvotes: 3

Related Questions