NumPy Filter Array
π― NumPy Filtering Arrays (Complete Guide)
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
