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
Pandas sort row values
提问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_values
but 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)
Bar chart:
条形图:
Using ggplot:
使用 ggplot:
melt_df = pd.melt(df, var_name='Cols')
ggplot(aes(x="Cols", weight="value"), melt_df) + geom_bar()
Using built-in:
使用内置:
melt_df.plot.bar(x=['Cols'], y=['value'], legend=False, cmap=plt.cm.Spectral)
plt.show()
回答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”