bundles / numpy 2.4.4 / numpy / nonzero
_ArrayFunctionDispatcher
numpy:nonzero
Signature
def nonzero ( a ) Summary
Return the indices of the elements that are non-zero.
Extended Summary
Returns a tuple of arrays, one for each dimension of a, containing the indices of the non-zero elements in that dimension. The values in a are always tested and returned in row-major, C-style order.
To group the indices by element, rather than dimension, use argwhere, which returns a row for each non-zero element.
Parameters
a: array_likeInput array.
Returns
tuple_of_arrays: tupleIndices of elements that are non-zero.
Notes
While the nonzero values can be obtained with a[nonzero(a)], it is recommended to use x[x.astype(bool)] or x[x != 0] instead, which will correctly handle 0-d arrays.
Examples
import numpy as np x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]]) x np.nonzero(x)✓
x[np.nonzero(x)] np.transpose(np.nonzero(x))✓
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) a > 3 np.nonzero(a > 3)✓
a[np.nonzero(a > 3)] a[a > 3] # prefer this spelling✓
(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.
- ndarray.nonzero
Equivalent ndarray method.
Aliases
-
numpy.nonzero