如何使用范围在 numpy 数组中查找列表元素的索引



>假设我有一个numpy数组,如下所示:

arr = np.array([[[1, 7], [5, 1]], [[5, 7], [6, 7]]])

其中每个最里面的子数组都是一个元素。例如;[1, 7] 和 [5, 1] 都被视为元素。

。我想找到满足以下条件的所有元素:[<=5,>=7]。因此,上述示例的真实结果数组如下所示:

arr_truthy = [[True, False], [True, False]]

。至于arr中的底部元素之一,第一个值是<=5,第二个值是>=7

我可以通过迭代arr中的每个轴来轻松解决此问题:

for x in range(arr.shape[0]):
for y in range(arr.shape[1]):
# test values, report if true.

.. 但是这种方法很慢,我希望有更numpy的方法可以做到这一点。我已经尝试过np.where但我无法弄清楚如何进行多子元素条件。

我正在有效地尝试对元素中的每个数字测试一个独立的条件。

谁能指出我正确的方向?

我会这样做。 将输出初始化为相同的形状。 然后只需对这些元素进行比较。

out = np.full(arr.shape,False)
out[:,:,0] = arr[:,:,0] >= 5
out[:,:,1] = arr[:,:,1] >= 8

输出:

array([[[False, False],
[ True, False]],
[[ True,  True],
[ True, False]]])

编辑:在我们的编辑之后,我认为你只需要一个最终的np.all 沿着最后一个轴:

np.all(out, axis=-1)

返回:

array([[False, False],
[ True, False]])

你在寻找吗

(arr[:,:,0] <= 5) & (arr[:,:,1] >= 7)

?您可以执行广播比较。

输出:

array([[True, False],
[True, False]])

在您的示例中,第二对 ([5, 1]) 与您的规则匹配(第一个值为>=5,第二个值为 <=7),但在 result(arr_truthy) 中,其值为 False。如果这是一个错误,我的代码可以工作,否则请澄清条件。

arr = np.array([[[1, 7], [5, 1]], [[5, 6], [6, 7]], [[1, 9], [9, 1]]])
# Create True/False arrays for the first/second element of the input
first = np.zeros_like(arr, dtype=bool)
first = first.flatten()
first[::2] = 1
first = first.reshape(arr.shape)
second = np.invert(first)
# The actual logic:
out = np.logical_or(np.where(arr >= 5, first, False), np.where(arr <= 7, second, False))
# Both the condition for the first and for the second element of each par has to be meet
out = out.all(axis=-1)

最新更新