8.2. Descriptive Distributions#

Hide code cell source

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

sns.set_theme()

This section uses numeric summaries, visualizations, and common distribution families to describe observed data and simulated outcomes. It continues with the tips data from the previous section.

tips = sns.load_dataset('tips')

df.describe() gives the descriptive statistics of every numeric column at once: the count, mean, standard deviation, minimum, quartiles, and maximum.

tips.describe()
total_bill tip size
count 244.000000 244.000000 244.000000
mean 19.785943 2.998279 2.569672
std 8.902412 1.383638 0.951100
min 3.070000 1.000000 1.000000
25% 13.347500 2.000000 2.000000
50% 17.795000 2.900000 2.000000
75% 24.127500 3.562500 3.000000
max 50.810000 10.000000 6.000000

The four summaries used most for a numeric variable are the mean and median, which describe the center, and the standard deviation and IQR, which describe the spread. The next two sections compute each for total_bill and explain what it tells you.

8.2.1. Center: Mean vs Median#

col = tips['total_bill']

summary = pd.DataFrame({
    'mean': [col.mean()],
    'median': [col.median()],
    'std (SD)': [col.std()],
    'IQR': [col.quantile(0.75) - col.quantile(0.25)]
})
summary
mean median std (SD) IQR
0 19.785943 17.795 8.902412 10.78

The mean bill ($19.79) is about $2 higher than the median bill ($17.80). The median is the middle value, so it depends only on the order of the bills. The mean adds up every dollar, so a handful of large bills between $40 and $50 pull it upward. When the mean sits above the median like this, the distribution is skewed to the right: most values are bunched at the low end and a long tail stretches toward large values. You can see that tail in the histogram in Visualizing One Variable below. pandas measures the skew directly with .skew(); a positive value means a right tail.

col.skew()
np.float64(1.1332130376158203)

For skewed data, the median usually describes a “typical” value better than the mean. This book’s exercises use a simple rule of thumb: if the mean is more than 20% above the median, treat the data as right-skewed and report the median as the typical value. This is a convenient cutoff for practice, not a formal statistical test. For the tips data the mean is about 11% above the median, so the skew is moderate and the mean and median tell a similar story.

8.2.2. Spread: SD, Percentiles, IQR#

Center tells you where a typical value is; spread tells you how far values typically fall from it.

8.2.2.1. Standard Deviation and Variance#

The standard deviation (SD) measures the typical distance of the values from the mean. The variance is the SD squared. Variance is in squared units (here, dollars squared), which are hard to interpret, so the SD is usually reported.

print('Variance:', round(col.var(), 2))
print('SD (pandas .std):', round(col.std(), 2))
print('SD (np.std):', round(np.std(col), 2))
Variance: 79.25
SD (pandas .std): 8.9
SD (np.std): 8.88

pandas .std() divides by \(n-1\) (the sample SD, ddof=1), while np.std() divides by \(n\) (the population SD, ddof=0) by default. With 244 bills the two barely differ ($8.90 vs $8.88), but with a small dataset the gap is noticeable, so use the function an exercise asks for.

8.2.2.2. Percentiles and the IQR#

The \(p\)-th percentile is the value below which \(p\%\) of the observations fall. The median is the 50th percentile. The 25th and 75th percentiles are the first and third quartiles (Q1 and Q3), and the interquartile range (IQR = Q3 − Q1) is the width of the middle 50% of the data.

NumPy computes percentiles with np.percentile(data, p), where data is an array or a pandas column and p is a percentile between 0 and 100. For example, np.percentile(col, 90) returns the 90th percentile of col. Passing a list, as in np.percentile(col, [25, 75]), returns one value per percentile, so Q1 and Q3 can be unpacked in a single line. Note that p is on a 0 to 100 scale, not 0 to 1.

q25, q50, q75, q90 = np.percentile(col, [25, 50, 75, 90])
print('25th percentile (Q1):', q25)
print('50th percentile (median):', q50)
print('75th percentile (Q3):', q75)
print('90th percentile:', q90)
print('IQR:', round(q75 - q25, 2))
25th percentile (Q1): 13.3475
50th percentile (median): 17.795
75th percentile (Q3): 24.127499999999998
90th percentile: 32.23500000000001
IQR: 10.78

Half of the bills fall between about $13.35 and $24.13, an IQR of $10.78. The 90th percentile is $32.24: 90% of bills are at or below that amount. Like the median, percentiles and the IQR depend only on the order of the values, so a few extreme bills do not move them much. That makes them a good choice for skewed data, while the SD is sensitive to extreme values just like the mean.

8.2.2.3. Outliers: The 1.5 × IQR Rule#

A common way to flag outliers is to call any value more than 1.5 IQRs above Q3 (or below Q1) unusual:

iqr = q75 - q25
upper_fence = q75 + 1.5 * iqr
lower_fence = q25 - 1.5 * iqr
print('Upper fence:', round(upper_fence, 2))
print('Lower fence:', round(lower_fence, 2))
print('Bills above the upper fence:', (col > upper_fence).sum())
Upper fence: 40.3
Lower fence: -2.82
Bills above the upper fence: 9

Nine bills are above $40.30, and none are below the lower fence. A boxplot uses exactly this rule: those nine bills are the individual points drawn above the top whisker in the boxplot below.

8.2.3. Visualizing One Variable#

Three plots describe one numeric variable: a histogram shows counts (or densities) in bins, a boxplot shows the median, quartiles, and outliers, and a KDE (kernel density estimate) draws a smoothed version of the histogram’s shape. Whatever the plot, read it with the same checklist: center, spread, shape, outliers.

fig, axes = plt.subplots(1, 2, figsize=(10,4))

sns.histplot(tips, x='total_bill', kde=True, ax=axes[0])
axes[0].set_title('Histogram + KDE')

sns.boxplot(y=tips['total_bill'], ax=axes[1])
axes[1].set_title('Boxplot')

