/Curriculum/Core NumPyData Access

10. Advanced & Boolean IndexingIntermediate

Boolean masking, conditional filtering, and index array selection.

15 mins

Concept Overview

Boolean indexing lets you filter array elements using condition expressions like `arr > 25`. NumPy creates a boolean mask and extracts all elements where the condition is True.

Hardware Mental Model

A boolean mask is a stencil with holes cut out wherever your condition is True. Placing the stencil over the array lets only matching numbers pass through.

Key Concepts (1)Click snippet to load in editor

Expressions like `arr > 20` evaluate element-wise into an array of booleans `[False, True, ...]`. Passing this mask into `arr[mask]` filters elements.

filtered = arr[arr > 20]

⚠ Common Mistakes & Pitfalls

Avoid these frequent beginner syntax and logic traps
❌ Incorrect:filtered = arr[arr > 10 and arr < 50] # Python 'and' fails on arrays
✓ Correct:filtered = arr[(arr > 10) & (arr < 50)]

Use bitwise `&` (AND) and `|` (OR) with parentheses for multiple conditions in NumPy.

Pro Tip: Always wrap individual conditions in parentheses: `(arr > 10) & (arr < 50)`.

📌 Quick Revision

Core takeaway points from this topic
Boolean masks evaluate conditions element-wise.
`arr[arr > threshold]`: Filters data matching condition.
Use `&` for AND, `|` for OR, `~` for NOT.
Advanced indexing returns a copy, not a view.
Editor: 10. Advanced & Boolean Indexing
Python ● Ready
Initializing Python IDE...
Ctrl+Enter
Execution Result
Click "RUN CODE" to execute and inspect array state

🎯 Try It Yourself: Practice Challenge

Hands-on Mode

Solve the objective below using NumPy vectorized syntax

Objective:Filter Even Numbers

Create `arr = np.array([10, 15, 20, 25, 30])`, filter all elements greater than 18 using `arr[arr > 18]`, and print.

Expected Output Target:[20 25 30]
Practice Workspace
Python ● Ready
Initializing Python IDE...
Ctrl+Enter
Execution Result
Click "RUN CODE" to execute and inspect array state