DEV Community

TechPlygrnd
TechPlygrnd

Posted on

NumPy Tutorial #13: Array Filtering

In this blog, I will show you how to filter an array in NumPy.


Filter

NumPy has provided us a functionality to perform a filtration. Let me show you how to use it.

First, let us create an array

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Enter fullscreen mode Exit fullscreen mode

Then, perform filtration. In this example, I want to filter out the odd numbers from the array. To achieve this, First I will create an expression of even number as the following

even_arr_index = arr % 2 == 0
Enter fullscreen mode Exit fullscreen mode

If you print the even_arr_index variable, you will get the following output

[False  True False  True False  True False  True False  True]
Enter fullscreen mode Exit fullscreen mode

Then you can assign even_arr_index to the arr to perform the filtration

even_arr = arr[even_arr_index]
Enter fullscreen mode Exit fullscreen mode

If you print even_arr, you will get the following result

array([ 2,  4,  6,  8, 10])
Enter fullscreen mode Exit fullscreen mode

There you go, that is how you can filter a NumPy array. Thank you for reading this blog and see you next time!

Top comments (0)