查找满足条件的二维 numpy 数组的索引

Hap*_*lop 4 python arrays numpy matrix

我有一个大的 2D numpy 数组,想在其中找到满足条件的一维数组的索引:例如,至少有一个大于给定阈值 x 的值。

我已经可以通过以下方式做到这一点,但有没有更短、更有效的方法来做到这一点?

import numpy

a = numpy.array([[1,2,3,4,5], [1,2,3,4,20], [1,2,2,4,5]])

indices = []
i = 0
x = 10
for item in a:
    if any(j > x for j in item):
        indices.append(i)
    i += 1

print(indices) # gives [1]
Run Code Online (Sandbox Code Playgroud)

Chr*_*ler 5

您可以使用 numpy 的内置布尔运算:

import numpy as np
a = np.array([[1,2,3,4,5], [1,2,3,4,20], [1,2,2,4,5]])

indices = np.argwhere(np.any(a > 10, axis=1))
Run Code Online (Sandbox Code Playgroud)