【发布时间】:2018-09-01 15:52:39
【问题描述】:
我只需要找到一维 numpy.array 中最小的第 n 个元素。
例如:
a = np.array([90,10,30,40,80,70,20,50,60,0])
我想获得第五小的元素,所以我想要的输出是40。
我目前的解决方案是这样的:
result = np.max(np.partition(a, 5)[:5])
但是,找到 5 个最小的元素,然后取出最大的一个,这对我来说似乎有点笨拙。有更好的方法吗?我是否缺少一个可以实现目标的功能?
有些问题的标题与此类似,但我没有看到任何回答我的问题的内容。
编辑:
我本来应该提到它,但性能对我来说非常重要;因此,heapq 解决方案虽然不错,但对我不起作用。
import numpy as np
import heapq
def find_nth_smallest_old_way(a, n):
return np.max(np.partition(a, n)[:n])
# Solution suggested by Jaime and HYRY
def find_nth_smallest_proper_way(a, n):
return np.partition(a, n-1)[n-1]
def find_nth_smallest_heapq(a, n):
return heapq.nsmallest(n, a)[-1]
#
n_iterations = 10000
a = np.arange(1000)
np.random.shuffle(a)
t1 = timeit('find_nth_smallest_old_way(a, 100)', 'from __main__ import find_nth_smallest_old_way, a', number = n_iterations)
print 'time taken using partition old_way: {}'.format(t1)
t2 = timeit('find_nth_smallest_proper_way(a, 100)', 'from __main__ import find_nth_smallest_proper_way, a', number = n_iterations)
print 'time taken using partition proper way: {}'.format(t2)
t3 = timeit('find_nth_smallest_heapq(a, 100)', 'from __main__ import find_nth_smallest_heapq, a', number = n_iterations)
print 'time taken using heapq : {}'.format(t3)
结果:
time taken using partition old_way: 0.255564928055
time taken using partition proper way: 0.129678010941
time taken using heapq : 7.81094002724
【问题讨论】:
-
另外,查看docs.python.org/2/library/heapq.html 可能会有所帮助
-
@C.B.上述问题与我的问题有很大不同;它要求最小值和最大值,它是二维矩阵
-
这是怎么复制的?标题听起来很相似,但问题本身却大不相同。有时不同的问题会得出相同的答案,但这里的答案也大不相同。这个问题的答案不可能是我问题的答案。