How to return the indices of non-zero unmasked elements
Overview
The ma.nonzero() method in NumPy returns the indices, or index positions, of non-zero unmasked elements of an array.
Syntax
The ma.nonzero() method takes the following syntax:
ma.nonzero(self)
Syntax for the ma.nonzero() function
Parameter value
The ma.nonzero() method takes a single parameter: self. This represents the input array, which may be masked.
Return value
The ma.nonzero() method returns the index position of unmasked elements that are not zero.
Example
import numpy as npimport numpy.ma as ma# Creating an input arraya = ma.array(np.eye(4))# Implementing the ma.nonzero() methodb = ma.nonzero(a)print(a)print(b)
Explanation
Line 1: We import the
numpymodule.Line 2: We import the
numpy.mamodule.Line 4: We create an input array,
a.Line 7: We call the
ma.nonzero()method and pass theainput array as the argument. We assign the result to the variableb.Line 9: We print the
ainput array.Line 10: We print
b.