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:
Syntax
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()
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
- Forgetting the one-argument form returns a tuple
- Passing arrays of incompatible shapes
- 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: