/Curriculum/AdvancedStatistics & Reductions

45. NumPy Statistics & CorrelationAdvanced

Calculate median, percentiles, quantiles, covariance, and correlation matrices (corrcoef).

16 mins

Concept Overview

NumPy provides rich statistical tools for data science: `np.median` for robust center metrics, `np.percentile` for distribution thresholds, and `np.corrcoef` for Pearson correlation matrices.

Hardware Mental Model

Mean is sensitive to Elon Musk entering the bar (average wealth skyrockets). Median is the middle person in line, staying stable regardless of extreme outliers.

Key Concepts (1)Click snippet to load in editor

`np.corrcoef(x, y)` returns a 2x2 normalized covariance matrix where values range from -1.0 (inverse correlation) to +1.0 (perfect positive correlation).

corr = np.corrcoef(x, y)[0, 1]

⚠ Common Mistakes & Pitfalls

Avoid these frequent beginner syntax and logic traps
❌ Incorrect:data.median() # AttributeError: 'numpy.ndarray' has no .median() method
✓ Correct:np.median(data)

Unlike `.mean()`, `median` is only available as a top-level function `np.median(arr)`.

Pro Tip: Call `np.median(arr)` and `np.percentile(arr, q)` as top-level functions.

📌 Quick Revision

Core takeaway points from this topic
`np.median(arr)`: Middle value (robust against outliers).
`np.percentile(arr, q)`: Computes q-th percentile threshold.
`np.corrcoef(x, y)`: Pearson correlation matrix.
`np.cov(x, y)`: Covariance matrix.
Editor: 45. NumPy Statistics & Correlation
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:Compute Median of Numbers

Create `arr = np.array([5, 1, 9, 3, 7])`, calculate its median with `np.median(arr)`, and print.

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