Demetri P Demetri P - 6 months ago 30
Python Question

How can I sort a dataframe on a row rather than a column?

I have a dataframe

Albania Andorra Armenia Austria Azerbaijan
2014 98.0 96.0 97.0 96.0 98.0
2013 99.0 95.0 97.0 96.0 98.0
2012 98.0 98.0 97.0 95.5 97.0
2011 99.0 99.0 97.0 96.0 98.0
2010 99.0 99.0 97.0 96.0 98.0


and I would like to sort the columns on the
2014
row. So the resulting sort should have the columns as Albania, Azerbajain, Armenia, Andorra, Austria.

I bet I could do it using
df.values
and then sorting the resulting ndarray, but could
df.sort_values
do this? I tried
df.sort_values('2014',axis = 1)
but got the error
KeyError: '2014'
.

closest I can get without using arrays is
f[f.ix['2014'].sort_values(ascending = False).index]

Answer

Solution

Take transpose then sort

df.T.sort_values(2014).T