You are viewing an older version (2.4.3). Go to latest (2.4.4)
{ } Raw JSON

bundles / numpy 2.4.3 / numpy / ma / core / nonzero

function

numpy.ma.core:nonzero

source: /numpy/ma/core.py :7063

Signature

def   nonzero ( self )

Summary

Return the indices of unmasked elements that are not zero.

Extended Summary

Returns a tuple of arrays, one for each dimension, containing the indices of the non-zero elements in that dimension. The corresponding non-zero values can be obtained with

a[a.nonzero()]

To group the indices by element, rather than dimension, use instead

np.transpose(a.nonzero())

The result of this is always a 2d array, with a row for each non-zero element.

Parameters

None

Returns

tuple_of_arrays : tuple

Indices of elements that are non-zero.

Examples

import numpy as np
import numpy.ma as ma
x = ma.array(np.eye(3))
x
x.nonzero()
Masked elements are ignored.
x[1, 1] = ma.masked
x
x.nonzero()
Indices can also be grouped by element.
np.transpose(x.nonzero())
A common use for ``nonzero`` is to find the indices of an array, where a condition is True. Given an array `a`, the condition `a` > 3 is a boolean array and since False is interpreted as 0, ma.nonzero(a > 3) yields the indices of the `a` where the condition is true.
a = ma.array([[1,2,3],[4,5,6],[7,8,9]])
a > 3
ma.nonzero(a > 3)
The ``nonzero`` method of the condition array can also be called.
(a > 3).nonzero()

See also

count_nonzero

Counts the number of non-zero elements in the input array.

flatnonzero

Return indices that are non-zero in the flattened version of the input array.

numpy.ndarray.nonzero

Equivalent ndarray method.

numpy.nonzero

Function operating on ndarrays.

Aliases

  • numpy.ma.nonzero