简体   繁体   中英

Mask 3D numpy array where array is equal to a list of values

How do you mask a 3D numpy array using a list of integers? I would like all elements in the array where an element is equal to any of the values in the list to be masked.

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

The above will, for illustration purposes, create a 3D array with random integer values between 0 and 10. We'll then define the values we want to mask from our first array. Then we're using the np.in1d method to create a bool mask based on our original array and the values, and pass that into numpy.ma.MaskedArray , which generates a masked array with the values masked out.

This then allows you to run operations on non-masked values and then unmask then later on or fill them with a default value.

Use np.in1d for this

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]

This will output:

mask = [[[False False]
  [ True  True]]

 [[False False]
  [False False]]]
found elements = [2 3]

np.in1d is basically the element wise equivalent of the in keyword in vanilla python. As it only operates on 1d arrays you also need to do the reshape at the end so that the shape of the mask matches the shape of your data.

If you want the indices of those positions you can use np.where

indices = zip( *np.where(mask) )
print indices
# [(0, 1, 0), (0, 1, 1)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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