6

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(...)

3
  • 1
    Do you have just one row? Or you want to sort it according to the first row? Commented Nov 5, 2016 at 13:32
  • Your solution of transposing, sorting, and transposing again is the current solution. See this post and bug report. Commented Nov 5, 2016 at 13:34
  • @NickilMaveli I only have one row Commented Nov 5, 2016 at 13:34

1 Answer 1

14

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

Sign up to request clarification or add additional context in comments.

1 Comment

Er, this doesn't work if your table has more than one row, right?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.