np.nonzero()
nonzero returns the positions of every element that is not zero (or not False).
In this page:
Syntax
indices = np.nonzero(arr)
np.nonzero()
np.nonzero(a) returns a tuple with one index array per dimension, listing where the non-zero elements are. Combined with a comparison it finds positions matching a condition. np.argwhere gives the same information as rows of coordinates.
Note:
np.count_nonzero is a fast way to count how many elements are non-zero.
Example: np.nonzero()
import numpy as np
a = np.array([0, 3, 0, 5, 7])
print(np.nonzero(a))
print(np.count_nonzero(a))
m = np.array([[0, 1], [2, 0]])
print(np.argwhere(m))
# Output:
# (array([1, 3, 4]),)
# 3
# [[0 1]
# [1 0]]
Related Topics
Common Mistakes
- Forgetting the result is a tuple
- Treating 0 and False as non-zero
- Using nonzero on values when you needed the values themselves
Chapter Summary
- nonzero returns index arrays
- One array per dimension
- argwhere returns coordinate rows
- count_nonzero counts them
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: