Series.sort()和Series.order()有什么区别?

2024-04-26 18:13:02 发布

您现在位置:Python中文网/ 问答频道 /正文

s = pd.Series( nr.randint( 0, 10, 5 ), index=nr.randint(0, 10, 5 ) )
s

输出

1    3
7    6
2    0
9    7
1    6

order()按值排序并返回新序列

s.order()

输出

2    0
1    3
7    6
1    6
9    7

看起来sort也按值排序,但实际上:

s.sort()
s

输出

2    0
1    3
7    6
1    6
9    7

这是这两种方法的唯一区别吗?


Tags: 方法index排序order序列sortnrseries
2条回答

你的问题:这是两种方法之间唯一的区别吗?

熊猫0.17.0最终发布之前(即2015-10-09之前)

简短回答:是的。它们在功能上是等价的。

更长的答案:

^{}:更改对象本身(就地排序),但不返回任何内容。

Sort values and index labels by value. This is an inplace sort by default. Series.order is the equivalent but returns a new Series.

所以

>>> s = pd.Series([3,4,0,3]).sort()
>>> s

没有输出。有关详细信息,请参见the answer here

^{}:不更改对象,而是返回一个新的排序对象。

Sorts Series object, by value, maintaining index-value link. This will return a new Series by default. Series.sort is the equivalent but as an inplace method.


熊猫0.17.0最终发布后(即2015-10-09之后)

排序的API是changed,事情变得更干净、更愉快。

要按值排序,不推荐使用Series.sort()Series.order(),取而代之的是新的^{}api,它返回一个已排序的序列对象。

总结这些变化(摘自pandas 0.17.0doc):

To sort by the values (A * marks items that will show a FutureWarning):

        Previous              |         Replacement
------------------------------|-----------------------------------
* Series.order()              |  Series.sort_values()
* Series.sort()               |  Series.sort_values(inplace=True)
* DataFrame.sort(columns=...) |  DataFrame.sort_values(by=...) 

查看pandas源代码(并跳过docstring)

def sort(self, axis=0, ascending=True, kind='quicksort', na_position='last', inplace=True):
        return self.order(ascending=ascending,
                          kind=kind,
                          na_position=na_position,
                          inplace=inplace)

将此与声明的订单行进行比较(我使用的是0.14.1)

def order(self, na_last=None, ascending=True, kind='quicksort', na_position='last', inplace=False)

您可以看到,由于sort调用order函数,除了默认参数之外,这两个函数在hood下的所有意图和用途都是相同的。

如问题中所述,sortinplace = True和orderinplace = Falseinplace参数的默认值不同,但在行为上没有其他差异。

另一个唯一的区别是order有一个附加的(但不推荐使用的)参数,其形式是na_last,不能与sort一起使用(无论如何也不应该使用)。

相关问题 更多 >