Statistical & Mathematical Aggregations (mean, median, std, Axis Rules)
Overview & Learning Objectives
Statistical reductions collapse high-dimensional matrices into actionable scalar metrics or summary vectors. The `axis` parameter defines the direction of reduction: `axis=0` collapses rows (calculating metrics down each column), while `axis=1` collapses columns (calculating metrics across each row). Understanding axis rules is fundamental for data analytics.
- Compute core summary statistics: `np.mean()`, `np.median()`, `np.std()`, `np.var()`.
- Understand the direction of reduction for `axis=0` vs `axis=1`.
- Locate peak and trough indices using `np.argmax()` and `np.argmin()`.
- Calculate quantiles and outlier percentiles using `np.percentile()`.
Industry Standard
Standard: Production metric calculation engines at Swiggy and Zomato enforce using `np.nanmean` and `np.nanmedian` over standard statistics to prevent unhandled missing values from returning `NaN` summaries.
Real-World Example: ScoopCraft Dark-Store Performance Benchmarking
ScoopCraft analyzes a 4x3 matrix of revenue numbers across 4 regional outlets and 3 daily shifts (Morning, Afternoon, Evening).
| Dark Store Outlet | Morning (₹) | Afternoon (₹) | Evening (₹) | Store Total (axis=1) |
|---|---|---|---|---|
| Store 1 (Koramangala) | 12,500 | 18,200 | 35,000 | ₹65,700 |
| Store 2 (Indiranagar) | 15,000 | 22,400 | 42,000 | ₹79,400 |
| Store 3 (HSR Layout) | 9,800 | 14,500 | 28,000 | ₹52,300 |
| Store 4 (Whitefield) | 11,200 | 16,800 | 31,500 | ₹59,500 |
| Shift Total (axis=0) | ₹48,500 | ₹71,900 | ₹1,36,500 | ₹2,56,900 Total |
Syntax & Core Code Implementation
import numpy as np
# 4x3 Revenue matrix (Stores x Shifts)
rev = np.array([
[12500, 18200, 35000],
[15000, 22400, 42000],
[9800, 14500, 28000],
[11200, 16800, 31500]
])
# Global statistics (collapses entire matrix to scalar)
grand_total = np.sum(rev)
avg_revenue = np.mean(rev)
# Axis reductions:
# axis=0 -> Collapses rows down columns -> Returns 3 shift totals
shift_totals = np.sum(rev, axis=0) # [48500, 71900, 136500]
# axis=1 -> Collapses columns across rows -> Returns 4 store totals
store_totals = np.sum(rev, axis=1) # [65700, 79400, 52300, 59500]
# Peak performer location
best_store_idx = np.argmax(store_totals) # 1 (Indiranagar)
p90_revenue = np.percentile(rev, 90)
Parameters & Arguments Breakdown
axis=0: Collapses along the row index; computes metric for each COLUMN.axis=1: Collapses along the column index; computes metric for each ROW.np.nanmean() / np.nanstd(): NaN-safe versions that ignore missing null values during computation.np.argmax() / np.argmin(): Returns the index of the maximum or minimum value along specified axis.
Sample Walkthrough (Q&A)
Question: How do you calculate the median delivery time while ignoring any NaN records?
Code Pattern: np.nanmedian(delivery_times_array)
Result: Calculates true numeric median without returning NaN.
Explanation: Standard `np.median()` propagates any single NaN to the final result. `np.nanmedian()` filters out NaNs before sorting and finding the midpoint.
Common Mistakes & Limitations
- Inverting `axis=0` and `axis=1`; remember: axis parameter indicates the dimension that will be ELIMINATED / COLLAPSED.
- Using standard Python `sum()` on a 2D NumPy array, which is slow and only iterates the outer dimension.
Keyboard Shortcuts (Jupyter & VS Code)
| Action | Windows | Mac |
|---|---|---|
| Quick Summary String | f"{arr.mean():.2f} ± {arr.std():.2f}" | f"{arr.mean():.2f} ± {arr.std():.2f}" |
| Keep Dimensions in Reduction | np.sum(arr, axis=1, keepdims=True) | np.sum(arr, axis=1, keepdims=True) |
Pro Tips & Modern Best Practices
- Use `keepdims=True` in aggregations to prevent 2D arrays from collapsing to 1D, facilitating subsequent broadcast operations.
- Use Scipy (`scipy.stats`) for advanced descriptive statistics like skewness, kurtosis, and mode.