如何在不使用显式循环的情况下替换 numpy.ndarray 关于条件的"array elements"?



我有一个形状为(5,4,3)的三维numpy.ndarray,我想用另一个数组替换数组内的三个元素。例如,我想用[0, 0, 0]替换所有的[3, 3, 3]元素。下面,我给出了一个我找到的解决方案,但是这个解决方案不够有效,并且在大数组上可能会很长。


我创建了以下numpy.ndarray:

c = np.array([[[3,3,3],[2,2,2],[3,3,3],[4,4,4]],[[1,1,1],[2,2,2],[7,3,3],[4,4,4]],[[1,1,1],[3,3,3],[3,3,3],[4,4,4]],[[1,1,1],[2,2,2],[3,8,3],[3,3,3]],[[3,3,3],[2,2,2],[3,3,3],[4,4,4]]])

这给了我:

,

祝辞的在比;c

array([[[3, 3, 3],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4]],
[[1, 1, 1],
[2, 2, 2],
[7, 3, 3],
[4, 4, 4]],
[[1, 1, 1],
[3, 3, 3],
[3, 3, 3],
[4, 4, 4]],
[[1, 1, 1],
[2, 2, 2],
[3, 8, 3],
[3, 3, 3]],
[[3, 3, 3],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4]]])

,祝辞祝辞的在c.shape

(5, 4, 3)

我想用[0, 0, 0]替换所有的[3, 3, 3]元素。

我找到的解决方案如下:

# I reshape my array to get only a 2D array
c_copy = c.reshape(c.shape[0] * c.shape[1], c.shape[2])
# Then I loop through all the elements of the array to replace [3, 3, 3] by [0, 0, 0]
c_copy[[np.array_equal(e, [3, 3, 3]) for e in c_copy]] = [0,0,0]
# And I reshape my copy to get the original shape back
c_modified = c_copy.reshape(c.shape)

运行良好:

,

祝辞的在比;c_modified

array([[[0, 0, 0],
[2, 2, 2],
[0, 0, 0],
[4, 4, 4]],
[[1, 1, 1],
[2, 2, 2],
[7, 3, 3],
[4, 4, 4]],
[[1, 1, 1],
[0, 0, 0],
[0, 0, 0],
[4, 4, 4]],
[[1, 1, 1],
[2, 2, 2],
[3, 8, 3],
[0, 0, 0]],
[[0, 0, 0],
[2, 2, 2],
[0, 0, 0],
[4, 4, 4]]])

然而,循环for e in c_copy是杀了我。这对于这个小数组来说很好,但是我有一个900000个元素的数组,我还没有找到任何有效的解决方案。

我怎么做才能加快计算速度?


生活例子

您需要找到[3,3,3]的索引,您可以使用all(axis=-1),然后替换为[0,0,0]:

row, col = np.where((c==3).all(-1))
c[row, col] = [0,0,0]
print(c)

输出:

[[[0 0 0]
[2 2 2]
[0 0 0]
[4 4 4]]
[[1 1 1]
[2 2 2]
[7 3 3]
[4 4 4]]
[[1 1 1]
[0 0 0]
[0 0 0]
[4 4 4]]
[[1 1 1]
[2 2 2]
[3 8 3]
[0 0 0]]
[[0 0 0]
[2 2 2]
[0 0 0]
[4 4 4]]]