NumPy has enough statistics built in to describe a dataset without any extra library. This chapter covers the summary numbers you compute constantly — the middle, the spread, the percentiles — and histograms, the way you turn raw values into a distribution.
Central tendency & spread
data = rng.normal(60, 15, size=1000)data.mean() # averagenp.median(data) # middle value (robust to outliers)data.std() # standard deviation (spread)data.var() # variance (std squared)data.ptp() # peak-to-peak: max − min (range)
Percentiles & quantiles
A percentile is the value below which a given percent of the data falls. They describe a distribution far better than the mean alone:
np.percentile(data, 50) # the mediannp.percentile(data, [25, 75]) # the quartilesiqr = np.percentile(data, 75) - np.percentile(data, 25) # interquartile rangenp.quantile(data, 0.9) # the 90th percentile (fraction form)
Correlation & covariance
Measure how two variables move together — the basis of relationships in data:
hours = np.array([1, 2, 3, 4, 5])scores = np.array([52, 61, 68, 80, 88])np.corrcoef(hours, scores) # 2×2 matrix; off-diagonal ≈ 0.99 → strong +venp.cov(hours, scores) # covariance matrix
Histograms & binning
A histogram counts how many values fall in each bin — how you see the shape of a distribution:
counts, edges = np.histogram(data, bins=10)# counts[i] = number of values in [edges[i], edges[i+1])# digitize assigns each value to a bin indexnp.digitize([55, 72, 90], bins=[40, 60, 80]) # [1 2 3]
Practice
For a sample of exam scores, report the mean, median, std and IQR, and note which pair is more robust to a couple of outliers you add. Build a 10-bin histogram of the scores. Compute the correlation between study hours and scores and interpret the sign and strength.
Key takeaways
- 01mean/median/std/var/ptp summarise centre and spread; median & IQR are robust to outliers.
- 02np.percentile / np.quantile describe a distribution far better than the mean alone.
- 03np.corrcoef measures how strongly two variables move together (−1 to +1); np.cov gives covariance.
- 04np.histogram counts values per bin to reveal a distribution's shape; np.digitize assigns bin indices.
- 05NumPy alone covers descriptive statistics — no extra library needed.
