Boolean Mask Indexing & Fancy Slicing
1Concept
Boolean indexing uses a boolean condition array to filter elements satisfying a predicate. Fancy indexing uses integer index arrays to extract arbitrary elements, creating a deep copy rather than a view.
2Architecture Diagram
Array: [ 10, 25, 30, 45, 50 ] Mask: [ F, T, F, T, T ] (arr > 20) Result: [ 25, 45, 50 ]
3Code Example
Python 3.12
data = [10, 25, 32, 18, 55, 40]
# Boolean filtering logic
threshold = 30
filtered = [x for x in data if x > threshold]
print(f"Original: {data}")
print(f"Filtered (data > {threshold}): {filtered}")4Expected Output
Original: [10, 25, 32, 18, 55, 40] Filtered (data > 30): [32, 55, 40]
5Key Takeaways
- ✓Boolean mask indexing creates a COPY, not a view.
- ✓Combine conditions using bitwise operators (`&` for AND, `|` for OR, `~` for NOT) with parentheses.
- ✓Fancy indexing (`arr[[0, 2, 4]]`) extracts arbitrary indices in specified order.