How to Use NumPy where() With Multiple Conditions


You can use the following methods to use the NumPy where() function with multiple conditions:

Method 1: Use where() with OR

#select values less than five or greater than 20
x[np.where((x < 5) | (x > 20))]

Method 2: Use where() with AND

#select values greater than five and less than 20
x[np.where((x > 5) & (x < 20))]

The following example shows how to use each method in practice.

Method 1: Use where() with OR

The following code shows how to select every value in a NumPy array that is less than 5 or greater than 20:

import numpy as np

#define NumPy array of values
x = np.array([1, 3, 3, 6, 7, 9, 12, 13, 15, 18, 20, 22])

#select values that meet one of two conditions
x[np.where((x < 5) | (x > 20))]

array([ 1,  3,  3, 22])

Notice that four values in the NumPy array were less than 5 or greater than 20.

You can also use the size function to simply find how many values meet one of the conditions:

#find number of values that are less than 5 or greater than 20
(x[np.where((x < 5) | (x > 20))]).size

4

Method 2: Use where() with AND

The following code shows how to select every value in a NumPy array that is greater than 5 and less than 20:

import numpy as np

#define NumPy array of values
x = np.array([1, 3, 3, 6, 7, 9, 12, 13, 15, 18, 20, 22])

#select values that meet two conditions
x[np.where((x > 5) & (x < 20))]

array([6,  7,  9, 12, 13, 15, 18])

The output array shows the seven values in the original NumPy array that were greater than 5 and less than 20.

Once again, you can use the size function to find how many values meet both conditions:

#find number of values that are greater than 5 and less than 20
(x[np.where((x > 5) & (x < 20))]).size

7

Additional Resources

The following tutorials explain how to perform other common operations in NumPy:

How to Calculate the Mode of NumPy Array
How to Find Index of Value in NumPy Array
How to Map a Function Over a NumPy Array

Leave a Reply

Your email address will not be published.