如何在二维数组中找到高于某个阈值的n个最大值?

时间:2016-02-06 15:02:14

标签: python arrays numpy

前言:我建立了this answer

考虑以下代码:

import numpy as np

# Create an array to work with.
np.random.seed(123)
full = np.random.randint(1, 99, size=(8, 8))

# Get the indices for the largest `num_largest` values.
num_largest = 8

indices = (-full).argpartition(num_largest, axis=None)[:num_largest]
# OR, if you want to avoid the temporary array created by `-full`:
# indices = full.argpartition(full.size - num_largest, axis=None)[-num_largest:]

x, y = np.unravel_index(indices, full.shape)

print "full:"
print full
print "x =", x
print "y =", y
print "Largest values:", full[x, y]    

输出:

full:
[[67 93 18 84 58 87 98 97]
 [48 74 33 47 97 26 84 79]
 [37 97 81 69 50 56 68  3]
 [85 40 67 85 48 62 49  8]
 [93 53 98 86 95 28 35 98]
 [77 41  4 70 65 76 35 59]
 [11 23 78 19 16 28 31 53]
 [71 27 81  7 15 76 55 72]]
x = [0 2 4 4 0 1 4 0]
y = [6 1 7 2 7 4 4 1]
Largest values: [98 97 98 98 97 97 95 93]    

如何找到高于的最大值?

换句话说,如果我有兴趣只返回上面的值,例如,我该如何做?

期望的输出:

Largest values: [98 97 98 98 97 97] # 95 and 93 are missing because it's below the threshold

除了过滤,我还想保留索引信息;也就是说,最大值的x和y坐标。

因此,下面的解决方案不会起作用,因为它只是在最后过滤值并删除索引信息。

full[full>95]

0 个答案:

没有答案