plt.tight_layout()
../../_images/ab067811abb1c2996ad1bd40303f4d18dba3466a2a4995eb9fac0a480da612f8.png

The histogram shows the shape: a peak between about $10 and $20 and a long tail to the right. The boxplot shows the same thing in summary form. The median line sits closer to the bottom of the box, the upper whisker is longer than the lower one, and the outliers are all on the high side. Together with the numbers above, this covers center (median about $18), spread (IQR about $11), and shape (right-skewed, with a few large bills).

8.2.4. Normal Distribution#

A normal distribution, also called a Gaussian distribution, is a symmetric, bell-shaped distribution centered on its mean. Most values cluster near the mean, and the frequencies taper off equally on both sides. Two numbers define it: the mean \(\mu\), which sets the center, and the standard deviation \(\sigma\), which sets the spread. Its mean, median, and mode are all at the center.

Many measured quantities are close to normal: delivery times on a fixed route, the weights of packaged goods coming off one line, daily sales of a steady product. The reason is the Central Limit Theorem, which comes later in this section: a quantity that adds up many small independent effects tends to be normal.

The most useful fact about a normal distribution is the 68-95-99.7 rule: about 68% of values fall within 1 SD of the mean, 95% within 2 SDs, and 99.7% within 3 SDs. If a route’s delivery time averages 30 minutes with an SD of 4, then 95% of deliveries take between 22 and 38 minutes.

np.random.normal(loc=0.0, scale=1.0, size=None) draws from a normal distribution; loc is the mean and scale is the SD.

8.2.4.1. Checking the 68–95–99.7 Rule#

The empirical rule is easy to check by simulation. The code below draws 1,000 values from a normal distribution with mean 50 and SD 5 and counts how many fall within 1, 2, and 3 SDs of the mean (45–55, 40–60, and 35–65).

np.random.seed(42)
values = np.random.normal(loc=50, scale=5, size=1000)

for k in [1, 2, 3]:
    within = ((values > 50 - k * 5) & (values < 50 + k * 5)).mean()
    print(f'Within {k} SD: {within:.1%}')
Within 1 SD: 69.8%
Within 2 SD: 95.9%
Within 3 SD: 99.7%

The simulated shares (69.8%, 95.9%, and 99.7%) are close to the 68%, 95%, and 99.7% the rule predicts. Simulation lets you check a rule instead of memorizing it. Sampling Variability uses the 95% figure again for the margin of error.

Time for some visualization. Here you plot 1,000 draws from a standard normal distribution (mean 0, SD 1). displot() is a figure-level function, so you control the figure size with height and aspect (the width-to-height ratio).

np.random.seed(42)
sns.displot(np.random.normal(size=1000), height=3, aspect=2, kde=True);
../../_images/f76ec3d529b46021cd76c3ee261efcefbc13ff5b6e486563a7dcd3434dd52efa.png
### Exercise: Delivery Times
# Deliveries on a route take 30 minutes on average with a standard deviation of 4.
#   1. Seed NumPy with 42 and draw 10,000 delivery times from the matching normal distribution.
#   2. Find the share of deliveries that take between 22 and 38 minutes (within 2 SDs).
#   3. Find the share that take more than 40 minutes.
#   4. Print both shares as percentages with 1 decimal.
# Print exactly:
# Within 22 to 38 minutes: 95.3%
# Over 40 minutes: 0.7%
### Your code starts here




### Your code ends here

Hide code cell source

### Solution
np.random.seed(42)
times = np.random.normal(loc=30, scale=4, size=10000)

ex_within = ((times > 22) & (times < 38)).mean()
over = (times > 40).mean()
print(f'Within 22 to 38 minutes: {ex_within:.1%}')
print(f'Over 40 minutes: {over:.1%}')
# About 95% fall within 2 SDs, as the rule predicts; 40 minutes is 2.5 SDs above the mean.
Within 22 to 38 minutes: 95.3%
Over 40 minutes: 0.7%

8.2.5. Binomial Distribution#

A binomial distribution is a discrete probability distribution that models the number of successes in a fixed number of independent trials, where each trial has only two outcomes: “success” or “failure.” Every trial must have the same probability of success. This distribution is fundamental for analyzing repeated yes/no-type experiments (Bernoulli trials) and appears frequently in statistics and data science.

Key Features:

  • There are n fixed trials.

  • Each trial is independent.

  • There are only two possible outcomes per trial (success or failure).

  • The chance of success p is constant for each trial.

For example, flipping a fair coin 10 times and counting the number of heads. Here, each flip is independent, and the probability of heads (success) is 0.5. The distribution of the number of heads follows a binomial distribution with n=10, p=0.5.

Start with the coin itself. np.random.choice(coin, size=10) picks one side of coin at random, 10 times; size= is the number of picks, so this is 10 flips. Each flip is one trial with two outcomes, and the number of heads is the number of successes.

### 10 flips of a fair coin
np.random.seed(42)
coin = ['Tails', 'Heads']
flips = np.random.choice(coin, size=10)          ### size= is the number of flips
print(flips)

### count the heads: the number of successes in 10 trials
num_heads = np.count_nonzero(flips == 'Heads')
print("Number of heads:", num_heads)

plt.figure(figsize=(4, 3))
sns.countplot(x=flips, order=['Heads', 'Tails'], color='green');
['Tails' 'Heads' 'Tails' 'Tails' 'Tails' 'Heads' 'Tails' 'Tails' 'Tails'
 'Heads']
Number of heads: 3
../../_images/67b149f67f520922527ba8f2e7c0495b556f56f6a8d1eba18f2d70dc0f98ff80.png

Words are easy to read, but numbers are easier to count with. Coding tails as 0 and heads as 1 turns the count of heads into a sum. With the same seed, the cell below makes the same ten flips as above, written as numbers.

