O'Reilly logo

NumPy Cookbook - Second Edition by Ivan Idris

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating a masked array

Masked arrays can be used to ignore missing or invalid data items. A MaskedArray class from the numpy.ma module is a subclass of ndarray, with a mask. We will use the Lena Söderberg image as the data source and pretend that some of this data is corrupt. Finally, we will plot the original image, log values of the original image, the masked array, and log values thereof.

How to do it...

Let's create the masked array:

  1. To create a masked array, we need to specify a mask. Create a random mask with values that are either 0 or 1:
    random_mask = np.random.randint(0, 2, size=lena.shape)
  2. Using the mask from the previous step, create a masked array:
    masked_array = np.ma.array(lena, mask=random_mask)

    The following is the complete code for ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required