Skip to main content
Albero Academy

Statistics & Histograms

Describe data numerically — percentiles and quantiles, variance and spread, correlation, and binning with histograms.

Chapter 11NumPy14 min readBeginner friendly
  • #NumPy
  • #Statistics
  • #Histograms

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

the summary numbers
data = rng.normal(60, 15, size=1000)
data.mean() # average
np.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:

percentiles
np.percentile(data, 50) # the median
np.percentile(data, [25, 75]) # the quartiles
iqr = np.percentile(data, 75) - np.percentile(data, 25) # interquartile range
np.quantile(data, 0.9) # the 90th percentile (fraction form)

Correlation & covariance

Measure how two variables move together — the basis of relationships in data:

do they move together?
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 +ve
np.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 per bin
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 index
np.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

  1. 01mean/median/std/var/ptp summarise centre and spread; median & IQR are robust to outliers.
  2. 02np.percentile / np.quantile describe a distribution far better than the mean alone.
  3. 03np.corrcoef measures how strongly two variables move together (−1 to +1); np.cov gives covariance.
  4. 04np.histogram counts values per bin to reveal a distribution's shape; np.digitize assigns bin indices.
  5. 05NumPy alone covers descriptive statistics — no extra library needed.