Signature
np.where(condition, x=None, y=None)What it does
With three arguments, np.where returns x where the condition is true and y elsewhere. With only a condition, it returns the indices where the condition is true.
Parameters
conditionarray_like of bool- The mask that selects between x and y.
xarray_like, optionaloptional- Values used where condition is true.
yarray_like, optionaloptional- Values used where condition is false.
Returns
ndarray or tuple of ndarrays
Example
pythonnp.where example
import numpy as np
values = np.array([-2, 0, 5])
print(np.where(values > 0, "positive", "non-positive"))Output
['positive' 'non-positive' 'positive']
Watch out for
- Both x and y must be provided to choose values.
- Boolean indexing with values[values > 0] is often simpler when you only need the kept values.