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:
2. Filtering Using a Condition (Most Useful)
You don’t need to manually write True/False.
NumPy automatically creates a boolean array:
Output:
Use it for filtering:
Output:
🧠 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:
Example: Filter Items Between 10 and 50
🔁 Filtering on Strings
🧱 Filtering a 2D Array
Output:
(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:
Find:
1️⃣ Numbers greater than 10
2️⃣ Even numbers
3️⃣ Numbers between 10–30
4️⃣ Numbers not equal to 24