### the same 10 flips, with tails as 0 and heads as 1
np.random.seed(42)
arr = np.random.choice([0, 1], size=10)
print(arr)

### count the 1s: the number of heads
print(np.sum(arr))
[0 1 0 0 0 1 0 0 0 1]
3

np.random.choice([0, 1], size=10) makes ten independent trials with \(p = 0.5\), where 1 means heads (a success), and np.sum(arr) adds up the 1s, which counts the heads. One run of ten flips therefore produces one number between 0 and 10, and that number is one draw from the binomial distribution with \(n = 10\) and \(p = 0.5\).

A single draw does not show the distribution itself. To see it, repeat the 10-flip experiment many times and record how many heads each experiment produced.

### repeat the 10-flip experiment 100 times and keep the number of heads from each
np.random.seed(42)
arr = np.array([])                  ### initiator of the accumulator pattern
for i in range(100):                ### 100 experiments of 10 flips each
    arr = np.append(arr, np.sum(np.random.choice([0, 1], size=10)))
print(arr)

### histogram of the number of heads per experiment
fig, ax = plt.subplots(1, 2, figsize=(8, 3))
ax[0].hist(arr, alpha=0.6, color='g', bins=np.arange(-0.5, 11.5, 1), density=True)   ### proportions; bar heights sum to 1
sns.histplot(arr, bins=np.arange(-0.5, 11.5, 1), ax=ax[1])                          ### counts

ax[0].set_title('Matplotlib')
ax[1].set_title('Seaborn');
[3. 4. 9. 4. 7. 4. 4. 7. 5. 9. 8. 6. 6. 1. 5. 3. 5. 4. 3. 3. 5. 2. 5. 9.
 3. 4. 4. 7. 5. 5. 6. 4. 7. 5. 4. 5. 4. 7. 4. 6. 8. 5. 6. 6. 5. 6. 5. 5.
 5. 4. 4. 7. 6. 4. 5. 7. 5. 6. 6. 6. 6. 5. 5. 5. 5. 4. 4. 8. 5. 7. 7. 7.
 3. 4. 4. 6. 5. 4. 5. 3. 5. 3. 6. 3. 4. 2. 6. 5. 5. 4. 5. 7. 2. 5. 4. 4.
 3. 7. 9. 7.]
../../_images/ba1d033c42cf99ffa54192f2c6524c928c286fb2d2d42be930884eec78637939.png

arr now holds 100 numbers, one head count per experiment. Each bar shows how often a count came up: the left plot as a proportion of the 100 experiments, the right plot as a raw count. Counts near 5, which is \(n \times p\), come up most often, the bars fall off evenly on both sides, and 0 or 10 heads almost never happen. That shape is the binomial distribution with \(n = 10\) and \(p = 0.5\).

The exact probability of \(k\) heads is \(P(X = k) = \binom{10}{k} 0.5^{10}\). For example, 5 heads can happen in \(\binom{10}{5} = 252\) of the \(2^{10} = 1024\) equally likely flip sequences, so \(P(X = 5) = 252/1024 \approx 0.25\). With only 100 experiments the bars are bumpy; more repetitions bring them closer to the exact probabilities.

Note

To center each bin on a whole number (−0.5 to 0.5 for 0, 0.5 to 1.5 for 1, and so on) and make both plots look consistent, start the bins half a unit below the smallest possible value:

bins=np.arange(-0.5, max(arr) + 1.5, 1)

Starting the bins at 0.5 instead leaves out the bar for 0 heads.

NumPy can also draw binomial counts directly. np.random.binomial(n=10, p=0.5, size=100) returns 100 numbers, each the number of successes in 10 trials, which is what the loop above built one experiment at a time. Below, the red points mark the exact probabilities \(P(X = k)\) over the simulated proportions.

### 100 binomial counts at once: each is the number of heads in n=10 flips with p=0.5
np.random.seed(42)
counts = np.random.binomial(n=10, p=0.5, size=100)
print(counts)

### exact probabilities P(X = k) for k = 0..10, over the simulated proportions
from math import comb
k = np.arange(0, 11)
exact = [comb(10, j) * 0.5**10 for j in k]

fig, ax = plt.subplots(figsize=(4, 3))
ax.hist(counts, bins=np.arange(-0.5, 11.5, 1), density=True, alpha=0.6, color='g')
ax.plot(k, exact, 'o-', color='red')
ax.set_title('Simulated vs. exact');
[4 8 6 5 3 3 3 7 5 6 2 8 7 4 4 4 4 5 5 4 5 3 4 4 5 6 4 5 5 2 5 3 3 8 8 6 4
 3 6 5 3 5 2 7 4 6 4 5 5 4 8 6 7 7 5 7 3 4 2 4 5 4 7 4 4 5 3 6 3 8 6 4 1 6
 6 6 6 3 4 3 7 6 4 3 4 4 6 6 7 5 3 6 6 5 6 5 5 5 2 3]
../../_images/f48437d6d56c828e8eede2f7e0343792b26e447e498123914e998c5f788bf57d.png
### Exercise: Store Visits
# Each of 20 visitors to a store buys something with probability 0.3, independently.
#   1. Seed NumPy with 42 and simulate 5,000 days of 20 visitors with np.random.binomial.
#   2. Print the mean number of buyers per day, rounded to 2 decimals.
#   3. Print the share of days with 10 or more buyers, rounded to 3 decimals.
# Print exactly:
# Mean buyers per day: 5.98
# Share of days with 10+ buyers: 0.048
### Your code starts here




### Your code ends here

Hide code cell source

### Solution
np.random.seed(42)
buyers = np.random.binomial(n=20, p=0.3, size=5000)

print('Mean buyers per day:', round(buyers.mean(), 2))
print('Share of days with 10+ buyers:', round(np.mean(buyers >= 10), 3))
# The mean is close to n * p = 6; ten or more buyers happens on about 5% of days.
Mean buyers per day: 5.98
Share of days with 10+ buyers: 0.048

