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

np.where()

np.where() chooses between two values for each element depending on a condition, like an if/else for whole arrays.

In this page:

  1. np.where()
Syntax
python
result = np.where(condition, x, y)

np.where()

np.where(condition, x, y) returns x where the condition is True and y elsewhere. With only a condition it returns the indices of True elements. It is the vectorized replacement for a loop with if/else.

Note: With only one argument, np.where returns a tuple of index arrays, one per dimension.

Example: np.where()

python
import numpy as np

scores = np.array([45, 82, 67, 90, 30])
print(np.where(scores >= 50, "pass", "fail"))
print(np.where(scores > 60))

# Output:
# ['fail' 'pass' 'pass' 'pass' 'fail']
# (array([1, 2, 3]),)
Related Topics
Common Mistakes
  1. Forgetting the one-argument form returns a tuple
  2. Passing arrays of incompatible shapes
  3. Using a Python if/else inside a loop instead
Chapter Summary
  • where(cond, x, y) picks per element
  • One argument returns indices
  • Broadcasts x and y
  • Replaces loops with if/else
🔒

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.