How to Create a Filter Array That Returns Only Designated Values in NumPy


In this example we will show how to create a filter array that will return only designated values using the for loop in Python NumPy.

Source Code

import numpy as np

n = np.array([5, 6, 7, 8, 9, 10, 11, 12])

# Create an empty list to store Boolean values.
filter_boolean = []

for item in n:
    # if the element is less than 9, set the value to True, otherwise False
    if item < 9:
        filter_boolean.append(True)
    else:
        filter_boolean.append(False)

filter_n = n[filter_boolean]

print(filter_boolean)
print(filter_n)

Output:

[True, True, True, True, False, False, False, False]
[5 6 7 8]
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments