# NumPy filter array by condition | Example code

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:

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 and suggestions on this NumPy Array topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.