Mask a 3d array with a 2d mask in numpy

我们两清 提交于 2019-12-05 03:03:15

Without the loop you could write it as:

field3d_mask[:,:,:] = field2d[np.newaxis,:,:] > 0.3

For example:

field3d_mask_1 = np.zeros(field3d.shape, dtype=bool)
field3d_mask_2 = np.zeros(field3d.shape, dtype=bool)

for t in range(nt):
    field3d_mask_1[t,:,:] = field2d > 0.3

field3d_mask_2[:,:,:] = field2d[np.newaxis,:,:] > 0.3

print((field3d_mask_1 == field3d_mask_2).all())

gives:

True

There's numpy.broadcast_to (new in Numpy 1.10.0):

field3d_mask = np.broadcast_to(field2d > 0.3, field3d.shape)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!