Reputation: 1325
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:
How to sort this dataframe by row['a']: After sort the dataframe, it might be:
Upvotes: 1
Views: 9992
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
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
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