Filtering means selecting specific elements from an array based on a condition. In NumPy, we can filter arrays using Boolean conditions and Boolean indexing. This is useful for finding passing students, high sales, eligible employees, and other records that match specific requirements.
1. What is Array Filtering in NumPy?
Array filtering means extracting only those elements that satisfy a given condition.
For example, suppose we have student marks:
import numpy as np
marks = np.array([45, 80, 35, 90, 60])
result = marks[marks >= 50]
print(result)
Output:
[80 90 60]
Explanation:
marks >= 50checks whether each value is 50 or greater.- Only the values that satisfy the condition are selected.
- The result contains
80, 90, 60.
2. Creating a Boolean Array
A Boolean array contains only True and False values.
When we apply a condition to a NumPy array, NumPy creates a Boolean array.
Example:
import numpy as np
marks = np.array([45, 80, 35, 90, 60])
result = marks >= 50
print(result)
Output:
[False True False True True]
Explanation:
45 >= 50returnsFalse.80 >= 50returnsTrue.35 >= 50returnsFalse.90 >= 50returnsTrue.60 >= 50returnsTrue.
This Boolean array can be used to filter the original array.
3. Filtering an Array Using True and False Values
You can directly use a Boolean array inside square brackets to filter elements.
Example:
import numpy as np
numbers = np.array([10, 20, 30, 40, 50])
filter_values = np.array([True, False, True, False, True])
result = numbers[filter_values]
print(result)
Output:
[10 30 50]
Explanation:
Trueselects the element at that position.Falseskips the element at that position.- Therefore, only
10, 30, 50are selected.
The Boolean array must have a compatible shape with the array being filtered.
4. Filtering Values Greater Than a Number
You can filter an array to select values greater than a specific number.
Example:
import numpy as np
sales = np.array([12000, 25000, 8000, 40000, 18000])
result = sales[sales > 15000]
print(result)
Output:
[25000 40000 18000]
Explanation:
sales > 15000checks every sales value.- Values greater than 15,000 are selected.
- Values equal to or below 15,000 are excluded.
5. Filtering Values Less Than a Number
You can use the less-than operator (<) to select smaller values.
Example:
import numpy as np
prices = np.array([500, 1200, 800, 2000, 300])
result = prices[prices < 1000]
print(result)
Output:
[500 800 300]
Explanation:
Only prices below 1,000 are selected from the original array.
6. Filtering Using Equal To and Not Equal To
You can filter array elements using the equal-to (==) and not-equal-to (!=) operators.
Example 1: Equal To
import numpy as np
numbers = np.array([10, 20, 30, 20, 40])
result = numbers[numbers == 20]
print(result)
Output:
[20 20]
Example 2: Not Equal To
import numpy as np
numbers = np.array([10, 20, 30, 20, 40])
result = numbers[numbers != 20]
print(result)
Output:
[10 30 40]
Explanation:
==selects elements equal to the given value.!=selects elements that are different from the given value.
7. Filtering Using Multiple Conditions
You can apply more than one condition while filtering a NumPy array.
NumPy uses:
&for AND (both conditions must be true).|for OR (at least one condition must be true).
Always put each condition inside parentheses.
Example 1: Using AND (&)
import numpy as np
marks = np.array([35, 55, 65, 80, 95])
result = marks[(marks >= 50) & (marks <= 80)]
print(result)
Output:
[55 65 80]
Explanation:
Both conditions must be satisfied:
- Marks must be greater than or equal to 50.
- Marks must be less than or equal to 80.
Example 2: Using OR (|)
import numpy as np
marks = np.array([35, 55, 65, 80, 95])
result = marks[(marks < 40) | (marks > 90)]
print(result)
Output:
[35 95]
Explanation:
An element is selected if either condition is true:
- Marks are below 40.
- Marks are above 90.
8. Filtering a 2-D NumPy Array
You can also filter elements from a two-dimensional array using conditions.
Example:
import numpy as np
sales = np.array([
[10000, 25000, 30000],
[15000, 40000, 20000],
[5000, 18000, 35000]
])
result = sales[sales > 20000]
print(result)
Output:
[25000 30000 40000 35000]
Explanation:
sales > 20000checks every element in the 2-D array.- Only values greater than 20,000 are selected.
- The filtered result is a one-dimensional array.
9. Filtering a 2-D Array Using Row Conditions
Sometimes, you need to select complete rows based on a particular column’s values.
Example:
import numpy as np
employees = np.array([
[101, 25000],
[102, 40000],
[103, 18000],
[104, 50000]
])
result = employees[employees[:, 1] > 30000]
print(result)
Output:
[[102 40000]
[104 50000]]
Explanation:
employees[:, 1]selects the salary column.employees[:, 1] > 30000checks which employees earn more than 30,000.- The Boolean condition selects the complete matching rows.
This technique is useful for filtering employee records based on salary, department codes, or other columns.
10. Filtering an Array Using np.where()
The np.where() function can also be used to filter values based on a condition.
Example:
import numpy as np
marks = np.array([35, 60, 45, 90, 75])
result = np.where(marks >= 50, marks, 0)
print(result)
Output:
[ 0 60 0 90 75]
Explanation:
The np.where() function uses three arguments:
np.where(condition, value_if_true, value_if_false)
condition: Checks whether marks are 50 or greater.value_if_true: Keeps the original mark when the condition is true.value_if_false: Replaces the value with0when the condition is false.
Important: Unlike Boolean indexing, this example keeps the original array length and replaces values that do not satisfy the condition.
11. Filtering an Array Using np.isin()
The np.isin() function checks whether each array element exists in a given list of values. It returns a Boolean array that can be used for filtering.
Example:
import numpy as np
numbers = np.array([10, 20, 30, 40, 50, 60])
result = numbers[np.isin(numbers, [20, 40, 60])]
print(result)
Output:
[20 40 60]
Explanation:
np.isin(numbers, [20, 40, 60])checks whether each number exists in the given list.- Matching elements return
True. - Boolean indexing selects only the matching values.
12. Difference Between Boolean Indexing, where() and isin()
| Method | Purpose |
|---|---|
| Boolean Indexing | Selects elements that satisfy a condition |
np.where() | Returns indexes or selects/replaces values based on conditions |
np.isin() | Checks whether elements exist in a specified collection |
Student Task
Create the following NumPy array:
import numpy as np
student_marks = np.array([35, 55, 75, 90, 42, 65, 88])
Complete these tasks:
- Select marks greater than 60.
- Select marks less than 50.
- Select marks equal to 75.
- Select marks between 50 and 90 (inclusive).
- Select marks below 40 or above 85.
- Create a Boolean array to check which students scored 60 or more.
- Use
np.where()to replace marks below 40 with0.
Final Student Challenge: Create an Employee Salary Filter
A company maintains employee IDs and their monthly salaries.
import numpy as np
employees = np.array([
[101, 25000],
[102, 45000],
[103, 30000],
[104, 55000],
[105, 18000],
[106, 40000]
])
Complete these tasks:
- Select employees earning more than 30,000.
- Select employees earning less than 25,000.
- Select employees earning between 25,000 and 45,000 (inclusive).
- Select employees earning below 20,000 or above 50,000.
- Use
np.isin()to select employee IDs 102, 104, and 106. - Use
np.where()to replace salaries below 30,000 with0.
Key Takeaways
- Filtering selects array elements based on conditions.
- NumPy Boolean Indexing conditions return
TrueorFalse. - Boolean indexing selects elements where the condition is
True. &represents AND, while|represents OR.np.where()can select or replace values based on a condition.np.isin()checks whether elements exist in a given collection.- NumPy supports filtering in both 1-D and 2-D arrays.
Frequently Asked Questions (FAQs)
1. What is NumPy Array Filtering in Python?
NumPy Array Filtering is used to select specific elements from an array based on given conditions. It allows you to extract values that meet certain requirements using Boolean conditions and indexing.
2. What is NumPy Boolean Indexing?
NumPy Boolean Indexing is a technique used to access or filter array elements using Boolean values (True and False). It returns only the elements whose corresponding condition evaluates to True.
3. How do you filter a NumPy Array in Python?
You can filter a NumPy Array by applying a condition inside square brackets. The condition creates a Boolean array that selects only the matching elements.
Example:
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
result = arr[arr > 25]
print(result)
Output:
[30 40 50]
4. What is the NumPy where() function used for?
The NumPy where() function is used to find the index positions of elements that satisfy a given condition. It can also return selected values based on a condition when two alternative values are provided.
Example: np.where(arr > 25)
5. What is the NumPy Filter Function?
NumPy does not provide a dedicated function named filter(). Instead, you can use Boolean Indexing, np.where(), and other condition-based techniques to filter NumPy Array elements.
6. What is the difference between NumPy Boolean Indexing and the where() function?
Boolean Indexing directly selects elements that satisfy a condition, whereas the where() function returns their index positions when used with a single condition. It can also select between two sets of values using its three-argument form.
7. Can we apply multiple conditions to filter a NumPy Array?
Yes, you can apply multiple conditions using operators such as & (AND) and | (OR). Each condition should be enclosed in parentheses.
Example: arr[(arr > 20) & (arr < 50)]
8. Why is NumPy Array Filtering important in Python?
NumPy Array Filtering helps extract relevant data, remove unwanted values, identify specific records, and perform condition-based analysis. It is widely used in data analysis, scientific computing, and machine learning.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