8.2.6. Multinomial Distribution#

A binomial count splits each trial into two outcomes. Many business questions have more than two. A coffee customer orders a small, medium, or large drink; a support ticket is about billing, a technical problem, or an account; a survey respondent falls into one of five age groups. A multinomial distribution models the counts for each category in a fixed number of independent trials, where each trial lands in exactly one of \(k\) categories.

Key Features:

  • There are n fixed trials.

  • Each trial is independent.

  • Each trial lands in one of \(k\) categories.

  • The chance of each category, \(p_1, p_2, \ldots, p_k\), is constant for each trial, and the chances add to 1.

The result of one multinomial draw is not one number but a list of \(k\) counts, one per category, and the counts always add to n. The binomial is the special case with \(k = 2\): the count of failures is just n minus the count of successes, so one number tells the whole story.

For example, suppose a coffee shop sells 30% small, 50% medium, and 20% large drinks (shares made up for this example). The sizes ordered by the next 20 customers follow a multinomial distribution with n=20 and probabilities 0.3, 0.5, and 0.2.

Start with the customers themselves. In Probability Models you used p= with choice to give each outcome its own chance; np.random.choice(sizes, size=20, p=probs) does the same here, picking one size for each of 20 customers. Counting each size turns the 20 orders into three counts.

### 20 customers, each ordering a small, medium, or large drink
np.random.seed(42)
sizes = ['Small', 'Medium', 'Large']
probs = [0.3, 0.5, 0.2]
orders = np.random.choice(sizes, size=20, p=probs)     ### p= gives each size its chance
print(orders)

### count each size: one count per category
counts = np.array([np.count_nonzero(orders == s) for s in sizes])
print("Counts (small, medium, large):", counts)
print("Total:", counts.sum())
['Medium' 'Large' 'Medium' 'Medium' 'Small' 'Small' 'Small' 'Large'
 'Medium' 'Medium' 'Small' 'Large' 'Large' 'Small' 'Small' 'Small'
 'Medium' 'Medium' 'Medium' 'Small']
Counts (small, medium, large): [8 8 4]
Total: 20

The three counts, 8 small, 8 medium, and 4 large, add to the 20 customers. Together they are one draw from the multinomial distribution with \(n = 20\) and probabilities \((0.3, 0.5, 0.2)\). Expected counts are \(n \times p\) for each category: 6 small, 10 medium, and 4 large. One group of 20 customers rarely matches those exactly.

NumPy draws multinomial counts directly, without making the individual orders first. The pattern is:

np.random.multinomial(n, pvals, size=None)

  • n: the number of trials in one draw, here 20 customers

  • pvals: the chance of each category, in a fixed order, here probs

  • size: how many draws to make; leave it out for one draw

Without size, the call returns one array of \(k\) counts that adds to n, in the same order as pvals. With size=1000, it returns a table with 1,000 rows, one draw per row, and one column per category.

### one draw: counts of small, medium, and large among 20 customers
np.random.seed(42)
print(np.random.multinomial(20, probs))

### 1,000 draws at once: one row per group of 20 customers
np.random.seed(42)
many = np.random.multinomial(20, probs, size=1000)
print(many[:5])                         ### the first 5 draws
print("Shape:", many.shape)
print("Row totals:", many[:5].sum(axis=1))
print("Mean count per size:", many.mean(axis=0))
[5 8 7]
[[ 5  8  7]
 [ 7  9  4]
 [ 4 13  3]
 [ 3 10  7]
 [ 6  9  5]]
Shape: (1000, 3)
Row totals: [20 20 20 20 20]
Mean count per size: [ 5.942 10.004  4.054]

A multinomial draw has one count per category, so a picture needs all three sizes at once. In the left plot, each bar is one draw, split into small, medium, and large; the bars change color mix from draw to draw but always reach 20. The right plot shows, for each size, how often each count came up across the 1,000 draws, with a dashed line at the expected count \(n \times p\).

### all three sizes: the first 10 draws, and each size's counts across 1,000 draws
colors = ['tab:blue', 'tab:green', 'tab:orange']
fig, ax = plt.subplots(1, 2, figsize=(9, 3.2))

### left: each bar is one group of 20 customers, split by size
bottom = np.zeros(10)
for j, s in enumerate(sizes):
    ax[0].bar(np.arange(1, 11), many[:10, j], bottom=bottom, color=colors[j], label=s)
    bottom = bottom + many[:10, j]
ax[0].set_xticks(np.arange(1, 11))
ax[0].set_xlabel('Draw (group of 20 customers)')
ax[0].set_ylabel('Orders')
ax[0].set_title('Every draw adds to 20')
ax[0].set_ylim(0, 24)                             ### headroom for the legend
ax[0].legend(fontsize=8, loc='upper center', ncol=3)

### right: how often each count came up, one histogram per size
for j, s in enumerate(sizes):
    ax[1].hist(many[:, j], bins=np.arange(-0.5, 21.5, 1), density=True, alpha=0.5, color=colors[j], label=s)
    ax[1].axvline(20 * probs[j], color=colors[j], linestyle='--')   ### expected count n * p
ax[1].set_xlabel('Count among 20 customers')
ax[1].set_title('Counts center on n × p')
ax[1].legend(fontsize=8)
plt.tight_layout();
../../_images/79e91455ad0a7dfbdcc4ce8b49455f9db5a552759d70e28cfdd955befea828af.png

The column means, about 5.9, 10.0, and 4.1, sit close to the expected counts 6, 10, and 4, which is why each histogram centers on its dashed line. Large drinks, the rarest size, have the narrowest spread, and medium drinks the widest. The counts also move together: in the left plot, a draw with more medium orders has fewer orders left for the other sizes.

