Statistical modeling with Python · Lesson 2 of 16
Describing data: mean, median and spread
Summarise a column before you model it: mean and median, standard deviation, quantiles and IQR, group summaries and a box plot.
Before any model, look at the numbers. Where is the middle? How spread out are they? Are there odd values? These descriptive statistics take one line each in pandas, and they decide which model makes sense later.
The data: 18 people in three cities wrote down how many minutes their trip to work took.
The middle: mean and median
The mean is the usual average: add up, divide by the count. The median is the middle value once the numbers are sorted: half are below, half above. One very long trip (75 minutes in Turin) pulls the mean up but barely moves the median.
import pandas as pd
df = pd.DataFrame({
"city": ["Lyon"] * 6 + ["Porto"] * 6 + ["Turin"] * 6,
"minutes": [22, 25, 31, 28, 24, 26,
18, 35, 20, 41, 19, 33,
27, 29, 26, 30, 75, 28],
})
m = df["minutes"]
print("mean: ", round(m.mean(), 2))
print("median:", m.median())
print("without the 75:", round(m[m < 75].mean(), 2))mean: 29.83 median: 27.5 without the 75: 27.18
The spread: standard deviation and quantiles
The standard deviation (std) is roughly the typical distance of a value from the mean. pandas divides by n − 1 (the sample standard deviation), which is what statistics books use for data that is a sample of something bigger; NumPy's np.std divides by n unless you pass ddof=1, so the two can disagree.
Quantiles cut the sorted data: the 0.25 quantile (first quartile) has a quarter of the values below it. The interquartile range (IQR = Q3 − Q1) is the width of the middle half, and like the median it ignores extreme values.
import pandas as pd
df = pd.DataFrame({
"city": ["Lyon"] * 6 + ["Porto"] * 6 + ["Turin"] * 6,
"minutes": [22, 25, 31, 28, 24, 26,
18, 35, 20, 41, 19, 33,
27, 29, 26, 30, 75, 28],
})
m = df["minutes"]
print("std:", round(m.std(), 2))
print("variance:", round(m.var(), 2))
q = m.quantile([0.25, 0.5, 0.75])
print(q)
print("IQR:", q[0.75] - q[0.25])
print(m.describe().round(2))std: 12.65 variance: 160.03 0.25 24.25 0.50 27.50 0.75 30.75 Name: minutes, dtype: float64 IQR: 6.5 count 18.00 mean 29.83 std 12.65 min 18.00 25% 24.25 50% 27.50 75% 30.75 max 75.00 Name: minutes, dtype: float64
describe() puts count, mean, std, min, the quartiles and max in one place.
Summaries by group
Statistics get interesting when you compare groups. groupby with agg (see groupby: totals and averages by group) gives several summaries per city at once.
import pandas as pd
df = pd.DataFrame({
"city": ["Lyon"] * 6 + ["Porto"] * 6 + ["Turin"] * 6,
"minutes": [22, 25, 31, 28, 24, 26,
18, 35, 20, 41, 19, 33,
27, 29, 26, 30, 75, 28],
})
summary = df.groupby("city")["minutes"].agg(["mean", "median", "std"])
print(summary.round(1))mean median std city Lyon 26.0 25.5 3.2 Porto 27.7 26.5 9.9 Turin 35.8 28.5 19.2
How to read it: Porto and Lyon have similar means, but Porto's standard deviation is three times bigger: trips there are less predictable. Turin's mean is high only because of one 75-minute trip; its median is in line with Lyon's. When mean and median disagree, look for extreme values.
A box plot shows it all
A box plot draws the median (line), the middle half (box), the normal range (whiskers) and the points beyond it (dots, possible outliers). One box per group makes comparisons quick.
import pandas as pd
df = pd.DataFrame({
"city": ["Lyon"] * 6 + ["Porto"] * 6 + ["Turin"] * 6,
"minutes": [22, 25, 31, 28, 24, 26,
18, 35, 20, 41, 19, 33,
27, 29, 26, 30, 75, 28],
})
import matplotlib.pyplot as plt
cities = ["Lyon", "Porto", "Turin"]
groups = [df.loc[df["city"] == c, "minutes"] for c in cities]
print("Medians:", [float(g.median()) for g in groups])
plt.boxplot(groups)
plt.xticks([1, 2, 3], cities)
plt.title("Trip to work (minutes)")
plt.ylabel("Minutes")
plt.show()Medians: [25.5, 26.5, 28.5]

✎ Exercise
For each city print the median and the IQR (Q3 − Q1) of the trip times. Tip: quantile(0.75) - quantile(0.25) inside a function.
Hint: Define def iqr(s): return s.quantile(0.75) - s.quantile(0.25), then df.groupby("city")["minutes"].agg(iqr).
import pandas as pd
df = pd.DataFrame({
"city": ["Lyon"] * 6 + ["Porto"] * 6 + ["Turin"] * 6,
"minutes": [22, 25, 31, 28, 24, 26,
18, 35, 20, 41, 19, 33,
27, 29, 26, 30, 75, 28],
})
# your code here
Expected output:
city Lyon 25.5 Porto 26.5 Turin 28.5 Name: minutes, dtype: float64 city Lyon 3.25 Porto 15.25 Turin 2.50 Name: minutes, dtype: float64
Show a solution
import pandas as pd
df = pd.DataFrame({
"city": ["Lyon"] * 6 + ["Porto"] * 6 + ["Turin"] * 6,
"minutes": [22, 25, 31, 28, 24, 26,
18, 35, 20, 41, 19, 33,
27, 29, 26, 30, 75, 28],
})
print(df.groupby("city")["minutes"].median())
def iqr(s):
return s.quantile(0.75) - s.quantile(0.25)
print(df.groupby("city")["minutes"].agg(iqr))city Lyon 25.5 Porto 26.5 Turin 28.5 Name: minutes, dtype: float64 city Lyon 3.25 Porto 15.25 Turin 2.50 Name: minutes, dtype: float64
Check yourself
1. One value in a column is much larger than the others. Which summary moves the most?
The mean uses every value's size; the median and IQR only depend on the order.
2. What does pandas' std() divide by?
pandas gives the sample standard deviation (ddof=1). NumPy's np.std uses n unless you pass ddof=1.
3. The 0.25 quantile of a column is 24. What does that mean?
The first quartile has roughly 25% of the sorted values below it.