How to return a mask or nomask of a masked array in Python

Overview

The numpy.ma.getmask() method in Python is used to return the mask or no mask values of a masked array. This is done by returning a Boolean array, which holds the result, of the same shape as the input array.

Syntax

The ma.getmask() method uses the syntax below:

ma.getmask(a)
Syntax for the ma.getmask() function in Python

Parameters

The ma.getmask() method takes a single parameter value, a, which represents the input array (possibly masked) for which the mask is to be obtained.

Return values

The ma.getmask() method returns an array of Boolean values indicating the mask (True) or nomask (False) elements of the input array.

Example

Below, we see an example of the ma.getmask() method:

import numpy.ma as ma
# creating a masked array
a = ma.arange(8).reshape(4,2)
# masking the element in the second row but the second column
a[1, 1] = ma.masked
# masking the elements in the third row
a[2, :] = ma.masked
# implementing the ma.getmask() method
b = ma.getmask(a)
print(a)
print(b)

Explanation

In the code above, we do the following:

  • Line 1: We import the numpy.ma module.
  • Line 3: We create an input array, a.
  • Line 6: We mask the element in the second row on the second column of the input array.
  • Line 9: We mask the elements of the third row of the input array.
  • Line 12: We obtain the mask and nomask values of the input array by using the ma.getmask() function. The result is assigned to a variable, b.
  • Lines 14–15: We print the input array, a and the obtained array, b.

Free Resources