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

你离开我真会死。 提交于 2019-12-22 03:55:11

问题


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

回答1:


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




回答2:


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

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


来源:https://stackoverflow.com/questions/37682284/mask-a-3d-array-with-a-2d-mask-in-numpy

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