How to Use NumPy where() With Multiple Conditions

The NumPy where() function can be used to filter an array with multiple conditions. It takes an array of Boolean values as its argument and returns the elements from the original array that correspond to the True values. This is a powerful way to filter and manipulate data in Python, allowing you to apply complex logic to your data.


You can use the following methods to use the NumPy 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

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

x