Skip to content

NumPy filter array by condition | Example code

  • by

Use NumPy extract() or Where() function to filter array by condition.

NumPy filter array by condition example

Simple example code NumPy filter using condition on each element.

Using NumPy.extract:

import numpy as np

na = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
res = np.extract(na % 2 == 0, na)

print(res)

Output:

NumPy filter array by condition

Using NumPy.where:

import numpy as np

na = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
res = na[np.where(na % 2 == 0)]

print(res)

Output: [ 2 4 6 8 10]

How to efficiently filter elements in a NumPy array by value in Python?

Answer: Use boolean indexing to filter elements in an array by value to filter NumPy Array.

import numpy as np

na = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
res = na[na > 4]

print(res)

Output: [ 5 6 7 8 9 10]

Do comment if you have any doubts or suggestions on this NumPy Array topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *