NumPy | where method
Start your free 7-days trial now!
where(~) method maps an array of booleans to the specified outputs, similar to how an
An array of booleans.
All instances of True will be replaced by x.
All instances of False will be replaced by y.
A Numpy array.
To replace all
True with 5, and all
False with 10:
x = np.array([True, True, False, False])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:
x = np.array([1,2,3,4])mask = x > 2maskarray([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:
x = np.array([1,2,3,4])np.where(x>2, x+5, x-5)array([-4, -3, 8, 9])
where(~) can also be used for multi-dimensional arrays:
x = np.array([[1,2],[3,4]])np.where(x>2, 10, 5)array([[5, 5],[10, 10]])