NumPy Tutorial for Beginners: Arrays, Maths and Filtering in Python
P12.5 NumPy Boolean Indexing: Filter Arrays with Conditions
Why. Show only orders above ₹1,000. Filtering is the most used operation in data work, and pandas filters work exactly like this.
What. A comparison on an array gives an array of True/False called a mask. arr[mask] keeps only the True positions.
How.
Filter an array
- Write the condition:
arr > 1000. - Look at the mask (True/False).
- Use it inside brackets:
arr[arr > 1000]. - Combine conditions with
&and|, each in brackets.
Worked example A — Make a mask.
Step 1 — What we do. Order amounts at an online shop in Mumbai.
Step 2 — Type and run this code.
import numpy as np
amounts = np.array([450, 1200, 300, 2500, 800])
mask = amounts > 1000
print(mask)
Step 3 — Output you should see.
[False True False True False]
Step 4 — What it means. Each position says whether that order is above ₹1,000.
Worked example B — Filter and count.
Step 1 — What we do. Use the mask to keep and count the big orders.
Step 2 — Type and run this code.
import numpy as np
amounts = np.array([450, 1200, 300, 2500, 800])
big = amounts[amounts > 1000]
print(big)
print((amounts > 1000).sum())
Step 3 — Output you should see.
[1200 2500]
2
Step 4 — What it means. The filter keeps 1200 and 2500. Summing the mask counts True values: 2.
Worked example C — Two conditions.
Step 1 — What we do. Orders between ₹400 and ₹1,000.
Step 2 — Type and run this code.
import numpy as np
amounts = np.array([450, 1200, 300, 2500, 800])
mid = amounts[(amounts >= 400) & (amounts <= 1000)]
print(mid)
Step 3 — Output you should see.
[450 800]
Step 4 — What it means. Use & for and, | for or, and put brackets around each condition. pandas filters use the same rule.
Worked example D — Replace values with np.where.
Step 1 — What we do. Label orders as "High" or "Normal".
Step 2 — Type and run this code.
import numpy as np
amounts = np.array([450, 1200, 300, 2500, 800])
labels = np.where(amounts > 1000, "High", "Normal")
print(labels)
Step 3 — Output you should see.
['Normal' 'High' 'Normal' 'High' 'Normal']
Step 4 — What it means. np.where(condition, yes, no) is a one-line if for a whole array. Very common in pandas too.
Ravindra Bagale's Tip
Remember the brackets: (a > 1) & (a < 5). Without them Python reads it in the wrong order and gives an error.
Ravindra Bagale's Tip – मराठी
Brackets लक्षात ठेवा: (a > 1) & (a < 5). त्याशिवाय Python चुकीच्या क्रमाने वाचतो आणि error देतो.
Ravindra Bagale's Tip – हिंदी
Brackets याद रखो: (a > 1) & (a < 5). उनके बिना Python गलत क्रम में पढ़ता है और error देता है.