Skip to main content

NumPy: Creating the Filter Array

When we filter out some elements from the given array using some conditions to create a new array out of them is called filtering. In Numpy we use a boolean index list for filtering an array. Boolean index list is the type of list containing booleans corresponding to indexes in an array.

If the value at an index is True, that particular element is contained forward in the filtered array. If the value at that index is False that element is excluded from that filtered array.

Syntax:

filter(func,sequence)

1. Creating the filter array:

We can easily create the filter array by using the condition.

Example:

import numpy as np
a=np.array([30,50,16,40,27])
#Create an empty list
filter_a=[]
# Use for loop to iterate through elements in a
for values in a:
  # if the elements divisible by 5 set the value to True, otherwise False:
  if values%5==0:
    filter_a.append(True)
  else:
    filter_a.append(False)

new_array=a[filter_a]
print("Filtered Array=",filter_a)
print("After filtering array=",new_array)

Output:

Filtered Array= [True, True, False, True, False]
After filtering array= [30 50 40]

2. Creating Filter Directly From Array

In this method, We can directly do filtering on an array without iterating each element in the given condition and we will get the same filtered array.

Example:

import numpy as np
a=np.array([30,50,16,40,27])
filter_a=a%5==0
new_array=a[filter_a]
print("Filtered Array=",filter_a)
print("After filtering array=",new_array)

Output:

Filtered Array= [ True  True False  True False]
After filtering array= [30 50 40]
Submitted by devanshi.srivastava on September 8, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.