The numpy.where() method returns a new array based on a condition applied to each element of an array.
where() Syntax
The syntax of where() is:
numpy.where(condition, x, y)
where() Arguments
The where() method takes three arguments:
condition- a boolean or an arrayx- value to take if theconditionisTruey- value to take if theconditionisFalse
We can also pass a single argument to np.where(). To learn about it, visit np.where() with a single argument section below.
where() Return Value
The where() method returns a new NumPy array.
Example 1: numpy.where() With Two Arrays
Output
[1 2 30 40]
Example 2: numpy.where() with Operation
We can also use numpy.where() to perform operations on array elements.
Output
[1 2 3 4]
Example 3: where() with Array Condition
We can use array_like objects (such as lists, arrays etc.) as a condition in the where() method.
Output
[[1 2] [-3 -4]] [[1 -2] [-3 4]]
Example 4: where() with Multiple Conditions
The test condition in a where() method may have multiple conditions.
We use
- the
|operator to performORoperation on multiple conditions - the
&operator to performANDoperation on multiple conditions
Output
[1 0 0 0 0 0 7] [0 0 3 4 5 0 0]
Example 5: where() with Only One Argument
If we pass a single argument (test condition) to numpy.where(), it tells us where in a given array the given condition is met by returning the indices.
Output
(array([4, 5, 6, 7], dtype=int64), )