NumPy | where method
Start your free 7-days trial now!
Numpy's where(~)
method maps an array of booleans to the specified outputs, similar to how an if-else
works.
Parameters
1. condition
| array_like
of booleans
An array of booleans.
2. x
| array_like
All instances of True will be replaced by x.
3. y
| array_like
All instances of False will be replaced by y.
Return value
A Numpy array.
Examples
Basic mapping
To replace all True
with 5, and all False
with 10:
np.where(x, 5, 10)
array([5, 5, 10, 10])
Using a boolean mask
On a more practical note, the where()
method works well with a boolean mask. Suppose we wanted all values larger than 2 to be 10, and all other values to be -1.
We first build a boolean mask like follows:
array([False, False, True, True])
We then apply the mapping:
np.where(mask, 10, -1)
array([-1, -1, 10, 10])
Replace values based on number
Suppose we wanted to perform some arithmetics based on a certain criteria. As an example, we want to add 5 to values larger than 2, and subtract by 5 otherwise:
np.where(x>2, x+5, x-5)
array([-4, -3, 8, 9])
Multi-dimensional arrays
The method where(~)
can also be used for multi-dimensional arrays:
np.where(x>2, 10, 5)
array([[5, 5], [10, 10]])