Locate populated entries
Sparse or masked data
NumPy · Function
Returns the indices of non-zero elements as one index array per input dimension. It also works with boolean conditions to locate entries where a predicate is true.
np.nonzero evaluates an array-like input and returns a tuple containing one index array for each dimension. Each array holds coordinates of non-zero elements, ordered according to row-major, C-style traversal; boolean conditions can therefore be passed to locate elements satisfying a predicate.
numpy.nonzero(a)| Name | Type | Description |
|---|---|---|
a | array_like | Array-like input whose values are tested for being non-zero. |
A tuple of arrays containing the indices of non-zero elements, with one array for each dimension of the input.
import numpy as np
x = np.array([[0, 2, 0], [3, 0, 4]])
rows, columns = np.nonzero(x)
print(rows) # [0 1 1]
print(columns) # [1 0 2]
mask = x > 2
print(np.nonzero(mask))The function returns one index array per dimension; applying it to a boolean condition finds positions where the condition is true.
Sparse or masked data
Thresholding
Multidimensional coordinate extraction
It returns a tuple with one array for each input dimension. The arrays contain the coordinates of non-zero elements, and the coordinates follow row-major C-style order.
Follow-up: How would you obtain one coordinate row per matching element? Use np.argwhere, which groups the indices by element.
A comparison such as a > 3 produces a boolean array. Because False is treated as zero, np.nonzero(a > 3) returns the positions where the comparison is true.
Follow-up: How can you retrieve the matching values instead of their coordinates? Use boolean indexing, for example a[a > 3].
Its input parameter a is array-like. The function tests the values and reports the indices of entries that are not zero.
Follow-up: What ordering should callers expect? The returned indices follow row-major, C-style order.
numpy.argwherenumpy.nonzeronumpy.atleast_1d