where() (NumPy)
np.where(condition, x, y) builds a new array choosing elements from x where the condition is True and from y where it is False. Called with only a condition, it returns the indices where that condition holds.
NumPy
The three-argument form is a vectorized if/else: np.where(scores >= 60, 'pass', 'fail') labels each element without a loop. x and y can be arrays or scalars and broadcast against the condition, which makes where the go-to tool for conditional element-wise transforms.
The one-argument form, np.where(condition), returns a tuple of index arrays marking the True positions — effectively 'where is this true?' — which you can use to index back into arrays. For a 2-D input you get one index array per axis.
where is faster and cleaner than looping or list comprehensions, and it composes well with boolean masks. For selecting from more than two choices based on multiple conditions, np.select generalizes it.
Syntax
np.where(condition, x, y) | np.where(condition)Examples
Python
import numpy as np
a = np.array([1, 5, 2, 8])
print(np.where(a > 3, "hi", "lo"))Output:
['lo' 'hi' 'lo' 'hi']