Mask a 3d array with a 2d mask in numpy
There's numpy.broadcast_to
(new in Numpy 1.10.0):
field3d_mask = np.broadcast_to(field2d > 0.3, field3d.shape)
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.3field3d_mask_2[:,:,:] = field2d[np.newaxis,:,:] > 0.3print((field3d_mask_1 == field3d_mask_2).all())
gives:
True