Search code examples
pythonnumpymasking

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.


Solution

  • 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.