Now look at one column alone. Each customer either orders a medium or does not, with chance 0.5, so the number of medium drinks in a row is a binomial count with \(n = 20\) and \(p = 0.5\). Every column of a multinomial table is binomial in this way. The red points below are the exact binomial probabilities, computed as in the binomial section.

### the medium column alone: binomial with n=20, p=0.5
from math import comb
medium = many[:, 1]
k = np.arange(0, 21)
exact = [comb(20, j) * 0.5**20 for j in k]

fig, ax = plt.subplots(figsize=(4, 3))
ax.hist(medium, bins=np.arange(-0.5, 21.5, 1), density=True, alpha=0.6, color='g')
ax.plot(k, exact, 'o-', color='red')
ax.set_xlabel('Medium drinks among 20 customers')
ax.set_title('One category is binomial');
../../_images/8df29406dd32fdeb65f758a5b43c579306743755f1dea80fd5a8675b9e7060ff.png

The simulated proportions follow the exact binomial probabilities, peaking at 10 medium drinks. Use the binomial when you care about one category against everything else, and the multinomial when you need all the category counts at once. In Comparing Distributions you will use multinomial to ask whether a survey’s age mix could have come from a random sample of a company’s customers.

### Exercise: Support Tickets
# A help desk receives 50 tickets a day. Each ticket is about billing (0.40),
# a technical problem (0.35), or an account (0.25), independently.
#   1. Seed NumPy with 42 and simulate 2,000 days with np.random.multinomial.
#   2. Print the mean number of tickets per category, rounded to 2 decimals.
#   3. Print the share of days with more technical tickets than billing tickets, rounded to 3 decimals.
# Print exactly:
# Mean tickets per category: [19.93 17.54 12.53]
# Share of days with more technical than billing: 0.325
### Your code starts here




### Your code ends here

Hide code cell source

### Solution
np.random.seed(42)
tickets = np.random.multinomial(50, [0.40, 0.35, 0.25], size=2000)

print('Mean tickets per category:', tickets.mean(axis=0).round(2))
print('Share of days with more technical than billing:', round(np.mean(tickets[:, 1] > tickets[:, 0]), 3))
# The means are close to 50 * p = 20, 17.5, and 12.5. Billing is the most likely
# category, yet on about a third of days technical tickets outnumber it by chance.
Mean tickets per category: [19.93 17.54 12.53]
Share of days with more technical than billing: 0.325

8.2.7. Uniform Distribution#

A uniform distribution spreads probability evenly: every outcome in its range is equally likely, so no result is favored over another. It comes in two kinds:

  • A discrete uniform distribution has a fixed list of separate outcomes, each with the same probability. A fair six-sided die is one: each face, 1 through 6, has probability 1/6.

  • A continuous uniform distribution covers every number in an interval, such as any decimal from 0 to 5. A single exact value has probability 0, so here “equally likely” means that intervals of the same length are equally likely: a draw is as likely to land between 1 and 2 as between 3 and 4.

A single coin flip is also a discrete uniform: Heads and Tails each have probability 0.5. The number of heads in 10 flips, however, is not uniform. As the binomial section showed, 5 heads is far more likely than 0 or 10.

8.2.7.1. Discrete Uniform: Rolling a Die#

np.random.randint() draws whole numbers that are equally likely:

np.random.randint(low, high, size=None)

It returns integers from low up to, but not including, high, so np.random.randint(1, 7) rolls a die (1 to 6).

Below, a fair die is rolled 6, 60, 600, 6,000, and 60,000 times. With only a few rolls, some faces come up more often than others by chance. As the number of rolls grows, all six faces appear about equally often, which is what a uniform distribution predicts. discrete=True gives each face its own bar, centered on its number.

### roll a die more and more times
np.random.seed(42)
fig, axes = plt.subplots(1, 5, figsize=(12, 3))

for i, n_rolls in enumerate([6, 60, 600, 6000, 60000]):
    rolls = np.random.randint(1, 7, size=n_rolls)     ### integers 1 to 6
    sns.histplot(rolls, discrete=True, ax=axes[i])     ### one bar per face
    axes[i].set_xticks(range(1, 7))
    axes[i].set_title(f'{n_rolls:,} rolls')

plt.tight_layout()
../../_images/6a2c6252df119c55f5cfc420b727b8085e2c76d5da138cc0c0307ab5860dbedc.png

How the bars are drawn matters. Without discrete=True, Seaborn chooses bin edges from the range of the data, and those edges do not line up with the six faces. Below, the same 60,000 rolls are drawn both ways. With automatic bins, the axis is split into many narrow bins, most of which hold no face at all, so the chart shows six thin spikes separated by gaps instead of six bars.

### the same rolls, with automatic bins and with one bin per face
np.random.seed(42)
rolls = np.random.randint(1, 7, size=60000)

fig, axes = plt.subplots(1, 2, figsize=(8, 3))
sns.histplot(rolls, ax=axes[0])
sns.histplot(rolls, discrete=True, ax=axes[1])
axes[1].set_xticks(range(1, 7))
axes[0].set_title('Automatic bins')
axes[1].set_title('discrete=True')
plt.tight_layout()
../../_images/15c3f33ffdb17773dfe9c1ea63cc0fd5442e88f60a5a1e8af99fad49268c0312.png

Now roll the die 10,000 times. With six equally likely faces, you expect each face to come up about 10,000 / 6 ≈ 1,667 times. np.unique(..., return_counts=True) counts how often each face actually came up.

### roll a die 10,000 times and count each face
np.random.seed(42)
rolls2 = np.random.randint(1, 7, size=10000)

print('Expected rolls per face:', round(len(rolls2) / 6, 1))
faces, counts = np.unique(rolls2, return_counts=True)
for face, count in zip(faces, counts):
    print(f'Face {face}: {count}')

