Check the base of a masked array in NumPy

NumpyServer Side ProgrammingProgramming

To check the base of masked array data that owns its memory, use the ma.MaskedArray.base attribute in Numpy. Returns dtype for the base element of the subarrays, regardless of their dimension or shape.

NumPy offers comprehensive mathematical functions, random number generators, linear algebra routines, Fourier transforms, and more. It supports a wide range of hardware and computing platforms, and plays well with distributed, GPU, and sparse array libraries.

Masked arrays are arrays that may have missing or invalid entries. The numpy.ma module provides a nearly work-alike replacement for numpy that supports data arrays with masks.

Steps

At first, import the required library −

import numpy as np
import numpy.ma as ma

Create an array using the numpy.array() method −

arr = np.array([[35, 85], [67, 33]])
print("Our Array...\n", arr)

Create a masked array and mask some of them as invalid −

maskArr = ma.masked_array(arr, mask =[[0, 0], [ 0, 1]])
print("\nOur Masked Array\n", maskArr)

To check the base of an array that owns its memory, use the numpy.base attribute. The base of an array that owns its memory is None −

print("\nOur Array baseclass\n", arr.base)

To check the base of masked array data that owns its memory, use the ma.MaskedArray.base attribute in Numpy −

print("\nOur Masked Array baseclass\n", maskArr.base)

Example

import numpy as np
import numpy.ma as ma

arr = np.array([[35, 85], [67, 33]])
print("Our Array...\n", arr)

# Create a masked array and mask some of them as invalid
maskArr = ma.masked_array(arr, mask =[[0, 0], [ 0, 1]])
print("\nOur Masked Array\n", maskArr)

# To check the base of an array that owns its memory, use the numpy.base attribute
# The base of an array that owns its memory is None
print("\nOur Array baseclass\n", arr.base)

# To check the base of masked array data that owns its memory, use the ma.MaskedArray.base attribute in Numpy
print("\nOur Masked Array baseclass\n", maskArr.base)

Output

Our Array...
[[35 85]
[67 33]]

Our Masked Array
[[35 85]
[67 --]]

Our Array baseclass
None

Our Masked Array baseclass
[[35 85]
[67 33]]
raja
Updated on 04-Feb-2022 07:00:18

Advertisements