. Advertisement .
. Advertisement .
Numpy in Python comes with various library functions, allowing users to create an array from another one’s satisfied conditions. The
numpy.where() function is used to return the elements’ indices in the given condition.
numpy.where(condition[, x, y])
- x, y: these two values should be broadcastable to some shapes with the given condition.
- condition: it will yield x when True. Otherwise, it yields y.
The following article will introduce useful methods to implement
numpy.where() multiple conditions.
How To Implement Numpy.where() Multiple Conditions
Method 1: Implement With The & Operator In Python
Elements in an array can be selected with the
numpy.where() function after you apply a specific condition. For multiple conditions at once, the
& operator should be used to accomplish the task.
Enclose each condition in a parenthesis pair and use a
& between them:
import numpy as np values = np.array([1,2,3,4,5]) result = values[np.where((values>2) & (values<4))] print(result)
In the example above, the values selected from the integer array are greater than 2 and less than 4. The values also come with the
& operator and
Method 2: Implement With The | Operator
| operator can also be used to specify various conditions in the
numpy.where() option. It shows a logical OR Python gate and encloses each condition with a
| operator between two conditions.
import numpy as np values = np.array([1,2,3,4,5]) result = values[np.where((values>2) | (values%2==0))] print(result)
[2 3 4 5]
Here, you select the values from the list of integers, which are greater than 2 or divisible by 2. The returned values are stored in the result variable.
Method 3: Implement With The numpy.logical_and() Function
This option is useful for calculating the
AND gate’s element-wise truth value. Inside the desired
numpy.where, you can use it to specify numerous conditions.
import numpy as np values = np.array([1,2,3,4,5]) result = values[np.where(np.logical_and(values>2,values<4))] print(result)
Like the first method, this one also chooses values from the integer array with the values more than 2 yet less than 4.
Method 4: Implement With The numpy.logical_or() Function
You can use the
numpy.logical_or() option side the
numpy.where() to calculate the element-wise truth value. This way, easily specify various conditions.
import numpy as np values = np.array([1,2,3,4,5]) result = values[np.where(np.logical_or(values>2,values%2==0))] print(result)
[2 3 4 5]
All the chosen values from the array of integers are valued more than 2 or divisible by 2.
There are four main methods to implement
numpy.where() multiple conditions. Our post has explained them clearly with detailed examples. Each case should be dealt with by a specific method. Therefore, check the article again to get the best one.