plt.figure(figsize=(4, 3))
sns.histplot(rolls2, discrete=True);
Expected rolls per face: 1666.7
Face 1: 1665
Face 2: 1692
Face 3: 1625
Face 4: 1672
Face 5: 1689
Face 6: 1657
../../_images/8df45b29045ea5203b4ec6f71abf56242dff531649d8f007ef587c45931f4123.png

Each count lands within a few dozen of 1,667. The differences are chance, and they shrink relative to the total as the number of rolls grows. This settling has a name, the law of large numbers, which closes this section.

8.2.7.2. Continuous Uniform#

np.random.uniform() draws decimal numbers from a continuous uniform distribution:

np.random.uniform(low=0.0, high=1.0, size=None)

The draws fall in the half-open interval [low, high): low can come up, but high cannot. size= sets how many numbers to draw, or the shape of an array of them.

np.random.seed(42)

unif1 = np.random.uniform()                               ### 1 number in [0, 1)
unif2 = np.random.uniform(low=1, high=5, size=3)          ### 3 numbers in [1, 5)
unif3 = np.random.uniform(low=5, high=10, size=(3, 3))    ### a 3x3 array in [5, 10)
unif4 = np.round(np.random.uniform(low=5, high=10, size=(3, 3)), 2)     ### rounded to 2 decimals

for unif in [unif1, unif2, unif3, unif4]:
    print(unif, '\n')
0.3745401188473625 

[4.80285723 3.92797577 3.39463394] 

[[5.7800932  5.7799726  5.29041806]
 [9.33088073 8.00557506 8.54036289]
 [5.10292247 9.84954926 9.1622132 ]] 

[[6.06 5.91 5.92]
 [6.52 7.62 7.16]
 [6.46 8.06 5.7 ]] 

With many draws, the histogram of a continuous uniform sample is flat. Below, 1,000,000 draws between 0 and 5 look flat with either 6 bins or 100 bins.

np.random.seed(42)
unif = np.random.uniform(0, 5, size=1000000)

fig, ax = plt.subplots(1, 2, figsize=(8, 3))
sns.histplot(unif, bins=6, ax=ax[0])
sns.histplot(unif, bins=100, ax=ax[1])
ax[0].set_title('6 bins')
ax[1].set_title('100 bins')
plt.tight_layout()
../../_images/b20aa3fe876632c5c5dde257e345b0cb6c94f0beb0bf4fa7f144c089b29a416c.png

With a small sample, too many bins break the histogram into random spikes. Below are 1,000 draws in 100 bins. Each bin expects only about 10 draws, so chance alone makes some bars two or three times as tall as others, even though the distribution is flat.

np.random.seed(42)
unif = np.random.uniform(0, 5, size=1000)

plt.figure(figsize=(6, 3))
sns.histplot(unif, bins=100);
../../_images/7bf1f6b70b1974ad68b1c7186de7f4e073008df35105c4a1526540f0c4b8e755.png

Instead of choosing the number of bins by hand, you can use the Freedman–Diaconis rule, which sets the bin width from the data:

\[\text{bin width} = 2 \times \text{IQR} \times n^{-1/3}\]

Data with a wider spread (larger IQR) get wider bins, and larger samples get narrower bins. So as \(n\) grows, the histogram gets more bins and shows more detail, while small samples get fewer bins and do not break into random spikes. Below, samples of 100, 1,000, 10,000, and 100,000 draws are binned this way. Seaborn applies the same rule when you pass bins='fd'.

### samples of 100 to 100,000 draws, binned with the Freedman-Diaconis rule
np.random.seed(42)
samples = [np.random.uniform(0, 5, size=n) for n in [100, 1000, 10000, 100000]]

fig, axes = plt.subplots(1, 4, figsize=(12, 3))
for i, data in enumerate(samples):
    q25, q75 = np.percentile(data, [25, 75])            ### IQR: the 75th minus the 25th percentile
    bin_width = 2 * (q75 - q25) * len(data) ** (-1/3)   ### Freedman-Diaconis bin width
    bins = int((data.max() - data.min()) / bin_width)   ### number of bins of that width
    sns.histplot(data, bins=bins, ax=axes[i])           ### same as bins='fd'
    axes[i].set_title(f'n = {len(data):,}, {bins} bins')

plt.tight_layout()
../../_images/8d12d0c3a17afad34a93e04c8da917c1000fd17c541068d38945bd311a41c0e3.png

A KDE (kernel density estimate) draws a smooth curve instead of bars. It smooths by spreading each draw a little to both sides, so by default the curve runs past 0 and 5 and slopes down at the edges, although the true density is flat right up to them. cut=0 stops the curve at the smallest and largest draws, but it still dips near the edges, because part of each edge draw’s spread falls outside the range. For a distribution with hard edges like this one, a histogram is the clearer picture.

### KDE of 10,000 draws: the default, and stopped at the data's edges
np.random.seed(42)
data = np.random.uniform(0, 5, size=10000)

fig, axes = plt.subplots(1, 2, figsize=(8, 3))
sns.kdeplot(data, ax=axes[0])
sns.kdeplot(data, cut=0, ax=axes[1])
axes[1].set_ylim(bottom=0)                          ### same baseline as the default
axes[0].set_title('Default')
axes[1].set_title('cut=0')
plt.tight_layout()
../../_images/8b04f2483934c1a07694187a84537350e267b1dcd4539a0676f5c795b48a52c7.png

8.2.8. Limit Theorems#

Two results describe what happens as the number of trials or observations grows. The Central Limit Theorem says what shape a sum or average takes; the law of large numbers says where an average ends up. Both use the simulations above.

8.2.8.1. Central Limit Theorem#

A binomial count is a sum of \(n\) independent 0/1 trials. The Central Limit Theorem (CLT) says that sums and averages of many independent values tend toward a normal distribution as the number of values grows, even when each single value is far from normal. So as the number of trials \(n\) gets larger, the binomial distribution should look more and more like a normal curve.

