TExcelTAD
Home › Data Science › DS Distributions

DS Distributions

A distribution describes which values a variable takes and how often. Knowing the shape of a distribution tells you which summaries are meaningful, which models fit, and what counts as "unusual".

Histograms show the shape

A histogram groups values into bins and counts each bin. The number of bins changes the picture, so try a few:

python · try it yourself
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

fig, axes = plt.subplots(1, 3, figsize=(12, 3.5))
for ax, bins in zip(axes, [5, 12, 30]):
    ax.hist(bikes["rides"], bins=bins, color="#ff6f00", edgecolor="white")
    ax.set_title(f"{bins} bins")
    ax.set_xlabel("rides")
plt.tight_layout()
plt.show()

counts, edges = np.histogram(bikes["rides"], bins=5)
for c, lo, hi in zip(counts, edges[:-1], edges[1:]):
    print(f"{lo:6.1f} - {hi:6.1f}: {'#' * c} {c}")
 124.0 -  213.6: ###### 6
 213.6 -  303.2: ################# 17
 303.2 -  392.8: ############# 13
 392.8 -  482.4: ################# 17
 482.4 -  572.0: ####### 7

Too few bins hide detail; too many turn the histogram into noise. With 60 values, 8–15 bins is a reasonable range.

Common shapes

Shape Looks like Example Typical summary
Normal (bell) symmetric, one peak, thin tails measurement errors, regression residuals mean ± SD
Uniform flat — every value equally likely our simulated temperatures (4–30 °C) min, max
Right-skewed long tail to the right rainfall, trip lengths, incomes median, IQR
Bimodal two peaks trip lengths of commuters vs tourists describe each group

The normal distribution

The normal distribution is defined by two numbers: its mean μ and standard deviation σ. It is the reference shape for many statistical methods. SciPy's stats.norm computes probabilities for it:

python · try it yourself
from scipy import stats

mu, sigma = 355, 109          # roughly our rides' mean and SD
dist = stats.norm(mu, sigma)

print("P(rides < 246):          ", round(dist.cdf(246), 3))
print("P(246 < rides < 464):    ", round(dist.cdf(464) - dist.cdf(246), 3))
print("P(rides > 573):          ", round(dist.sf(573), 3))
print("90th percentile:         ", round(dist.ppf(0.90), 1))
P(rides < 246):           0.159
P(246 < rides < 464):     0.683
P(rides > 573):           0.023
90th percentile:          494.7
Method Returns
cdf(x) probability of a value ≤ x
sf(x) probability of a value > x (1 − cdf)
ppf(q) the value with probability q below it (inverse of cdf)
pdf(x) height of the bell curve at x

The middle line reproduces the "68 %" of the 68–95 rule from the Standard Deviation lesson.

Does our data follow the rule?

Let's check the rule against the actual rides, and do the same for rain, which is clearly not bell-shaped:

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

for col in ["rides", "rain_mm"]:
    x = bikes[col]
    m, s = x.mean(), x.std()
    within1 = ((x - m).abs() <= s).mean()
    within2 = ((x - m).abs() <= 2 * s).mean()
    print(f"{col:8} within 1 SD: {within1:.0%}   within 2 SD: {within2:.0%}")
rides    within 1 SD: 70%   within 2 SD: 98%
rain_mm  within 1 SD: 83%   within 2 SD: 92%

Rides fit the rule loosely (60 values is a small sample). Rain does not: most values pile up at 0, so "within one SD" covers far more than 68 %. The 68–95 rule is only a guide for roughly bell-shaped data.

Simulating distributions

NumPy's generator draws from many distributions. Simulating is a great way to build intuition for what "random" looks like:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(10)
samples = {
    "normal(0, 1)": rng.normal(0, 1, 2000),
    "uniform(0, 1)": rng.uniform(0, 1, 2000),
    "exponential(5)": rng.exponential(5, 2000),     # e.g. minutes between rentals
    "poisson(3)": rng.poisson(3, 2000),             # e.g. rentals per 10 minutes
}

fig, axes = plt.subplots(1, 4, figsize=(13, 3))
for ax, (name, x) in zip(axes, samples.items()):
    ax.hist(x, bins=30, color="#ff6f00")
    ax.set_title(name)
plt.tight_layout()
plt.show()
for name, x in samples.items():
    print(f"{name:15} mean={x.mean():6.2f}  median={np.median(x):6.2f}")
normal(0, 1)    mean= -0.04  median= -0.05
uniform(0, 1)   mean=  0.50  median=  0.49
exponential(5)  mean=  5.11  median=  3.59
poisson(3)      mean=  2.98  median=  3.00

For the skewed exponential distribution the mean is clearly above the median — the long right tail pulls it up, just as with rainfall.

Tip: A Q-Q plot (scipy.stats.probplot) is a sharper test of normality than a histogram: if the points lie on a straight line, the data is close to normal. You'll use it for residuals in the Residual Analysis lesson.

Test yourself

Which distribution shape best describes daily rainfall (many dry days, few very wet ones)?

  1. Normal
  2. Uniform
  3. Right-skewed
  4. Bimodal

With dist = stats.norm(100, 15), what does dist.cdf(130) return?

  1. The height of the curve at 130
  2. The probability of a value ≤ 130 (about 0.977)
  3. The 130th percentile
  4. The probability of exactly 130

In a right-skewed distribution, how do mean and median usually compare?

  1. Mean < median
  2. Mean = median
  3. Mean > median
  4. They can't be compared