This code filters elements of arr that are greater than 20 using boolean indexing.
Execution Table
Step
Action
Expression
Result
1
Create array
arr = np.array([10, 15, 20, 25, 30])
[10 15 20 25 30]
2
Apply condition > 20
mask = arr > 20
[False False False True True]
3
Filter array using mask
filtered = arr[mask]
[25 30]
4
Print filtered array
print(filtered)
[25 30]
💡 Filtering done, only elements > 20 selected
Variable Tracker
Variable
Start
After Step 1
After Step 2
After Step 3
Final
arr
undefined
[10 15 20 25 30]
[10 15 20 25 30]
[10 15 20 25 30]
[10 15 20 25 30]
mask
undefined
undefined
[False False False True True]
[False False False True True]
[False False False True True]
filtered
undefined
undefined
undefined
[25 30]
[25 30]
Key Moments - 3 Insights
Why does the mask array contain True and False values?
The mask is created by checking each element of arr against the condition arr > 20. Elements greater than 20 get True, others get False, as shown in step 2 of the execution_table.
How does arr[mask] select elements?
arr[mask] picks elements where mask is True. It ignores elements where mask is False. This is shown in step 3 where filtered contains only [25 30].
Can the mask array be used directly for filtering without creating a new variable?
Yes, you can use arr[arr > 20] directly. Creating mask separately helps understand the process, but both ways produce the same filtered result.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, what is the value of mask?
A[False False False True True]
B[True True True False False]
C[False True False True False]
D[True False True False True]
💡 Hint
Check the 'Result' column for step 2 in execution_table.
At which step does the filtered array get its final values?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'filtered' variable in variable_tracker and execution_table step 3.
If the condition changes to arr >= 25, what would be the filtered array?
A[25 30]
B[20 25 30]
C[30]
D[15 20 25 30]
💡 Hint
Consider which elements in arr are greater than or equal to 25.
Concept Snapshot
Boolean indexing filters arrays by creating a boolean mask.
Syntax: filtered = arr[condition]
Condition returns True/False for each element.
Only elements with True are selected.
Useful for quick filtering without loops.
Full Transcript
Boolean indexing in numpy lets you filter arrays easily. You start with an array, then create a boolean mask by applying a condition to each element. This mask has True where the condition is met and False elsewhere. Using this mask to index the array returns only the elements where the mask is True. For example, arr > 20 creates a mask that is True for elements greater than 20. Then arr[mask] returns those elements. This method is simple and fast for filtering data.