Below, the chance of success is \(p = 0.2\), so with only a few trials the counts pile up near 0 and the distribution is skewed to the right. The code draws 5,000 binomial counts for \(n = 5\), \(30\), and \(300\) trials and overlays a normal curve with the same mean (\(np\)) and standard deviation (\(\sqrt{np(1-p)}\)).

np.random.seed(42)
p = 0.2
ns = [5, 30, 300]

fig, ax = plt.subplots(1, 3, figsize=(12, 3))
for i, n in enumerate(ns):
    counts = np.random.binomial(n=n, p=p, size=5000)      ### 5,000 binomial counts with n trials each
    sns.histplot(counts, discrete=True, stat='density', color='green', ax=ax[i])

    mu, sd = n * p, np.sqrt(n * p * (1 - p))               ### matching normal curve
    x = np.linspace(counts.min() - 1, counts.max() + 1, 300)
    ax[i].plot(x, np.exp(-(x - mu)**2 / (2 * sd**2)) / (sd * np.sqrt(2 * np.pi)), color='red')
    ax[i].set_title(f'n = {n} trials')
plt.tight_layout()
../../_images/5e0e4fef24abe4a6948f948dbb946d717fd9f2f4bf70de4b957ee2a68714b36d.png

The red curve is the normal density written out in code. Piece by piece:

Code

Math

Role

(x - mu)

\(x - \mu\)

distance of each point from the mean

(x - mu)**2 / (2 * sd**2)

\(\dfrac{(x-\mu)^2}{2\sigma^2}\)

that distance in units of the SD, squared and halved

np.exp(-...)

\(e^{-(x-\mu)^2/(2\sigma^2)}\)

the bell shape: 1 at the mean, falling toward 0 as the distance grows

/ (sd * np.sqrt(2 * np.pi))

\(\dfrac{1}{\sigma\sqrt{2\pi}}\)

scaling so the area under the curve is exactly 1

Put together:

\[f(x) = \frac{1}{\sigma\sqrt{2\pi}}\, e^{-\frac{(x-\mu)^2}{2\sigma^2}}\]

At \(x = \mu\) the exponent is 0, so the curve is at its peak; one SD away the exponent is \(-1/2\) and the curve has dropped to about 61% of the peak; two SDs away, about 14%; three SDs away, about 1%. The scaling in front matters because the histogram uses stat='density', which also gives its bars a total area of 1. A wider distribution therefore gets a lower peak, which is why the curve for \(n = 300\) is so much flatter than for \(n = 5\). Because x is an array of 300 points, NumPy evaluates the whole formula at every point at once.

With \(n = 5\) the counts are clearly skewed and the normal curve fits poorly. By \(n = 30\) the shape is close to a bell, and with \(n = 300\) the histogram follows the normal curve almost exactly. Notice that the number of draws (5,000) is the same in every panel. What changes the shape is \(n\), the number of trials added up in each count. Sampling Variability shows the same effect for sample means.

The pull of the binomial toward the normal is one of many links between distributions. Fig. 8.2 shows how common distributions are built from one another or are special cases of one another (solid arrows), or how one approaches another as a number grows (dashed arrows). You do not need to memorize it; read it as a map. The shaded boxes are the distributions simulated in this section.

Map of 18 probability distributions joined by arrows. Solid arrows are exact links, such as Bernoulli to binomial by summing n trials and normal to standard normal by Z = (X - mu) / sigma. Dashed arrows are approximations as a number grows, such as binomial to normal for large n. A dotted line joins Poisson counts and exponential waiting times. The six distributions simulated in Section 8.2 are shaded.

Fig. 8.2 How common probability distributions are connected. Select the figure to enlarge it.#

8.2.8.2. The Law of Large Numbers#

The die demo above ended with a pattern: with 10,000 rolls, each face came up within a few dozen of its expected 1,667, and those gaps shrink relative to the total as the rolls go on. That pattern has a name. The law of large numbers says that as the number of independent trials grows, the proportion of successes settles closer and closer to the true probability. The same holds for averages: the mean of more and more observations settles toward the population mean.

This is a different claim from the Central Limit Theorem above. The CLT describes the shape that a sum or average takes, a bell curve. The law of large numbers describes where an average ends up, at the true value. Sampling Variability uses both to explain why larger samples give better estimates.

To watch it happen, flip a fair coin and track the proportion of heads after each flip. As in the binomial demo, tails is 0 and heads is 1, so the number of heads is a sum.

### 20 flips of a fair coin: tails 0, heads 1
np.random.seed(42)
flips = np.random.choice([0, 1], size=20)
flips
array([0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0])

The proportion of heads after each flip needs two running totals: how many flips so far, and how many of them were heads. np.arange(len(flips)) + 1 counts the flips, 1 through 20.

np.arange(len(flips)) + 1     ### flips so far: 1, 2, 3, ...
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
       18, 19, 20])

flips.cumsum() is the running total of heads. It climbs by 1 on a head and stays flat on a tail, so it grows more slowly than the flip count.

flips.cumsum()                ### heads so far
array([0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 5, 6, 7, 7])

Dividing heads so far by flips so far gives the proportion of heads after each flip. The early values jump around: after one flip the proportion can only be 0 or 1, and after two it can only be 0, 0.5, or 1. Later values move less, because one more flip changes a large total only slightly.

flips.cumsum() / (np.arange(len(flips)) + 1)     ### proportion of heads so far
array([0.        , 0.5       , 0.33333333, 0.25      , 0.2       ,
       0.33333333, 0.28571429, 0.25      , 0.22222222, 0.3       ,
       0.27272727, 0.25      , 0.23076923, 0.21428571, 0.26666667,
       0.25      , 0.29411765, 0.33333333, 0.36842105, 0.35      ])

Now do the same for 5,000 flips and plot the running proportion. The red dashed line is the true probability, 0.5. The left panel zooms in on the first 200 flips; the right panel shows all 5,000.

