How to get the data of a masked array as an ndarray

Overview

In NumPy, the ma.getdata() method is used to return the data of a given masked array as an ndarray.

Syntax

The ma.getdata() method takes the syntax below:

ma.getdata(a, subok=True)
Syntax for the ma.getdata() method in NumPy

Parameters

The ma.getdata() method takes the following parameter values:

  • a (required): This is the input array.
  • subok (optional): This takes a boolean value. If set to False, it will force the result to be a pure ndarray. When set to True, it will return a subclass of the ndarray.

Return value

The ma.getdata() method returns an ndarray.

Code

import numpy.ma as ma
# creating a an 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
# printing the masked array
print(a)
# printing the original array
print(ma.getdata(a))

Explanation

  • 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 print the masked input array.
  • Line 15: We print the original array (ndarray).

Free Resources