我相信bottleneck.argpartsort做了与{a1}相似的事情。所以,让我们用这个。现在,使用np.argpartiton而不是{},我们需要使用range(3)来保持排序顺序。对于一个标量,argpartiton不会对这些3元素进行排序,但是使用range(3)则会。在
让我们举个例子来展示-In [360]: a
Out[360]:
array([ 0.6082239 , 0.74932587, 0.50574681, 0.85241966, 0.91742228,
0.9984438 , 0.6876266 , 0.90651069, 0.53746683, 0.70674607])
In [361]: np.argpartition(-a,3) # 4,5,7 are the top 3, but not in sorted order
Out[361]: array([4, 5, 7, 3, 1, 9, 6, 2, 8, 0])
In [362]: np.argpartition(-a,range(3)) # Sorted order maintained for top 3
Out[362]: array([5, 4, 7, 3, 1, 0, 6, 2, 8, 9])
另外,使用np.argpartiton它不会对数组中剩余的元素进行排序,从而在那里提供运行时的好处。如果我们希望按排序顺序获得top N元素,其中N是一个比数组长度相对较小的数字,那么这将非常有益。在
因此,我们将使用np.argpartiton实现,如下-
^{pr2}$
运行时测试-In [342]: a = np.random.rand(10000)
In [343]: %timeit a[np.argsort(a)[-1:-4:-1]] #@R. S. Nikhil Krishna's soln
1000 loops, best of 3: 907 µs per loop
In [344]: %timeit a[np.argpartition(-a,range(3))[:3]]
10000 loops, best of 3: 67.9 µs per loop