繁体   English   中英

在numpy中使用2d掩码掩盖3d数组

[英]Mask a 3d array with a 2d mask in numpy

我有一个三维数组,我想使用一个二维数组进行掩码,该数组的尺寸与三维数组中最右边的两个相同。 有没有办法在不编写以下循环的情况下执行此操作?

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

numpy.broadcast_to (Numpy 1.10.0中的新内容):

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

如果没有循环,您可以将其写为:

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

例如:

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())

得到:

真正

暂无
暂无

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

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