Summary Statistics
A column of a thousand numbers is unreadable; five well-chosen numbers describe it surprisingly well. Summary statistics describe where the values sit (centre), how widely they vary (spread), how lopsided they are (shape), and how columns move together (correlation). For ML they are a fast check: a summary that contradicts what you know about the world points to a data problem, and the summaries of the training data become the reference for spotting drift later.
The Statistics course explains each measure in depth (mean, median, standard deviation, quartiles, correlation); this lesson is about using them on datasets.
Centre, spread and shape
For a column with values :
The mean is the balance point, the sample variance the average squared distance from it (divided by , the convention of pandas and the Statistics course), and the standard deviation its square root, in the column's own unit. The median is the middle value after sorting, and the quantile is the value below which a share of the data lies, so the median is . The interquartile range is the width of the middle half of the data. The mean and are pulled by extreme values; the median and the IQR are robust: a few extreme values barely move them.
Shape is measured by the skewness, which is positive when the long tail points to large values. Incomes, prices, waiting times and counts are typically right-skewed.
From scratch with NumPy
import numpy as np
rng = np.random.default_rng(0)
income = np.round(rng.lognormal(mean=10.6, sigma=0.5, size=1000), -2) # right-skewed, like real incomes
income[:3] = [2_500_000, 1_800_000, 950_000] # three very rich applicants
n = len(income)
mean = income.sum() / n
var = ((income - mean) ** 2).sum() / (n - 1)
std = var ** 0.5
srt = np.sort(income)
median = (srt[n // 2 - 1] + srt[n // 2]) / 2 # n is even
q1, q3 = np.quantile(income, [0.25, 0.75])
skew = (((income - mean) / std) ** 3).mean()
print(f"n={n} mean={mean:,.0f} median={median:,.0f}")
print(f"std={std:,.0f} IQR={q3 - q1:,.0f} (q1={q1:,.0f}, q3={q3:,.0f})")
print(f"skewness={skew:.2f}")
no_top3 = srt[:-3]
print(f"without the top 3: mean={no_top3.mean():,.0f} median={np.median(no_top3):,.0f} std={no_top3.std(ddof=1):,.0f}")n=1000 mean=49,218 median=38,800
std=102,133 IQR=26,425 (q1=28,400, q3=54,825)
skewness=19.55
without the top 3: mean=44,101 median=38,600 std=22,664
Three applicants out of 1,000 move the mean from 44,101 to 49,218 and multiply the standard deviation by more than four (22,664 without them, 102,133 with them), while the median moves by just 200 (38,600 to 38,800). The skewness of 19.55 is extreme; incomes without such outliers are typically around 1 to 3. For a column like this, the median and the IQR describe a "typical" applicant, and the mean and mostly describe the three outliers.
The same with pandas
describe() gives count, mean, standard deviation, minimum, quartiles and maximum for every numeric column; skew() and median() add the rest. Grouping by the label shows how each feature differs between classes, which is often the most informative table of an early analysis:
import pandas as pd
from sklearn.datasets import load_wine
wine = load_wine(as_frame=True).frame
cols = ["alcohol", "malic_acid", "proline", "color_intensity"]
print(wine[cols].describe().round(2))
print()
print("skewness:", wine[cols].skew().round(2).to_dict())
print()
print(wine.groupby("target")[cols].median().round(2)) alcohol malic_acid proline color_intensity
count 178.00 178.00 178.00 178.00
mean 13.00 2.34 746.89 5.06
std 0.81 1.12 314.91 2.32
min 11.03 0.74 278.00 1.28
25% 12.36 1.60 500.50 3.22
50% 13.05 1.87 673.50 4.69
75% 13.68 3.08 985.00 6.20
max 14.83 5.80 1680.00 13.00
skewness: {'alcohol': -0.05, 'malic_acid': 1.04, 'proline': 0.77, 'color_intensity': 0.87}
alcohol malic_acid proline color_intensity
target
0 13.75 1.77 1095.0 5.40
1 12.29 1.61 495.0 2.90
2 13.16 3.26 627.5 7.55
The per-class medians already show which features separate the three cultivars: proline is far higher in class 0, and color_intensity is lowest in class 1. A model will find the same; seeing it first tells you what to expect.
Categorical columns
For categories, the summaries are counts and shares, the mode, and the number of distinct values:
import pandas as pd
tickets = pd.Series(["billing", "login", "billing", "shipping", "billing", "login",
"refund", "billing", "shipping", "login", "billing", "other"])
counts = tickets.value_counts()
print(pd.DataFrame({"count": counts, "share": (counts / len(tickets)).round(3)}))
print("mode:", tickets.mode()[0], "| distinct:", tickets.nunique()) count share
billing 5 0.417
login 3 0.250
shipping 2 0.167
refund 1 0.083
other 1 0.083
mode: billing | distinct: 5
Correlation
The Pearson correlation between two columns measures how well a straight line describes their relation, from to :
For a dataset, the correlation matrix shows redundant features (two columns that are almost the same) and suspicious ones (a feature correlated almost perfectly with the label may be a leak):
import numpy as np
import pandas as pd
from sklearn.datasets import load_breast_cancer
df = load_breast_cancer(as_frame=True).frame
corr = df.corr()
pairs = corr.where(np.triu(np.ones(corr.shape, dtype=bool), k=1)).stack()
print("most correlated feature pairs:")
print(pairs.abs().sort_values(ascending=False).head(4).round(4))
print()
print("strongest correlations with the target:")
print(corr["target"].drop("target").abs().sort_values(ascending=False).head(3).round(3))most correlated feature pairs:
mean radius mean perimeter 0.9979
worst radius worst perimeter 0.9937
mean radius mean area 0.9874
mean perimeter mean area 0.9865
dtype: float64
strongest correlations with the target:
worst concave points 0.794
worst perimeter 0.783
mean concave points 0.777
Name: target, dtype: float64
mean radius, mean perimeter and mean area are almost perfectly correlated, as geometry says they must be (perimeter and area are both determined by the radius). Keeping all three adds little information; Data Preparation shows how to select features. Correlation only measures linear relations and says nothing about cause; the Statistics course has the details.
Pitfalls
- The mean of skewed data: report the median (and quantiles) for incomes, prices and durations.
- Placeholders in statistics: a
-1or999for "unknown" distorts every summary. Inspect first. - Summaries hide structure: very different datasets can share the same mean, standard deviation and correlation (Anscombe's quartet). Always plot as well (Visualising Data).
- Statistics of the whole dataset vs the training part: values used later for preprocessing (means for scaling, medians for filling) must come from the training data only.
Practice
- A column of delivery times in days has mean 4.8 and median 2. What does that suggest?
Answer
A strong right skew: most deliveries are quick, and a few very late ones pull the mean up. Report the median and a high quantile (for example ) rather than the mean.
- Compute the sample mean and standard deviation of by hand.
Answer
. The squared deviations are , summing to . and . (Dividing by instead gives the population value .)
Test yourself
Which statistics are robust to a few extreme values?
- Mean and standard deviation
- Median and interquartile range
- Maximum and minimum
- Sum and variance
pandas' std() divides by…
A feature has a correlation of 0.999 with the label. What should you suspect first?
- A great feature
- A leak: the feature may be derived from the label
- A measurement in the wrong unit
- Nothing
Income data has a mean far above its median. The distribution is…
- Symmetric
- Left-skewed
- Right-skewed
- Uniform