pandas 在python中用pandas对系列进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36160019/
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
sort series with pandas in python
提问by xirururu
I selected one column from the a DataFrame, then I got a Series. How can I sort the series? I used the Series.sort(), but it doesn't work.
我从 DataFrame 中选择了一列,然后我得到了一个系列。如何对系列进行排序?我使用了 Series.sort(),但它不起作用。
df = pd.DataFrame({'A': [5,0,3,8],
'B': ['B8', 'B9', 'B10', 'B11']})
df
A B
0 5 B8
1 0 B9
2 3 B10
3 8 B11
Then I selected the column 'A'
然后我选择了“A”列
df['A']
A
0 5
1 0
2 3
3 8
After selected 'A' column, I got a Series, but with Series.sort(), it doesn't work.
选择“A”列后,我得到了一个系列,但使用 Series.sort(),它不起作用。
df['A'].sort()
It shows the error:
它显示错误:
"ValueError: This Series is a view of some other array, to sort in-place you must create a copy"
“ValueError:这个系列是一些其他数组的视图,要就地排序,你必须创建一个副本”
So I used the Series.copy() function to copy the series, after that I sort the series, but there is no outcome.
所以我使用 Series.copy() 函数复制系列,然后我对系列进行排序,但没有结果。
df['A'].copy().sort()
But there is no result returned.
但是没有返回结果。
How can I fix the problem?
我该如何解决这个问题?
采纳答案by user25064
But there is no result returned.
但是没有返回结果。
That is because the sort is in place, it modifies the object. Try this
那是因为排序就位,它修改了对象。尝试这个
A = df['A'].copy()
A.sort()
print(A)
回答by shikha singh
One of them will work for you -
其中之一将为您工作-
df.sort('A',ascending=False,inplace=True) #old version
df.sort_values('A',ascending=False,inplace=True) #new version