← Back to NumPy Course | Chapter 10: Boolean & Comparison | Lesson 6 of 6

np.nonzero()

nonzero returns the positions of every element that is not zero (or not False).

In this page:

  1. np.nonzero()
Syntax
python
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()

python
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
  1. Forgetting the result is a tuple
  2. Treating 0 and False as non-zero
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.