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])
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
If you print the even_arr_index
variable, you will get the following output
[False True False True False True False True False True]
Then you can assign even_arr_index
to the arr
to perform the filtration
even_arr = arr[even_arr_index]
If you print even_arr
, you will get the following result
array([ 2, 4, 6, 8, 10])
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)