python - 在 numpy 数组中找到第 k 个最小的元素

标签 python numpy

我需要在一维 numpy.array 中找到最小的第 n 个元素。

例如:

a = np.array([90,10,30,40,80,70,20,50,60,0])

我想得到第 5 个最小的元素,所以我想要的输出是 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

最佳答案

除非我遗漏了什么,否则你要做的是:

>>> a = np.array([90,10,30,40,80,70,20,50,60,0])
>>> np.partition(a, 4)[4]
40

np.partition(a, k) 会将 a 的第 k+1 最小元素放在 a[ k]a[:k] 中的值较小,a[k+1:] 中的值较大。唯一需要注意的是,由于 0 索引,第五个元素位于索引 4。

关于python - 在 numpy 数组中找到第 k 个最小的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22546180/

相关文章:

python - 为函数中的异常引发自定义消息

python - query.connector 的值如何设置在 Django 代码中的 Q 对象中?

Python Numpy intersect1d 一维数组与二维数组

python - reshape np 数组以进行深度学习

python - 如何比较两个具有 NaN 值的 numpy 数组?

python - 根据第 0 个列表的 argsort 对嵌套列表中的列表进行排序

python - Pandas 交叉表百分比

python - 如何在 kivy 应用程序中同时运行 Clock.schedule_interval 实例?

python - Windows 7 python 32 上 python.exe 的内存 - Numpy 仅使用一半的可用内存?

python - 验证均匀分布的 3D 坐标的分布