Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas sort row values

Tags:

python

pandas

I have a pandas dataframe like this:

    Col1  Col2  Col3
1   1092  203   802 

Is it possible to sort this dataframe and get a result like this:

    Col1  Col3  Col2
1   1092  802   203 

I tried sort_values but it doesn't work. My work around is df.T.sort_values(...)

like image 556
Cheng Avatar asked Nov 05 '16 13:11

Cheng


1 Answers

Starting from 0.19.0, you could sort the columns based on row values.

df.sort_values(by=1, ascending=False, axis=1)

enter image description here


Bar chart:

Using ggplot:

melt_df = pd.melt(df, var_name='Cols')
ggplot(aes(x="Cols", weight="value"), melt_df) + geom_bar()

Image

Using built-in:

melt_df.plot.bar(x=['Cols'], y=['value'], legend=False, cmap=plt.cm.Spectral)
plt.show()

Image

like image 133
Nickil Maveli Avatar answered Nov 02 '22 22:11

Nickil Maveli