Array Indexing, Multi-Axis Slicing, Boolean Masking & np.where
Overview & Learning Objectives
Extracting subsets of data across rows, columns, and higher-order tensors is central to numerical analytics. NumPy allows simultaneous multi-axis slicing `arr[rows, cols]` without nested list loops. Boolean masking enables lightning-fast conditional filtering, allowing analysts to extract records meeting complex business rules at native hardware speed.
- Extract rows, columns, and sub-matrices using 2D slicing `arr[start:stop, start:stop]`.
- Filter records conditionally using boolean masks (`arr[arr > threshold]`).
- Combine multiple logical conditions using bitwise operators (`&`, `|`, `~`).
- Execute vectorized conditional branching using `np.where()`.
Industry Standard
Standard: Analytics pipelines at Zepto and Blinkit use boolean masks on NumPy matrices to filter out cancelled orders and calculate on-time delivery rates across dark stores in under 5 milliseconds.
Real-World Example: ScoopCraft Inventory Outlier Filtering
ScoopCraft analyzes a 4x4 matrix of outlet stock quantities to identify stores with stockout risks (< 20 units) or excess holding (> 100 units).
| Store / Category | Tubs | Cones | Bars | Sundaes |
|---|---|---|---|---|
| Store 1 (Koramangala) | 120 (Excess) | 15 (Stockout) | 45 | 60 |
| Store 2 (Indiranagar) | 85 | 40 | 18 (Stockout) | 55 |
| Store 3 (HSR Layout) | 110 (Excess) | 65 | 80 | 12 (Stockout) |
| Store 4 (Whitefield) | 40 | 50 | 35 | 70 |
Functions & Methods Covered in this Chapter
Here is the definition, execution syntax, parameter breakdown, and real-world business example for each function/method covered in this chapter:
np.where(condition, [x, y])
Definition: Vectorized ternary operator returning elements chosen from x or y depending on condition.
status = np.where(sales > 1000, "High", "Normal")
condition: Boolean array or condition expression.x: Value or array returned when condition is True.y: Value or array returned when condition is False.
delivery_status = np.where(transit_mins > 20, "Delayed", "On-Time")np.select(condlist, choicelist, default=0)
Definition: Evaluates an ordered list of boolean conditions and returns elements from corresponding choice lists.
tier = np.select([spend >= 5000, spend >= 2000], ["Gold", "Silver"], default="Bronze")
condlist: List of boolean conditions (arrays).choicelist: List of arrays or scalar choices matching condlist.default: Default value if no condition evaluates to True.
tiers = np.select([spend >= 10000, spend >= 5000], ["Platinum", "Gold"], default="Silver")np.clip(a, a_min, a_max)
Definition: Clips (limits) the values in an array between designated minimum and maximum threshold values.
bounded_scores = np.clip(ratings, 1.0, 5.0)
a: Input array with numeric values.a_min: Lower boundary. Values smaller than a_min are set to a_min.a_max: Upper boundary. Values larger than a_max are set to a_max.
approved_discounts = np.clip(raw_discounts, 0.05, 0.40)Common Mistakes & Limitations
- Omitting parentheses around boolean conditions: `arr > 10 & arr < 50` fails due to operator precedence where `&` binds tighter than `>`. Always write `(arr > 10) & (arr < 50)`.
- Confusing basic slicing (returns a memory view) with fancy integer indexing (creates an independent copy).
Keyboard Shortcuts (Jupyter & VS Code)
| Action | Windows | Mac |
|---|---|---|
| Select Entire Column across All Rows | arr[:, col_idx] | arr[:, col_idx] |
| Select Entire Row across All Columns | arr[row_idx, :] | arr[row_idx, :] |
Pro Tips & Modern Best Practices
- Use `np.select()` when you have 3 or more tiered conditional branches instead of nested `np.where()`.
- Use `np.extract(condition, arr)` for clean functional extraction of elements.