NumPy Filter Array

🎯 NumPy Filter Array

Filtering means selecting elements based on a condition and creating a new array from matching values.

NumPy uses boolean indexing to filter arrays.


 1. Basic Filtering with a Boolean List


 

Output:

[10 30 50]

2. Filtering Using a Condition (Most Useful)

You don’t need to manually write True/False.
NumPy automatically creates a boolean array:


 

Output:

[False False False True True]

Use it for filtering:



 

Output:

[20 25]

🧠 Common Filtering Conditions

Condition Example
Greater than arr > 10
Less than arr < 5
Equal to arr == 20
Not equal to arr != 15
Range filter (arr > 10) & (arr < 30)
Even numbers arr % 2 == 0

 Example: Filter Even Numbers


 

Output:

[2 4 6]

 Example: Filter Items Between 10 and 50


 


🔁 Filtering on Strings


 


🧱 Filtering a 2D Array


 

Output:

[25 30 40 55]

(Filtering always returns a 1D array unless using advanced reshaping.)


🧪 Real Example: Remove Negative Values


 


🎯 Summary

Feature Example
Create boolean filter filter = arr > 10
Apply filter result = arr[filter]
Combine filters (arr > 10) & (arr < 30)
Filter even numbers arr[arr % 2 == 0]

🚀 Practice Exercise

Use this array:

arr = np.array([5, 12, 7, 24, 50, 3, 18])

Find:

1️⃣ Numbers greater than 10
2️⃣ Even numbers
3️⃣ Numbers between 10–30
4️⃣ Numbers not equal to 24

You may also like...