TExcelTAD

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 x1,…,xnx_1, \ldots, x_n:

xˉ=1n∑i=1nxis2=1n−1∑i=1n(xi−xˉ)2s=s2\bar{x} = \frac{1}{n}\sum_{i=1}^{n} x_i \qquad s^2 = \frac{1}{n-1}\sum_{i=1}^{n} (x_i - \bar{x})^2 \qquad s = \sqrt{s^2}

The mean xˉ\bar{x} is the balance point, the sample variance s2s^2 the average squared distance from it (divided by n−1n - 1, the convention of pandas and the Statistics course), and the standard deviation ss its square root, in the column's own unit. The median is the middle value after sorting, and the quantile qpq_p is the value below which a share pp of the data lies, so the median is q0.5q_{0.5}. The interquartile range IQR=q0.75−q0.25\text{IQR} = q_{0.75} - q_{0.25} is the width of the middle half of the data. The mean and ss 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

python · try it yourself
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 ss 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:

python · try it yourself
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:

python · try it yourself
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 −1-1 to 11:

rxy=∑i(xi−xˉ)(yi−yˉ)∑i(xi−xˉ)2 ∑i(yi−yˉ)2r_{xy} = \frac{\sum_i (x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum_i (x_i - \bar{x})^2}\,\sqrt{\sum_i (y_i - \bar{y})^2}}

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):

python · try it yourself
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 -1 or 999 for "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

  1. 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 q0.9q_{0.9}) rather than the mean.

  1. Compute the sample mean and standard deviation of 2,4,4,4,5,5,7,92, 4, 4, 4, 5, 5, 7, 9 by hand.
Answer

xˉ=40/8=5\bar{x} = 40/8 = 5. The squared deviations are 9,1,1,1,0,0,4,169, 1, 1, 1, 0, 0, 4, 16, summing to 3232. s2=32/7≈4.571s^2 = 32/7 \approx 4.571 and s≈2.138s \approx 2.138. (Dividing by n=8n = 8 instead gives the population value 22.)

Test yourself

Which statistics are robust to a few extreme values?

  1. Mean and standard deviation
  2. Median and interquartile range
  3. Maximum and minimum
  4. Sum and variance

pandas' std() divides by…

  1. nn
  2. n−1n - 1
  3. n+1n + 1
  4. n\sqrt{n}

A feature has a correlation of 0.999 with the label. What should you suspect first?

  1. A great feature
  2. A leak: the feature may be derived from the label
  3. A measurement in the wrong unit
  4. Nothing

Income data has a mean far above its median. The distribution is…

  1. Symmetric
  2. Left-skewed
  3. Right-skewed
  4. Uniform