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

Chiel picture Chiel · Jun 7, 2016 · Viewed 9.2k times · Source

I have a 3-dimensional array that I want to mask using a 2-dimensional array that has the same dimensions as the two rightmost of the 3-dimensional array. Is there a way to do this without writing the following loop?

import numpy as np

nx = 2
nt = 4

field3d = np.random.rand(nt, nx, nx)
field2d = np.random.rand(nx, nx)

field3d_mask = np.zeros(field3d.shape, dtype=bool)

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

field3d = np.ma.array(field3d, mask=field3d_mask)

print field2d
print field3d

Answer

user2379410 picture user2379410 · Jun 8, 2016

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

field3d_mask = np.broadcast_to(field2d > 0.3, field3d.shape)