python - 查找二维数组中最高元素的列表 : Python 3

标签 python arrays numpy search optimization

我有一个尺寸为 (640X480) 的二维数组,如下所示:

[[1.2 , 9.5 , 4.8 , 1.7],
 [5.5 , 8.1 , 7.6 , 7.1],
 [1.4 , 6.9 , 7.8 , 2.2]]     (this is a sample of a 4X3 array)

我必须以最快的方式找到数组中前 100(或 N)个最高值;所以我需要最优化的代码,它需要最少的处理时间。

因为它是一个巨大的数组,如果我只检查每个第 2 个元素或每个第 3 个或第 4 个元素就可以了。

算法的输出应该是一个元组列表,每个元组是高值元素的二维索引。

例如 9.5 的索引为 (0,1)

我找到了一个解决方案,但它太慢了:

indexes=[]
for i in range(100):
    highest=-1
    highindex=0.1
    for indi,i in enumerate(array):
        for indj,j in enumerate(i):
            if j>highest and not((indi,indj) in indexes):
                highest= j
                highindex=(indi,indj)
    indexes.append(highindex)

最佳答案

numpy.argpartition , numpy.unravel_indexnumpy.column_stack套路:

测试 ndarray arr 是一个随机排列的数组,其值 099 形状为 (11, 9) .
假设我们想要找到前 7 个最大值的二维索引列表:

In [1018]: arr
Out[1018]: 
array([[36, 37, 38, 39, 40, 41, 42, 43, 44],
       [27, 28, 29, 30, 31, 32, 33, 34, 35],
       [72, 73, 74, 75, 76, 77, 78, 79, 80],
       [ 0,  1,  2,  3,  4,  5,  6,  7,  8],
       [18, 19, 20, 21, 22, 23, 24, 25, 26],
       [45, 46, 47, 48, 49, 50, 51, 52, 53],
       [ 9, 10, 11, 12, 13, 14, 15, 16, 17],
       [90, 91, 92, 93, 94, 95, 96, 97, 98],
       [54, 55, 56, 57, 58, 59, 60, 61, 62],
       [63, 64, 65, 66, 67, 68, 69, 70, 71],
       [81, 82, 83, 84, 85, 86, 87, 88, 89]])

In [1019]: top_N = 7

In [1020]: idx = np.argpartition(arr, arr.size - top_N, axis=None)[-top_N:]

In [1021]: result = np.column_stack(np.unravel_index(idx, arr.shape))

In [1022]: result
Out[1022]: 
array([[7, 2],
       [7, 3],
       [7, 4],
       [7, 5],
       [7, 7],
       [7, 8],
       [7, 6]])

关于python - 查找二维数组中最高元素的列表 : Python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51122073/

相关文章:

python - Arnaud Legoux 移动平均线和 numpy

python - 矩阵的维度不等于相等

python - Pygame - 碰撞和列表

Python gRPC 服务器未启动

python - 解释 Python 的 '__enter__' 和 '__exit__'

java - 存储此数据的对象或数组

c++ - 如何将两种类型的数据分配给一个变量?

python - 如何在Python中的随机数数组中找到最多和最少被猜到的数字?

python - 循环时创建一个 numpy 数组数组(Python)

Python:帮助(numpy)导致退出时出现段错误