按第一列 Pandas 对数据框进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40462675/
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:22:41  来源:igfitidea点击:

Sort dataframe by first column, Pandas

sortingpandasdataframe

提问by Carmen

I have a dataframe with one column, which I would like to sort. Typing following code gives me a sorted dataframe:

我有一个包含一列的数据框,我想对其进行排序。输入以下代码会给我一个排序的数据框:

sort = tst.sort(["Mean"], ascending = False)

                Mean
SIMULATION          
Sim_758     1.351917
Sim_215     1.072942
Sim_830     0.921284
Sim_295     0.870272
Sim_213     0.845990
Sim_440     0.822394

This will be part of a function, which will be applied to other dataframes. For this reason I need to sort the dataframe without mentioning the column name "mean".

这将是一个函数的一部分,该函数将应用于其他数据帧。出于这个原因,我需要在不提及列名“mean”的情况下对数据框进行排序。

Is there a way to sort a dataframe by the values of a column, only indicating the position of the column?

有没有办法按列的值对数据框进行排序,只指示列的位置?

回答by jezrael

I think you can select first column by tst.columns[0], better is use sort_valuesbecause sortreturn warning:

我认为您可以通过 选择第一列tst.columns[0],最好使用,sort_values因为sort返回警告:

FutureWarning: sort(columns=....) is deprecated, use sort_values(by=.....)

FutureWarning: sort(columns=....) 已弃用,使用 sort_values(by=.....)

sort = tst.sort_values(tst.columns[0], ascending = False)


print (tst)
                Mean
SIMULATION          
Sim_213     0.845990
Sim_758     1.351917
Sim_830     0.921284
Sim_295     0.870272
Sim_215     1.072942
Sim_830     0.921284
Sim_295     0.870272
Sim_440     0.822394

print (tst.columns[0])
Mean

sort = tst.sort_values(tst.columns[0], ascending = False)
print (sort)
                Mean
SIMULATION          
Sim_758     1.351917
Sim_215     1.072942
Sim_830     0.921284
Sim_830     0.921284
Sim_295     0.870272
Sim_295     0.870272
Sim_213     0.845990
Sim_440     0.822394