NumPy Filter Array

M.Ramya

 Filtering Arrays in NumPy

Filtering an array means extracting specific elements from an existing array to create a new array.

In NumPy, filtering is done using a boolean index array.

A boolean index array contains True or False values corresponding to each element in the original array.

If the value is True, the element is included in the new array.

If the value is False, the element is excluded.

Program:

Select elements at index 0 and 2:

import numpy as np

arr = np.array([41, 42, 43, 44])

x = [True, False, True, False]

newarr = arr[x]

print(newarr)

Output:

[41 43]

Explanation:

Only the elements at positions where True appears in the filter (index 0 and index 2) are included.

Creating a Filter Array

In the above example, we manually defined the boolean list. However, in real cases, we often create filters using conditions.

Program:

Filter out elements greater than 42:

import numpy as np

arr = np.array([41, 42, 43, 44])

filter_arr = []

for element in arr:

    if element > 42:

        filter_arr.append(True)

    else:

        filter_arr.append(False)

newarr = arr[filter_arr]

print(filter_arr)

print(newarr)

Output:

[False, False, True, True]
[43 44]

Program:

Filter even numbers:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

filter_arr = []

for element in arr:

    if element % 2 == 0:

        filter_arr.append(True)

    else:

        filter_arr.append(False)

newarr = arr[filter_arr]

print(filter_arr)

print(newarr)

Output:

[False, True, False, True, False, True, False]
[2 4 6]

Efficient Filtering Using Array Conditions

Instead of using loops, you can directly apply conditions on NumPy arrays to create boolean filters.

Program:

Filter values greater than 42:

import numpy as np

arr = np.array([41, 42, 43, 44])

filter_arr = arr > 42

newarr = arr[filter_arr]

print(filter_arr)

print(newarr)

Output:

[False False True True]
[42 44]

Program:

Filter even numbers:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

filter_arr = arr % 2 == 0

newarr = arr[filter_arr]

print(filter_arr)

print(newarr)

Output:

[False True False True False True False]
[2 4 6]

This method is faster, more concise, and is preferred when working with NumPy arrays.


Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send