To return the mask of a masked array, use the ma.getmask() method in Python Numpy. Returns the mask of a as an ndarray if a is a MaskedArray and the mask is not nomask, else return nomask. To guarantee a full array of booleans of the same shape as a, use getmaskarray.

A masked array is the combination of a standard numpy.ndarray and a mask. A mask is either nomask, indicating that no value of the associated array is invalid, or an array of booleans that determines for each element of the associated array whether the value is valid or not.

## Steps

At first, import the required library −

import numpy as np
import numpy.ma as ma

Creating a 4x4 array with int elements using the numpy.arange() method −

arr = np.arange(16).reshape((4,4))
print("Array...", arr)
print("Array type...", arr.dtype)

Get the dimensions of the Array −

print("Array Dimensions...",arr.ndim)
print("Our Array type...", arr.dtype)

Get the shape of the Array −

print("Our Masked Array Shape...",arr.shape)


Get the number of elements of the Array −

print("Elements in the Masked Array...",arr.size)

arr = ma.array(arr)
arr[3, 3] = ma.masked

Count the number of masked elements along specific axis −

print("The number of masked elements...",ma.count_masked(arr, axis = 1))


print("Result (mask of a masked array)...",ma.getmask(arr))

## Example

import numpy as np
import numpy.ma as ma

# Creating a 4x4 array with int elements using the numpy.arange() method
arr = np.arange(16).reshape((4,4))
print("Array...", arr)
print("Array type...", arr.dtype)

# Get the dimensions of the Array
print("Array Dimensions...",arr.ndim)
print("Our Array type...", arr.dtype)

# Get the shape of the Array

# Get the number of elements of the Array

arr = ma.array(arr)

# Count the number of masked elements along specific axis

print("Result (mask of a masked array)...",ma.getmask(arr))

## Output

Array...
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]

Array type...
int64

Array Dimensions...
2

Our Array type...
int64

(4, 4)

16

[1 1 2 3]

[[False True False False]
[False True False False]
[False True True False]
[ True False True True]]

Updated on: 21-Feb-2022

805 Views