np.where(cond, x, y) is NumPy's vectorized equivalent of a conditional expression applied to every element at once: for each position, it evaluates cond and picks the corresponding element from x if True, or from y if False, broadcasting x and y to match cond's shape if they're scalars. Called with a single argument, np.where(cond), it instead returns the indices where cond is True, as a tuple of arrays, one per dimension — functionally very similar to np.argwhere(), but returned in a different tuple-of-arrays structure rather than a single 2D array of coordinate pairs.
1Understanding np.where()
np.where(cond, x, y) is NumPy's vectorized equivalent of a conditional expression applied to every element at once: for each position, it evaluates cond and picks the corresponding element from x if True, or from y if False, broadcasting x and y to match cond's shape if they're scalars. Called with a single argument, np.where(cond), it instead returns the indices where cond is True, as a tuple of arrays, one per dimension — functionally very similar to np.argwhere(), but returned in a different tuple-of-arrays structure rather than a single 2D array of coordinate pairs.
np.where(cond, x, y) is the vectorized alternative to writing a Python loop with an if/else inside it — always prefer it over an explicit loop for elementwise conditional selection on NumPy arrays.
import numpy as np
arr = np.array([1, -2, 3, -4, 5])
result = np.where(arr > 0, arr, 0)
print(result)2Practical Example
Here is a real-world application of np.where() showing how it is used in production NumPy code.
import numpy as np
arr = np.array([10, 25, 30, 15, 40])
indices = np.where(arr > 20)
print(indices)3Best Practices
Follow these guidelines when working with np.where():
1. Use np.where(cond, x, y) instead of a Python loop with if/else for elementwise conditional selection on arrays
2. Use the single-argument form, np.where(cond), when you need the indices of matching elements rather than replaced values
3. Reach for np.select() instead of np.where() when you have more than two mutually exclusive conditions/choices to combine
Tip: np.where(cond, x, y) is the vectorized alternative to writing a Python loop with an if/else inside it — always prefer it over an explicit loop for elementwise conditional selection on NumPy arrays.
import numpy as np
arr = np.array([1, -2, 3, -4, 5])
result = np.where(arr > 0, arr, 0)
print(result)