0
0
NumpyHow-ToBeginner ยท 3 min read

How to Use np.nonzero in NumPy: Syntax and Examples

Use np.nonzero(array) to get the indices of all non-zero elements in a NumPy array. It returns a tuple of arrays, each representing the indices along a dimension where the elements are non-zero.
๐Ÿ“

Syntax

The basic syntax of np.nonzero is:

  • np.nonzero(a): Returns a tuple of arrays, one for each dimension of a, containing the indices of non-zero elements.

Here, a is the input NumPy array.

python
indices = np.nonzero(a)
๐Ÿ’ป

Example

This example shows how to find the indices of non-zero elements in a 2D NumPy array.

python
import numpy as np

a = np.array([[0, 1, 2], [3, 0, 0], [0, 4, 5]])
indices = np.nonzero(a)
print("Row indices of non-zero elements:", indices[0])
print("Column indices of non-zero elements:", indices[1])

# To get the coordinates as pairs
coordinates = list(zip(indices[0], indices[1]))
print("Coordinates of non-zero elements:", coordinates)
Output
Row indices of non-zero elements: [0 0 1 2 2] Column indices of non-zero elements: [1 2 0 1 2] Coordinates of non-zero elements: [(0, 1), (0, 2), (1, 0), (2, 1), (2, 2)]
โš ๏ธ

Common Pitfalls

1. Forgetting that np.nonzero returns a tuple of arrays: Each array corresponds to indices along one dimension. You must use them together to get full coordinates.

2. Using np.nonzero on 1D arrays: It returns a single-element tuple with indices, so access with [0].

3. Confusing np.nonzero with boolean indexing: np.nonzero gives indices, not a filtered array.

python
import numpy as np

# Wrong: expecting a single array
arr = np.array([0, 2, 0, 3])
indices_wrong = np.nonzero(arr)  # This is a tuple
print(type(indices_wrong))  # <class 'tuple'>

# Right: access the first element
indices_right = np.nonzero(arr)[0]
print(indices_right)  # [1 3]
Output
<class 'tuple'> [1 3]
๐Ÿ“Š

Quick Reference

FunctionDescription
np.nonzero(a)Returns tuple of arrays with indices of non-zero elements in array a
indices = np.nonzero(a)Assigns indices tuple to variable for further use
indices[0], indices[1], ...Access indices along each dimension
list(zip(indices[0], indices[1]))Get list of coordinate pairs for 2D arrays
โœ…

Key Takeaways

np.nonzero returns a tuple of arrays with indices of non-zero elements along each dimension.
Use the tuple elements together to get full coordinates of non-zero values in multi-dimensional arrays.
For 1D arrays, access the first element of the tuple to get the indices array.
np.nonzero gives indices, not the filtered array itself.
Use list(zip(...)) to pair row and column indices for easy coordinate access.