在numpy中使用2d遮罩遮罩3d阵列 [英] Mask a 3d array with a 2d mask in numpy
本文介绍了在numpy中使用2d遮罩遮罩3d阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个3维数组,我想使用一个2维数组遮罩,该2维数组的尺寸与3维数组中最右边的两个相同.有没有一种方法,而无需编写以下循环?
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
推荐答案
没有循环,您可以将其编写为:
Without the loop you could write it as:
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())
给予:
是
这篇关于在numpy中使用2d遮罩遮罩3d阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文