Home » How to Filter a NumPy Array (4 Examples)

How to Filter a NumPy Array (4 Examples)

by Erma Khan

You can use the following methods to filter the values in a NumPy array:

Method 1: Filter Values Based on One Condition

#filter for values less than 5
my_array[my_array 5]

Method 2: Filter Values Using “OR” Condition

#filter for values less than 5 or greater than 9
my_array[(my_array 5) | (my_array > 9)]

Method 3: Filter Values Using “AND” Condition

#filter for values greater than 5 and less than 9
my_array[(my_array > 5) & (my_array 9)]

Method 4: Filter Values Contained in List

#filter for values that are equal to 2, 3, 5, or 12
my_array[np.in1d(my_array, [2, 3, 5, 12])]

This tutorial explains how to use each method in practice with the following NumPy array:

import numpy as np

#create NumPy array
my_array = np.array([1, 2, 2, 3, 5, 6, 7, 10, 12, 14])

#view NumPy array
my_array

array([ 1,  2,  2,  3,  5,  6,  7, 10, 12, 14])

Example 1: Filter Values Based on One Condition

The following code shows how to filter values in the NumPy array based on just one condition:

#filter for values less than 5
my_array[(my_array 5)]

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

#filter for values greater than 5
my_array[(my_array > 5)]

array([ 6,  7, 10, 12, 14])

#filter for values equal to 5
my_array[(my_array == 5)]

array([5])

Example 2: Filter Values Using “OR” Condition

The following code shows how to filter values in the NumPy array using an “OR” condition:

#filter for values less than 5 or greater than 9
my_array[(my_array 5) | (my_array > 9)]

array([ 1,  2,  2,  3, 10, 12, 14])

This filter returns the values in the NumPy array that are less than 5 or greater than 9.

Example 3: Filter Values Using “AND” Condition

The following code shows how to filter values in the NumPy array using an “AND” condition:

#filter for values greater than 5 and less than 9
my_array[(my_array > 5) & (my_array 9)]

array([6, 7])

This filter returns the values in the NumPy array that are greater than 5 and less than 9.

Example 4: Filter Values Contained in List

The following code shows how to filter values in the NumPy array that are contained in a list:

#filter for values that are equal to 2, 3, 5, or 12
my_array[np.in1d(my_array, [2, 3, 5, 12])]

array([ 2,  2,  3,  5, 12])

This filter returns only the values that are equal to 2, 3, 5, or 12.

Note: You can find the complete documentation for the NumPy in1d() function here.

Additional Resources

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

How to Filter Pandas DataFrame Rows that Contain a Specific String
How to Filter a Pandas DataFrame on Multiple Conditions
How to Use “NOT IN” Filter in Pandas DataFrame

Related Posts