### running proportion of heads over 5,000 flips
np.random.seed(42)
flips = np.random.choice([0, 1], size=5000)
running_prop = flips.cumsum() / (np.arange(len(flips)) + 1)

fig, axes = plt.subplots(1, 2, figsize=(12, 3.5))
for ax, n in zip(axes, [200, 5000]):
    ax.plot(running_prop[:n], linewidth=1)
    ax.axhline(0.5, color='red', linestyle='--')     ### the true probability
    ax.set_xlabel('Number of flips')
    ax.set_ylabel('Proportion of heads so far')
    ax.set_ylim(0, 1)
    ax.set_title(f'First {n:,} flips')

plt.tight_layout()
../../_images/c04b30ee93448cb9a69234565fcb6f300bee3c91880ec8b92d48c9b57d32ab5f.png

Early on the proportion swings widely, then the swings shrink and the line hugs 0.5. The law of large numbers is a statement about the proportion, not about the count of heads. Below, the count of heads is compared with \(n/2\), the count a perfectly fair split would give, at three points along the way.

### the count of heads can drift while the proportion settles
for n in [100, 1000, 5000]:
    heads = flips[:n].sum()
    print(f'{n:>5,} flips: {heads - n / 2:+5.0f} heads from n/2, proportion {heads / n:.3f}')
  100 flips:    +6 heads from n/2, proportion 0.560
1,000 flips:   +10 heads from n/2, proportion 0.510
5,000 flips:    -4 heads from n/2, proportion 0.499

The count never settles: at 100, 1,000, and 5,000 flips it sits 6, 10, and 4 heads away from \(n/2\), about the same size of gap each time. Yet the proportion goes from 0.560 to 0.499, because the same-sized gap is divided by a growing \(n\).

So a coin that has shown more tails than heads is not “due” for heads. The extra tails are never paid back; they are diluted by the flips that follow. Expecting the count to even out is the gambler’s fallacy; the law of large numbers only promises that the proportion will.

### Exercise: A Biased Coin
# A coin lands heads with probability 0.3.
#   1. Flip it 2,000 times with np.random.choice([0, 1], size=2000, p=[0.7, 0.3]).
#   2. Compute the running proportion of heads after each flip.
#   3. Print the proportion after 10, 100, 1,000, and 2,000 flips, rounded to 3 decimals.
#   4. Plot the running proportion with a red dashed line at 0.3.
# Use the seed below.
# Print exactly:
# After    10 flips: 0.400
# After   100 flips: 0.300
# After 1,000 flips: 0.288
# After 2,000 flips: 0.297
np.random.seed(42)
### Your code starts here




### Your code ends here

Hide code cell source

### Solution
np.random.seed(42)
ex_flips = np.random.choice([0, 1], size=2000, p=[0.7, 0.3])
ex_running_prop = ex_flips.cumsum() / (np.arange(len(ex_flips)) + 1)

for ex_n in [10, 100, 1000, 2000]:
    print(f'After {ex_n:>5,} flips: {ex_running_prop[ex_n - 1]:.3f}')

plt.figure(figsize=(6, 3))
plt.plot(ex_running_prop, linewidth=1)
plt.axhline(0.3, color='red', linestyle='--')
plt.xlabel('Number of flips')
plt.ylabel('Proportion of heads so far')
plt.ylim(0, 1)
plt.title('A biased coin, p = 0.3');
After    10 flips: 0.400
After   100 flips: 0.300
After 1,000 flips: 0.288
After 2,000 flips: 0.297
../../_images/2572fddc83a7b52d8132d50efddf97451ece0af4d5f7efe26645937a2493d115.png

8.2.9. Section Practice#

Use this short exercise to check the main workflow from this section.

### Exercise: Practice Descriptive Distributions
# An online store recorded daily website visits for two weeks.
#   1. Compute the mean, median, and standard deviation (np.std) of visits.
#   2. Is the distribution skewed? Compare the mean with the median.
#   3. Print the three statistics rounded to 1 decimal, and which one you would
#      report as a "typical" day.
#   4. Use np.percentile() to find Q1 and Q3, then the IQR and the upper fence
#      (Q3 + 1.5 * IQR). How many days are outliers above the fence?
# Print exactly:
# Mean: 527.5
# Median: 417.5
# SD: 281.3
# Typical day: median
# Q1: 406.25
# Q3: 428.75
# IQR: 22.5
# Upper fence: 462.5
# Outlier days: 2
import numpy as np

visits = np.array([410, 395, 430, 420, 405, 1250, 415, 400, 425, 390, 435, 410, 1180, 420])
### Your code starts here




### Your code ends here

Hide code cell source

### Solution
import numpy as np

visits = np.array([410, 395, 430, 420, 405, 1250, 415, 400, 425, 390, 435, 410, 1180, 420])

mean_visits = np.mean(visits)
median_visits = np.median(visits)
sd_visits = np.std(visits)

print('Mean:', round(mean_visits, 1))
print('Median:', round(median_visits, 1))
print('SD:', round(sd_visits, 1))
print('Typical day: median' if mean_visits > median_visits * 1.2 else 'Typical day: mean')
# Two promotion days pull the mean far above the median, so the distribution
# is skewed to the right and the median describes a typical day better.

q1, q3 = np.percentile(visits, [25, 75])
ex_iqr = q3 - q1
ex_upper_fence = q3 + 1.5 * ex_iqr

print('Q1:', q1)
print('Q3:', q3)
print('IQR:', ex_iqr)
print('Upper fence:', ex_upper_fence)
print('Outlier days:', (visits > ex_upper_fence).sum())
# The two promotion days (1,250 and 1,180 visits) are the outliers.
Mean: 527.5
Median: 417.5
SD: 281.3
Typical day: median
Q1: 406.25
Q3: 428.75
IQR: 22.5
Upper fence: 462.5
Outlier days: 2