Filtering Data with Boolean Indexing
Boolean indexing allows you to select array elements based on conditions. It is useful for identifying values that meet specific analytical criteria.
Applying Conditions to Arrays
import numpy as np
sales = np.array([12000, 18000, 9000, 25000, 15000])
condition = sales > 15000
print(condition)
print(sales[condition])Output:
[False True False True False]
[18000 25000]
The condition creates a Boolean array. Passing that array inside sales[] selects only the elements for which the condition is True.
You can perform the operation directly without storing the condition separately.
high_sales = sales[sales > 15000]
print(high_sales)
Combining Multiple Conditions
Use & for element-wise AND and | for element-wise OR. Enclose each comparison in parentheses.
sales = np.array([12000, 18000, 9000, 25000, 15000])
selected_sales = sales[
(sales >= 12000) & (sales <= 20000)
]
print(selected_sales)
This selects sales values between 12,000 and 20,000, inclusive.
Boolean indexing can also help identify invalid measurements or isolate observations for further analysis. For example, you can filter negative values when they are not valid for the particular measurement being analyzed.
Python for Data Science
Vishalini A








