简体   繁体   English

Filter numpy array base 1-0 掩码

[英]Filter numpy array base 1-0 mask

Say I have a numpy ndarray of shape (172,40,20) and a 1-0 mask of shape (172, 40).假设我有一个形状为 (172,40,20) 的 numpy ndarray 和一个形状为 (172, 40) 的 1-0 掩码。 I would like to do something similar to bitwise_and: to keep those values where the mask value is 1 while other values set to 0 where the mask value is 0.我想做一些类似于 bitwise_and 的事情:在掩码值为 1 的地方保留这些值,而在掩码值为 0 的地方将其他值设置为 0。

Is there a way that I can do without looping?有没有一种方法可以不用循环? for example例如

a3D = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(a3D.shape)
mask = np.array([[1, 0], [0, 1]])
print(mask.shape)
# (2, 2, 2)
# (2, 2)

# my func
result = bitwise_and(a3D, mask) 

# result = np.array([[[1, 2], [0, 0]], [[0, 0], [7, 8]]])

Simply index the array using the mask as boolean indices :只需使用掩码作为boolean 索引对数组进行索引

result = a3D.copy()
result[mask == 0, :] = 0
print(result)

outputs产出

[[[1 2]
  [0 0]]

 [[0 0]
  [7 8]]]

You can use np.where() :您可以使用np.where()

np.where(mask[:, :, np.newaxis], a3D, 0)
[[[1 2]
  [0 0]]

 [[0 0]
  [7 8]]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM