pandas 熊猫排序行值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40438656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:21:31  来源:igfitidea点击:

Pandas sort row values

pythonpandas

提问by Cheng

I have a pandas dataframe like this:

我有一个像这样的Pandas数据框:

    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_valuesbut it doesn't work. My work around is df.T.sort_values(...)

我试过了,sort_values但没有用。我的工作是df.T.sort_values(...)

回答by Nickil Maveli

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

从 开始0.19.0,您可以根据行值对列进行排序。

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

enter image description here

在此处输入图片说明



Bar chart:

条形图:

Using ggplot:

使用 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

图片

回答by Berg4

What if my dataframe have a datetime index, and I want to sort the values on the last Datetime. I have tried:

如果我的数据帧有一个日期时间索引,并且我想对最后一个日期时间的值进行排序,该怎么办?我试过了:

df.sort_values(by=df.iloc[-1],ascending=False,inplace=True)

df.sort_values(by=df.iloc[-1],ascending=False,inplace=True)

and

df.sort_values(by=df.index[-1],ascending=False,inplace=True)

df.sort_values(by=df.index[-1],ascending=False,inplace=True)

I get the error :"Exeption Unhandled Timestamp('2018-12-05 20:12:10')"

我收到错误:“Exeption Unhandled Timestamp('2018-12-05 20:12:10')”

My index type is 'datetime64'

我的索引类型是“datetime64”