如何使用整数列表遮盖3D numpy数组?我希望将数组中所有元素中等于列表中任何值的元素都进行遮盖。
import numpy as np
import numpy.ma as ma
randomArray = np.random.random_integers(0, 10, (5, 5, 5))
maskingValues = [1, 2, 5]
maskedRandomArray = ma.MaskedArray(randomArray, np.in1d(randomArray, maskingValues))
np.in1d
来完成此操作。import numpy as np
data = np.arange(8).reshape(2,2,2)
nums_wanted = [2,3]
mask = np.in1d( data, nums_wanted ).reshape( data.shape )
print "mask =", mask
print "found elements =", data[mask]
mask = [[[False False]
[ True True]]
[[False False]
[False False]]]
found elements = [2 3]
np.in1d
基本上相当于vanilla python中的in
关键字的逐元素等效。由于它仅在1d数组上操作,因此您还需要在最后进行reshape,以便掩码的形状与数据的形状匹配。
如果您想要这些位置的索引,可以使用np.where
。
indices = zip( *np.where(mask) )
print indices
# [(0, 1, 0), (0, 1, 1)]