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 np
import numpy.ma as ma
# Creating an input array
a = ma.array(np.eye(4))
# Implementing the ma.nonzero() method
b = ma.nonzero(a)
print(a)
print(b)

Explanation

  • Line 1: We import the numpy module.

  • Line 2: We import the numpy.ma module.

  • Line 4: We create an input array, a.

  • Line 7: We call the ma.nonzero() method and pass the a input array as the argument. We assign the result to the variable b.

  • Line 9: We print the a input array.

  • Line 10: We print b.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources