Python for Data Analytics & AutomationLesson 13 of 41
Lesson 13 of 41

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 / CategoryTubsConesBarsSundaes
Store 1 (Koramangala)120 (Excess)15 (Stockout)4560
Store 2 (Indiranagar)854018 (Stockout)55
Store 3 (HSR Layout)110 (Excess)658012 (Stockout)
Store 4 (Whitefield)40503570

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:

Function 1

np.where(condition, [x, y])

Definition: Vectorized ternary operator returning elements chosen from x or y depending on condition.

Syntax / Code Pattern:
status = np.where(sales > 1000, "High", "Normal")
Parameters Breakdown:
  • condition: Boolean array or condition expression.
  • x: Value or array returned when condition is True.
  • y: Value or array returned when condition is False.
Real-World Example (Order Delivery SLA Compliance Flag):
Problem / Scenario: Flag delivery trips taking more than 20 minutes as "Delayed", else "On-Time".
Code / Expression: delivery_status = np.where(transit_mins > 20, "Delayed", "On-Time")
Result: np.array(["On-Time", "Delayed", "On-Time", ...])
Why it works: Evaluates all delivery durations in C-speed vectorized memory without slow Python loops.
Function 2

np.select(condlist, choicelist, default=0)

Definition: Evaluates an ordered list of boolean conditions and returns elements from corresponding choice lists.

Syntax / Code Pattern:
tier = np.select([spend >= 5000, spend >= 2000], ["Gold", "Silver"], default="Bronze")
Parameters Breakdown:
  • condlist: List of boolean conditions (arrays).
  • choicelist: List of arrays or scalar choices matching condlist.
  • default: Default value if no condition evaluates to True.
Real-World Example (Customer Loyalty Tier Classification):
Problem / Scenario: Classify customers: Spend >= 10,000 -> "Platinum", >= 5,000 -> "Gold", else "Silver".
Code / Expression: tiers = np.select([spend >= 10000, spend >= 5000], ["Platinum", "Gold"], default="Silver")
Result: np.array(["Platinum", "Silver", "Gold", ...])
Why it works: Executes fast multi-branch conditional classification across millions of records.
Function 3

np.clip(a, a_min, a_max)

Definition: Clips (limits) the values in an array between designated minimum and maximum threshold values.

Syntax / Code Pattern:
bounded_scores = np.clip(ratings, 1.0, 5.0)
Parameters Breakdown:
  • 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.
Real-World Example (Discount Percentage Capping):
Problem / Scenario: Constrain promotional discounts between 5% minimum and 40% maximum allowable ceiling.
Code / Expression: approved_discounts = np.clip(raw_discounts, 0.05, 0.40)
Result: np.array([0.05, 0.25, 0.40, 0.15])
Why it works: Prevents rogue algorithmic outlier pricing errors from hurting store margins.

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)

ActionWindowsMac
Select Entire Column across All Rowsarr[:, col_idx]arr[:, col_idx]
Select Entire Row across All Columnsarr[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.