Module contents
Lesson 1 of 27Review 75 min

Descriptive statistics and exploratory data analysis

A dense review of summarizing and examining data before modeling: location, spread, shape, quantiles, the empirical distribution function, and linear and rank correlations. Introduce robustness (breakdown point) and use Anscombe’s quartet and the Datasaurus dozen to show why summaries without visualization mislead.

After this lesson you can

  • Calculate and interpret mean, median, variance, MAD, quantiles, skewness, and kurtosis, choosing measures suited to the shape of the data.
  • Construct the empirical distribution function and use it to read quantiles, tails, and differences between samples.
  • Determine a statistic’s breakdown point and justify when to use the median, trimmed mean, or MAD.
  • Distinguish Pearson, Spearman, and Kendall correlations and use plots to detect relationships hidden by a single coefficient.
  • Implement reproducible exploratory analysis with NumPy and pandas, including numerically stable variance.

Before you start

Motivation: summarizing loses information

Before fitting a model there is a dataset, and the first question is what it contains. Almost always the answer involves summarizing it: a mean, standard deviation, 99th percentile, or correlation coefficient. These are what you inspect on a service monitoring dashboard, in a training-set quality report, or in table 1 of a paper. A summary is a function turning nn numbers into a few, and every function with fewer outputs than inputs discards information. What determines whether analysis is reliable is which information it discards and whether you noticed.

The classic example is by Francis Anscombe (1973). Four sets of eleven pairs (x,y)(x, y) with the same summaries:

IIIIIIIV
mean of xx9.09.09.09.0
variance of xx11.011.011.011.0
mean of yy7.507.507.507.50
variance of yy4.1274.1284.1234.123
correlation rr0.8160.8160.8160.817
least-squares liney=3.00+0.500xy = 3.00 + 0.500xy=3.00+0.500xy = 3.00 + 0.500xy=3.00+0.500xy = 3.00 + 0.500xy=3.00+0.500xy = 3.00 + 0.500x

An analyst reading only the table concludes these are the same phenomenon. Now look at the data.

InteractiveSame statistics, different clouds
Dataset I
Dataset II
Dataset III
Dataset IV
Data
Dataset
Dataset I: xˉ\bar x9.00
sx2s_x^211.00
yˉ\bar y7.50
sy2s_y^24.13
Pearson's rr0.816
Least-squares liney = 3.00 + 0.500x
All four datasets produce the same numbers (to three digits, rr ranges from 0.816 to 0.817), yet their plots look completely different.
With 'Anscombe', the four 1973 sets with their least-squares lines: click one to read its summaries. With 'Clouds', one hundred Gaussian points deform toward your chosen shape (or one you draw: select 'Drawn by me' and trace on the chart). At each step, the cloud is projected onto the same five statistics (two means, two standard deviations, and correlation), which remain identical to two decimals as the drawing changes completely. Disable 'Keep the five statistics' and repeat: summaries drift. Try the X and horizontal lines; notice some shapes are easier to reach than others, because not all are compatible with given statistics.

The four sets tell four different stories. I is what one imagines from a correlation of 0.820.82: a linear relationship with noise. II is a curve, an almost exact parabola, and a line is a poor model. III is a perfect line, y=4.01+0.345xy = 4.01 + 0.345x, with one outlier pulling the fit to y=3.00+0.500xy = 3.00 + 0.500x (without it, r=0.999997r = 0.999997). In IV all xx values are 8 except one, which is 19: one observation determines the entire slope, and without it no slope can be estimated.

Anscombe constructed his data by hand. More than forty years later, Matejka and Fitzmaurice (2017) generated the Datasaurus dozen: thirteen datasets including a dinosaur, star, bullseye, and several lines, all with means, standard deviations, and correlation identical to two decimals, by simulated annealing: move points randomly, accepting the move if the cloud approaches the desired shape and summaries do not change. The second half of the preceding figure does the same with another method, an affine projection at each step, and its own geometric shapes (the original dozen is a published dataset and is not reproduced here).

Why is it so easy? Because fixing five numbers imposes five constraints on 2n2n coordinates. With n=100n = 100 points, the set of clouds with the same means, standard deviations, and correlation is a manifold of dimension 2n−5=1952n - 5 = 195: almost the whole space remains free. Any fixed-dimensional summary pp leaves 2n−p2n - p degrees of freedom, and what is hidden there may be exactly what matters.

The discipline arising from this section has three rules, developed in the rest of the lesson: summarize with the statistic appropriate to the shape of the data, know how that statistic behaves when data are contaminated, and always plot the data before trusting the summary.

Location and spread

We work with a sample x1,…,xn∈Rx_1, \dots, x_n \in \R, its order statistics x(1)≤⋯≤x(n)x_{(1)} \le \dots \le x_{(n)}, and functions of them that summarize it. As with expectation and variance in the moments lesson, each sample summary is an empirical analog of a population quantity; lesson 2 asks how close it is.

Equivariance is not a detail: it says the summary does not depend on units. If latency is measured in milliseconds or seconds, the median changes by a factor of 10001000 and skewness does not change at all.

Mean and median as solutions to a problem

The mean xˉ=1n∑ixi\bar{x} = \frac{1}{n}\sum_i x_i and median (the middle value of x(1),…,x(n)x_{(1)}, \dots, x_{(n)}, or half the sum of the two middle values) appear to be different recipes. They are the solutions of two constant-fitting problems with different losses.

The first identity follows in one line. Adding and subtracting xˉ\bar{x},

∑i(xi−c)2=∑i(xi−xˉ)2+2(xˉ−c)∑i(xi−xˉ)⏟= 0+n(xˉ−c)2=∑i(xi−xˉ)2+n(xˉ−c)2,\sum_i (x_i - c)^2 = \sum_i (x_i - \bar{x})^2 + 2(\bar{x} - c)\underbrace{\sum_i (x_i - \bar{x})}_{=\,0} + n(\bar{x} - c)^2 = \sum_i (x_i - \bar{x})^2 + n(\bar{x} - c)^2,

which is minimized uniquely at c=xˉc = \bar{x}. The minimum is ∑i(xi−xˉ)2\sum_i (x_i - \bar{x})^2, the sample’s total variation. The proof for the median, using a piecewise-linear function instead of a parabola, is the guided exercise at the end.

The interpretation is pure machine learning. Predicting a constant with squared loss gives the mean; with absolute loss, the median; and pinball loss (absolute loss with different weights on each side) yields any other quantile. Choosing a summary chooses a loss, and squared loss squares large deviations: this is why a distant observation dominates the rest. The robustness figure below makes this visible.

Variance, standard deviation, and the n−1n - 1 divisor

The sample variance and standard deviation are

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

The n−1n - 1 divisor (Bessel’s correction) is not arbitrary: it makes the estimator unbiased. The reason is that deviations are measured from xˉ\bar{x}, fitted to the same data and therefore closer to them than population mean μ\mu.

Proof

Adding and subtracting μ\mu and expanding, with ∑i(Xi−Xˉ)=0\sum_i (X_i - \bar{X}) = 0,

∑i(Xi−μ)2=∑i(Xi−Xˉ)2+n(Xˉ−μ)2.\sum_i (X_i - \mu)^2 = \sum_i (X_i - \bar{X})^2 + n(\bar{X} - \mu)^2.

Take expectations. The left side is nσ2n\sigma^2. Since Xˉ\bar{X} is the mean of nn independent variables with variance σ2\sigma^2, E[(Xˉ−μ)2]=Var⁡(Xˉ)=σ2/n\E[(\bar{X} - \mu)^2] = \Var(\bar{X}) = \sigma^2/n, and the last term contributes σ2\sigma^2. Thus E∑i(Xi−Xˉ)2=(n−1)σ2\E\sum_i (X_i - \bar{X})^2 = (n-1)\sigma^2, and dividing by n−1n - 1 gives σ2\sigma^2.

∎

Two clarifications. Unbiasedness applies to s2s^2, not ss: by Jensen’s inequality (⋅\sqrt{\cdot} is concave), E[s]<σ\E[s] < \sigma. With large nn the divisor barely matters; with n=5n = 5 dividing by 55 instead of 44 differs by 25%. NumPy defaults to nn (ddof=0), pandas uses n−1n - 1 (ddof=1): a classic trap.

Robust scales

The interquartile range IQR=Q(0.75)−Q(0.25)\mathrm{IQR} = Q(0.75) - Q(0.25) and median absolute deviation MAD=mediana⁡i ∣xi−mediana⁡(x)∣\mathrm{MAD} = \operatorname{mediana}_i\,\abs{x_i - \operatorname{mediana}(\vb{x})} measure spread without squaring, so an extreme observation barely moves them. To compare them with ss convert them to the same scale. If X∼N(μ,σ2)X \sim \Normal(\mu, \sigma^2), then ∣X−μ∣/σ\abs{X - \mu}/\sigma is the absolute value of a standard normal, whose median is Φ−1(3/4)≈0.6745\Phi^{-1}(3/4) \approx 0.6745 (Φ\Phi is the standard normal CDF). Therefore

σ=MADΦ−1(3/4)≈1.4826 MAD,σ=IQR2 Φ−1(3/4)≈IQR1.349.\sigma = \frac{\mathrm{MAD}}{\Phi^{-1}(3/4)} \approx 1.4826\,\mathrm{MAD}, \qquad \sigma = \frac{\mathrm{IQR}}{2\,\Phi^{-1}(3/4)} \approx \frac{\mathrm{IQR}}{1.349}.

The scaled MAD 1.4826 MAD1.4826\,\mathrm{MAD} is a consistent estimator of σ\sigma for Gaussian data and numerically comparable to ss. With outliers, when ss and scaled MAD differ greatly, something is happening. The price is efficiency: on clean Gaussian data MAD has asymptotic efficiency of 37% relative to ss (Rousseeuw and Croux, 1993), meaning it needs about 2.7 times as much data to match precision.

The mode is the most frequent value. For continuous data it has no sample definition: it depends on grouping, as the ECDF figure shows. It is estimated with a histogram or kernel density estimate (density estimation lesson).

Shape: skewness, kurtosis, and heavy tails

Location and spread do not say how mass is distributed. Standardized moments do: subtract location, divide by scale, and inspect third and fourth powers (higher moments). For the sample,

g1=m3m23/2,g2=m4m22−3,mk=1n∑i=1n(xi−xˉ)k.g_1 = \frac{m_3}{m_2^{3/2}}, \qquad g_2 = \frac{m_4}{m_2^2} - 3, \qquad m_k = \frac{1}{n}\sum_{i=1}^n (x_i - \bar{x})^k.

g1g_1 is skewness: positive if the right tail is longer, and 00 for symmetric distributions. g2g_2 is excess kurtosis: the −3-3 makes it 00 for a normal. Positive kurtosis indicates more mass in the center and tails than a normal with the same variance and less in the shoulders; Laplace has excess 33, Student’s tt with ν>4\nu > 4 degrees of freedom has 6/(ν−4)6/(\nu - 4), and uniform has −1.2-1.2. Above all, g2g_2 measures tail weight: the fourth moment is dominated by the farthest values.

A detail rarely mentioned is that these statistics cannot take just any value.

Proof

The first bound is immediate: with di=xi−xˉd_i = x_i - \bar{x}, ∑idi4≤(∑idi2)2\sum_i d_i^4 \le \big(\sum_i d_i^2\big)^2 because the square of a sum of nonnegative terms contains each term’s square, and m4/m22=n∑idi4/(∑idi2)2≤nm_4/m_2^2 = n\sum_i d_i^4 / \big(\sum_i d_i^2\big)^2 \le n. The exact bound is attained with one observation at distance (n−1)c(n-1)c from the mean and the other n−1n - 1 at distance −c-c: then m2=(n−1)c2m_2 = (n-1)c^2, m4=(n−1)(n2−3n+3)c4m_4 = (n-1)(n^2 - 3n + 3)c^4 and thus m4/m22=(n2−3n+3)/(n−1)m_4/m_2^2 = (n^2 - 3n + 3)/(n - 1), giving g2=n−5+1/(n−1)g_2 = n - 5 + 1/(n-1); in the same configuration, m3=(n−1)(n−2)c3m_3 = (n-1)(n-2)c^3 and g1=(n−2)/n−1g_1 = (n-2)/\sqrt{n-1}. That these values cannot be exceeded is Dalén’s result (1987). A two-line argument gives almost the same. Normalize ∑idi2=n\sum_i d_i^2 = n (so m2=1m_2 = 1) and let u=max⁡idi2u = \max_i d_i^2, attained at d1d_1. Since d1=−∑i≥2did_1 = -\sum_{i \ge 2} d_i, Cauchy-Schwarz gives d12≤(n−1)(n−d12)d_1^2 \le (n-1)(n - d_1^2), that is u≤n−1u \le n - 1; and u≥1u \ge 1 because the maximum exceeds the mean. Applying the first bound to the other n−1n - 1 observations, ∑idi4≤u2+(n−u)2\sum_i d_i^4 \le u^2 + (n - u)^2, a convex function of uu whose maximum on [1,n−1][1, n-1] is at an endpoint and equals (n−1)2+1(n-1)^2 + 1. Therefore m4/m22≤n−2+2/nm_4/m_2^2 \le n - 2 + 2/n, exceeding the exact bound n−2+1/(n−1)n - 2 + 1/(n-1) by only (n−2)/(n(n−1))(n-2)/\big(n(n-1)\big).

∎

With n=10n = 10, sample kurtosis cannot exceed 5.115.11 however contaminated the data. A lognormal with σ=1\sigma = 1 has population excess kurtosis 110.9110.9: no sample of fewer than 116116 observations can even attain that value. This is a bound, not an opinion.

InteractiveSample kurtosis is unstable
Histogram of 300 values of g2g_2 with n=100n = 100
3 values fall outside the chart.
Median and 10 %-90 % band of g2g_2 by nn (150 samples per point)
n = 10n = 100n = 1000
  • sample median
  • 10 %-90 % band
  • theoretical value
  • maximum possible with nn observations
Statistic
Distribution
100
Theoretical value of g2g_23.00
Median of g2g_2 with n=100n = 1001.85
10 %-90 % band0.75 to 4.58
Maximum possible bound with n=100n = 10095.0
With exponential tails, the median of g2g_2 is 1.85 versus theoretical 3.00, and the central 80 % of samples ranges from 0.75 to 4.58.
For each distribution, simulate many samples of size nn and plot the histogram of g2g_2 (left), with theoretical value dashed, and how the median and central 80% change with nn (right). The figure starts with Laplace and n=100n = 100: theoretical value is 3, but median g2g_2 is clearly below it. Switch to normal: it converges to 0, but at n=10n = 10 the center is below it (sample kurtosis is biased, with mean −6/(n+1)-6/(n+1)). Then try tt with 5 and 3 degrees of freedom and lognormal: the band barely narrows throughout the nn range and the median stays far from the theoretical value. The red dashed line is the maximum possible with nn observations. Switch to skewness and compare.

Lessons from the figure:

  1. Bias is real. Even with normal data, E[g2]≈−6/(n+1)\E[g_2] \approx -6/(n+1): with n=10n = 10, −0.55-0.55.
  2. Variance is enormous with heavy tails. The sample’s fourth moment has variance depending on the population eighth moment. With a tt of 5 degrees of freedom the fourth moment exists and g2→6g_2 \to 6 almost surely, but the eighth is infinite: there is no central limit theorem at rate 1/n1/\sqrt{n}, and between n=100n = 100 and n=1000n = 1000 the 10%-90% band barely narrows.
  3. Some distributions have no kurtosis. A tt with 3 degrees of freedom has finite variance but infinite fourth moment: g2g_2 grows with nn instead of converging. Variables such as income, file size, or latency often have such tails, with few finite moments (heavy-tailed distributions).

The practical consequence: do not use g2g_2 to decide whether a variable is normal, or report it to three decimals on a sample of one hundred. Quantile plots and the ECDF, next, tell much more.

Quantiles and the empirical distribution function

The best way to inspect a one-dimensional variable is to see its entire empirical distribution, not a summary. That is what the empirical distribution function does.

If the data are Xi∼iidFX_i \iid F, then nFn(x)∼Bin⁡(n,F(x))nF_n(x) \sim \Bin(n, F(x)) for each fixed xx, so E[Fn(x)]=F(x)\E[F_n(x)] = F(x) and Var⁡(Fn(x))=F(x)(1−F(x))/n\Var(F_n(x)) = F(x)(1 - F(x))/n: an unbiased estimator whose uncertainty is largest at the median and vanishes in the tails. More strongly, the Glivenko-Cantelli theorem says sup⁡x∣Fn(x)−F(x)∣→0\sup_x \abs{F_n(x) - F(x)} \to 0 almost surely, and the DKW inequality gives the rate: P(sup⁡x∣Fn(x)−F(x)∣>ε)≤2e−2nε2\Pr\big(\sup_x \abs{F_n(x) - F(x)} > \eps\big) \le 2e^{-2n\eps^2}. The ECDF converges uniformly to the true distribution without choosing anything.

A way of viewing earlier summaries unifies almost everything following in the module: a summary is a functional of the ECDF. The mean is ∫x  ⁣dFn(x)\int x\,\dd F_n(x), variance is ∫(x−xˉ)2  ⁣dFn(x)\int (x - \bar{x})^2\,\dd F_n(x) (with divisor nn), and a quantile is the inverse of FnF_n. Replacing unknown distribution FF by FnF_n in a formula is called the plug-in principle, revisited with the bootstrap (lesson 16).

Quantiles and their conventions

The population quantile is Q(p)=inf⁡{x:F(x)≥p}Q(p) = \inf\{x : F(x) \ge p\}. The empirical quantile, Qn(p)=inf⁡{x:Fn(x)≥p}=x(⌈np⌉)Q_n(p) = \inf\{x : F_n(x) \ge p\} = x_{(\lceil np \rceil)}, is a step function: it always returns an observation. Many programs interpolate between observations to smooth it, and disagree on how. Hyndman and Fan (1996) catalogued nine conventions; nearly all write the quantile as linear interpolation between order statistics at position (starting from 1)

h=(n+1−a−b) p+a,Q(p)=x(⌊h⌋)+(h−⌊h⌋)(x(⌊h⌋+1)−x(⌊h⌋)),h = (n + 1 - a - b)\,p + a, \qquad Q(p) = x_{(\lfloor h \rfloor)} + (h - \lfloor h \rfloor)\big(x_{(\lfloor h \rfloor + 1)} - x_{(\lfloor h \rfloor)}\big),

with hh bounded to [1,n][1, n] and different pairs (a,b)(a, b). Those that matter in practice:

Type(a,b)(a, b)method= in NumPyUse
1no interpolationinverted_cdftheoretical definition, x(⌈np⌉)x_{(\lceil np \rceil)}
6(0,0)(0, 0)weibullpk=k/(n+1)p_k = k/(n+1); Minitab, SPSS
7(1,1)(1, 1)lineardefault in NumPy, pandas, and R
8(1/3,1/3)(1/3, 1/3)median_unbiasedrecommended by Hyndman and Fan

For sample (2,3,5,7,11,13,17,19)(2, 3, 5, 7, 11, 13, 17, 19) and p=0.9p = 0.9, type 1 gives 1919, type 6 gives 1919, type 7 gives 17.617.6, and type 8 gives 18.6718.67: the same sample, three different results. With large nn differences vanish, but on small evaluation sets (a few hundred examples) or extreme percentiles they can be on the order of estimation error.

Reading tails: p95 and p99

High percentiles are the most watched in systems (p99 latency, p95 risk loss) and the worst estimated. Estimator Qn(p)Q_n(p) has asymptotic variance p(1−p)/(nf(Q(p))2)p(1-p)/\big(n f(Q(p))^2\big), where ff is density: density is small in the tails and error grows. There is also a combinatorial limit. For Qn(0.99)Q_n(0.99) to be more than the maximum, n≫100n \gg 100 is needed: if n=100n = 100, p99 lies between the largest and second-largest observation and is determined by a pair of observations. A useful rule: require at least about ten observations above the desired quantile, that is n≳10/(1−p)n \gtrsim 10/(1 - p).

Histogram versus ECDF

The histogram is the usual mental image of a distribution and has two analyst-chosen parameters: bin width hh and origin. With bins [o+jh,o+(j+1)h)[o + jh, o + (j+1)h), it estimates density as f^(x)=cj/(nh)\hat{f}(x) = c_j/(nh) if xx is in bin jj and cjc_j observations fall there. Choosing hh balances bias and variance: a large width oversmooths (integrated squared bias of order h2h^2) and a small one leaves noise (variance of order 1/(nh)1/(nh)), and Scott’s (h=3.49 s n−1/3h = 3.49\,s\,n^{-1/3}) and Freedman-Diaconis’ (h=2 IQR n−1/3h = 2\,\mathrm{IQR}\,n^{-1/3}) rules arise from minimizing integrated squared error under mild assumptions (n−1/3n^{-1/3} comes from equating the orders). They are starting rules, not guarantees about shape. The ECDF, by contrast, is the empirical distribution itself: it has no parameters.

InteractiveHistogram versus ECDF
Histogram (density) with data marks
ECDF of the same sample: no widths or origins
0.250.50.751
Number of modes by width hh (horizontal) and origin as a fraction of hh (vertical)
h = 0.15, origin 0.00: 12 modesh = 0.15, origin 0.13: 13 modesh = 0.15, origin 0.25: 11 modesh = 0.15, origin 0.38: 11 modesh = 0.15, origin 0.50: 11 modesh = 0.15, origin 0.63: 11 modesh = 0.15, origin 0.75: 12 modesh = 0.15, origin 0.88: 14 modesh = 0.30, origin 0.00: 5 modesh = 0.30, origin 0.13: 5 modesh = 0.30, origin 0.25: 5 modesh = 0.30, origin 0.38: 6 modesh = 0.30, origin 0.50: 5 modesh = 0.30, origin 0.63: 6 modesh = 0.30, origin 0.75: 6 modesh = 0.30, origin 0.88: 4 modesh = 0.45, origin 0.00: 3 modesh = 0.45, origin 0.13: 4 modesh = 0.45, origin 0.25: 3 modesh = 0.45, origin 0.38: 3 modesh = 0.45, origin 0.50: 2 modesh = 0.45, origin 0.63: 3 modesh = 0.45, origin 0.75: 3 modesh = 0.45, origin 0.88: 3 modesh = 0.60, origin 0.00: 2 modesh = 0.60, origin 0.13: 2 modesh = 0.60, origin 0.25: 2 modesh = 0.60, origin 0.38: 2 modesh = 0.60, origin 0.50: 3 modesh = 0.60, origin 0.63: 2 modesh = 0.60, origin 0.75: 2 modesh = 0.60, origin 0.88: 2 modesh = 0.75, origin 0.00: 1 modesh = 0.75, origin 0.13: 2 modesh = 0.75, origin 0.25: 2 modesh = 0.75, origin 0.38: 2 modesh = 0.75, origin 0.50: 2 modesh = 0.75, origin 0.63: 2 modesh = 0.75, origin 0.75: 2 modesh = 0.75, origin 0.88: 1 modesh = 0.90, origin 0.00: 1 modesh = 0.90, origin 0.13: 1 modesh = 0.90, origin 0.25: 2 modesh = 0.90, origin 0.38: 2 modesh = 0.90, origin 0.50: 2 modesh = 0.90, origin 0.63: 2 modesh = 0.90, origin 0.75: 2 modesh = 0.90, origin 0.88: 2 modesh = 1.05, origin 0.00: 1 modesh = 1.05, origin 0.13: 1 modesh = 1.05, origin 0.25: 1 modesh = 1.05, origin 0.38: 2 modesh = 1.05, origin 0.50: 2 modesh = 1.05, origin 0.63: 2 modesh = 1.05, origin 0.75: 2 modesh = 1.05, origin 0.88: 2 modesh = 1.20, origin 0.00: 1 modesh = 1.20, origin 0.13: 1 modesh = 1.20, origin 0.25: 1 modesh = 1.20, origin 0.38: 1 modesh = 1.20, origin 0.50: 1 modesh = 1.20, origin 0.63: 1 modesh = 1.20, origin 0.75: 1 modesh = 1.20, origin 0.88: 1 modesh = 1.35, origin 0.00: 1 modesh = 1.35, origin 0.13: 1 modesh = 1.35, origin 0.25: 1 modesh = 1.35, origin 0.38: 1 modesh = 1.35, origin 0.50: 1 modesh = 1.35, origin 0.63: 1 modesh = 1.35, origin 0.75: 1 modesh = 1.35, origin 0.88: 1 modesh = 1.50, origin 0.00: 1 modesh = 1.50, origin 0.13: 1 modesh = 1.50, origin 0.25: 1 modesh = 1.50, origin 0.38: 1 modesh = 1.50, origin 0.50: 1 modesh = 1.50, origin 0.63: 1 modesh = 1.50, origin 0.75: 1 modesh = 1.50, origin 0.88: 1 modesh = 1.65, origin 0.00: 1 modesh = 1.65, origin 0.13: 1 modesh = 1.65, origin 0.25: 1 modesh = 1.65, origin 0.38: 1 modesh = 1.65, origin 0.50: 1 modesh = 1.65, origin 0.63: 1 modesh = 1.65, origin 0.75: 1 modesh = 1.65, origin 0.88: 1 modesh = 1.80, origin 0.00: 1 modesh = 1.80, origin 0.13: 1 modesh = 1.80, origin 0.25: 1 modesh = 1.80, origin 0.38: 1 modesh = 1.80, origin 0.50: 1 modesh = 1.80, origin 0.63: 1 modesh = 1.80, origin 0.75: 1 modesh = 1.80, origin 0.88: 1 modesh = 1.95, origin 0.00: 1 modesh = 1.95, origin 0.13: 1 modesh = 1.95, origin 0.25: 1 modesh = 1.95, origin 0.38: 1 modesh = 1.95, origin 0.50: 1 modesh = 1.95, origin 0.63: 1 modesh = 1.95, origin 0.75: 1 modesh = 1.95, origin 0.88: 1 modesh = 2.10, origin 0.00: 1 modesh = 2.10, origin 0.13: 1 modesh = 2.10, origin 0.25: 1 modesh = 2.10, origin 0.38: 1 modesh = 2.10, origin 0.50: 1 modesh = 2.10, origin 0.63: 1 modesh = 2.10, origin 0.75: 1 modesh = 2.10, origin 0.88: 1 modesh = 2.25, origin 0.00: 1 modesh = 2.25, origin 0.13: 1 modesh = 2.25, origin 0.25: 1 modesh = 2.25, origin 0.38: 1 modesh = 2.25, origin 0.50: 1 modesh = 2.25, origin 0.63: 1 modesh = 2.25, origin 0.75: 1 modesh = 2.25, origin 0.88: 1 modesh = 2.40, origin 0.00: 1 modesh = 2.40, origin 0.13: 1 modesh = 2.40, origin 0.25: 1 modesh = 2.40, origin 0.38: 1 modesh = 2.40, origin 0.50: 1 modesh = 2.40, origin 0.63: 1 modesh = 2.40, origin 0.75: 1 modesh = 2.40, origin 0.88: 1 modesh = 2.55, origin 0.00: 1 modesh = 2.55, origin 0.13: 1 modesh = 2.55, origin 0.25: 1 modesh = 2.55, origin 0.38: 1 modesh = 2.55, origin 0.50: 1 modesh = 2.55, origin 0.63: 1 modesh = 2.55, origin 0.75: 1 modesh = 2.55, origin 0.88: 1 modesh = 2.70, origin 0.00: 1 modesh = 2.70, origin 0.13: 1 modesh = 2.70, origin 0.25: 1 modesh = 2.70, origin 0.38: 1 modesh = 2.70, origin 0.50: 1 modesh = 2.70, origin 0.63: 1 modesh = 2.70, origin 0.75: 1 modesh = 2.70, origin 0.88: 1 modesh = 2.85, origin 0.00: 1 modesh = 2.85, origin 0.13: 1 modesh = 2.85, origin 0.25: 1 modesh = 2.85, origin 0.38: 1 modesh = 2.85, origin 0.50: 1 modesh = 2.85, origin 0.63: 1 modesh = 2.85, origin 0.75: 1 modesh = 2.85, origin 0.88: 1 modesh = 3.00, origin 0.00: 1 modesh = 3.00, origin 0.13: 1 modesh = 3.00, origin 0.25: 1 modesh = 3.00, origin 0.38: 1 modesh = 3.00, origin 0.50: 1 modesh = 3.00, origin 0.63: 1 modesh = 3.00, origin 0.75: 1 modesh = 3.00, origin 0.88: 1 modes
  • sample A (ECDF and bars)
  • map: 1 mode
  • 2
  • 3
  • 4 or more
0.75
0.25
0.90
Histogram modes2
Quantile Q(0.90)Q(0.90), inverse ECDF1.49
Quantile with linear interpolation1.50
With h=0.75h = 0.75 and origin 0.25hh, the histogram shows 2 modes. The data are unchanged: so is the ECDF.
The sample has 60 observations from a mixture of two Gaussians. Move bin width and origin: the histogram changes from one to three or more modes (or pure noise with very narrow bins), while the ECDF below is unchanged. The lower map counts modes for all width and origin combinations; click a cell to jump to it. 'Show true density' reveals what is really there. Move level pp to read a quantile as the point where the ECDF crosses pp. Add a second sample B and shift it: the maximum vertical distance between the two ECDFs is the Kolmogorov-Smirnov statistic.

The ECDF also lets us compare two samples without choosing a bin width. The Kolmogorov-Smirnov distance between FnF_n and the ECDF GmG_m of another sample is Dn,m=sup⁡x∣Fn(x)−Gm(x)∣D_{n,m} = \sup_x \abs{F_n(x) - G_m(x)}, the largest vertical distance, shown as a segment in the figure. If both samples come from the same continuous distribution, nm/(n+m) Dn,m\sqrt{nm/(n+m)}\,D_{n,m} asymptotically has the Kolmogorov distribution and exceeds 1.3581.358 with probability 5%5 \%. Formalizing this is the job of nonparametric tests. For now keep the visual idea: two distributions differ where their ECDFs separate, and the ECDF shows it without choosing anything.

Robustness: sensitivity curve and breakdown point

In the first figure, a single outlier in set III changed the line. How much damage can one observation do to a summary? And how many corrupted observations can it withstand before giving an arbitrarily bad number? These are different questions, and the second has a clean answer.

This is a worst case: an adversary chooses which observations to corrupt and their values. It is calculated by a counting argument.

Proof

The n−kn - k clean observations have finite minimum and maximum. At most kk corrupted observations can lie below the clean minimum, so if j≥k+1j \ge k + 1, x(j)x_{(j)} stays above it; likewise at most kk can lie above the clean maximum, and if j≤n−kj \le n - k, x(j)x_{(j)} stays below it. This bounds it. If j≤kj \le k, the adversary places kk observations at −∞-\infty and x(j)x_{(j)} is one of them; if j≥n−k+1j \ge n - k + 1, it places them at +∞+\infty. (1): one observation at tt changes the mean by (t−xi)/n(t - x_i)/n, unbounded. (2): for odd nn, the median is x((n+1)/2)x_{((n+1)/2)}, bounded if k+1≤(n+1)/2k + 1 \le (n+1)/2, or k≤(n−1)/2k \le (n-1)/2; it breaks with k=(n+1)/2k = (n+1)/2. For even nn it is half the sum of x(n/2)x_{(n/2)} and x(n/2+1)x_{(n/2+1)}, and breaking either suffices: k=n/2k = n/2. (3): the trimmed mean averages x(g+1),…,x(n−g)x_{(g+1)}, \dots, x_{(n-g)}; the first is bounded if g+1≥k+1g + 1 \ge k + 1, and the last if n−g≤n−kn - g \le n - k, both true for k≤gk \le g and failing at k=g+1k = g + 1.

∎

The same argument gives any quantile’s breakdown point: Q(p)Q(p) breaks with fraction min⁡(p,1−p)\min(p, 1-p). The p99 breakdown point is 1 %1\,\%, which is its function rather than a defect: it should see the tail. Robustness is always relative to what you want to measure.

InteractiveDrag an outlier and see what breaks
Data and summaries (kk contaminated observations in red)
mean ± smedian ± scaled MADt = 1000 →
Shift of each summary versus kk (horizontal), in log⁡10(1+∣T−T0∣/s0)\log_{10}(1 + \abs{T - T_0}/s_0) (vertical)
  • mean (breaks at k=1k = 1)
  • 10 % trimmed mean (k=3k = 3)
  • median (k=10k = 10)
3 of 20 (15 %)
1000
Mean (clean 49.7)192.8
Median (clean 50.9)52.8
10 % trimmed mean (clean 49.8)111.2
Standard deviation ss (clean 7.4)347.9
Scaled MAD (clean 8.8)10.0
With k=3k = 3: the mean is shifted, the trimmed mean shifted, and the median unchanged.
There are 20 observations; kk are replaced by the same value tt (red points). Above: data, mean (orange), median (blue), and 10% trimmed mean (teal), plus 'mean ± s' and 'median ± scaled MAD' intervals. Drag the upper red point or use the tt slider to reach 10⁶. Below: each summary's displacement as a function of kk (log scale, fixed tt): mean jumps at k=1k = 1, trimmed mean at k=3k = 3, and median only at k=10k = 10, half the sample. Why does the median rise a little before breaking? What happens to ss and MAD?

Two nuances the figure teaches. First, before breaking, the median does move: with k<n/2k < n/2, contaminant value does not matter (whether tt is 100100 or 10610^6, provided it exceeds every clean observation), but the central statistic changes rank and the median ends up a neighboring clean observation. Second, a summary not breaking does not mean greater precision on clean data: robustness costs efficiency, measured on Gaussian data by asymptotic variance relative to the mean’s.

Location estimatorBreakdown pointAsymptotic efficiency (normal)
mean0011
5% trimmed mean0.050.050.9740.974
10% trimmed mean0.100.100.9430.943
20% trimmed mean0.200.200.8740.874
median0.500.502/π≈0.6372/\pi \approx 0.637

Trimming 10 %10\,\% from each side costs 6 %6\,\% efficiency on perfectly Gaussian data and buys a 10 %10\,\% breakdown point. This is inexpensive insurance, so the trimmed mean is the most common compromise. The winsorized mean replaces extremes with the cutoff quantile instead of discarding them and has the same breakdown point. M-estimators such as Huber’s continuously occupy the space between mean and median (lesson 8).

The sensitivity curve

The breakdown point measures the global worst case. The sensitivity curve measures the local effect of one new observation at position xx:

SCn(x)=n [ Tn(x1,…,xn−1,x)−Tn−1(x1,…,xn−1) ].\mathrm{SC}_n(x) = n\,\big[\,T_n(x_1, \dots, x_{n-1}, x) - T_{n-1}(x_1, \dots, x_{n-1})\,\big].

For the mean, SCn(x)=x−xˉn−1\mathrm{SC}_n(x) = x - \bar{x}_{n-1}: an unbounded line, another view of breakdown with k=1k = 1. For the median the curve is bounded: a distant observation weighs like a slightly farther one, and all that matters is which side of the median it falls on. The limit of this curve as n→∞n \to \infty is Hampel’s influence function (mean: x−μx - \mu; median: sign⁡(x−m)/(2f(m))\operatorname{sign}(x - m)/(2f(m))).

Association: covariance, Pearson, Spearman, and Kendall

With two variables, the best-known association summary is correlation. Given pairs (xi,yi)(x_i, y_i), sample covariance is sxy=1n−1∑i(xi−xˉ)(yi−yˉ)s_{xy} = \frac{1}{n-1}\sum_i (x_i - \bar{x})(y_i - \bar{y}) and the Pearson coefficient,

r=sxysxsy=∑i(xi−xˉ)(yi−yˉ)∑i(xi−xˉ)2∑i(yi−yˉ)2,r = \frac{s_{xy}}{s_x s_y} = \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}},

is the sample analog of population covariance and correlation. It has a geometric interpretation: centering the two data vectors, x~=x−xˉ1\tilde{\vb{x}} = \vb{x} - \bar{x}\vb{1} and y~=y−yˉ1\tilde{\vb{y}} = \vb{y} - \bar{y}\vb{1}, gives r=⟨x~,y~⟩/(∥x~∥∥y~∥)r = \inner{\tilde{\vb{x}}}{\tilde{\vb{y}}}/(\norm{\tilde{\vb{x}}}\norm{\tilde{\vb{y}}}), the cosine of the angle between them in Rn\R^n. By Cauchy-Schwarz, ∣r∣≤1\abs{r} \le 1, with equality if and only if points lie exactly on a line.

The least-squares line y^=a+bx\hat{y} = a + bx has slope b=sxy/sx2=r sy/sxb = s_{xy}/s_x^2 = r\,s_y/s_x, leaving squared residual ∑i(yi−y^i)2=(1−r2)∑i(yi−yˉ)2\sum_i (y_i - \hat{y}_i)^2 = (1 - r^2)\sum_i (y_i - \bar{y})^2. Thus r2r^2 is the fraction of yy variation explained by a line in xx. That is why each Anscombe set, with r2=0.667r^2 = 0.667, looks equally “explained”: rr is a linear summary.

Pearson sees only linear association. If XX is symmetric and Y=X2Y = X^2, there is perfect dependence and rr is (almost) zero: zero correlation does not imply independence. It has unbounded influence: one distant point controls rr, as it controls xˉ\bar{x}. Two alternatives examine only order.

Both equal 11 if and only if yy is a strictly increasing function of xx (and −1-1 if decreasing), and share the key property:

Proof

Strictly increasing ff means xi<xj  ⟺  f(xi)<f(xj)x_i < x_j \iff f(x_i) < f(x_j) and xi=xj  ⟺  f(xi)=f(xj)x_i = x_j \iff f(x_i) = f(x_j): it preserves order and ties, so ranks of f(x)f(\vb{x}) equal those of x\vb{x}, and each pair is concordant, discordant, or tied exactly when it was before. Likewise for gg. Spearman and Kendall depend only on ranks and signs of differences.

∎

Pearson does not share this property. For a standard Gaussian pair with correlation ρ=0.8\rho = 0.8, the three are approximately: Pearson 0.80.8, Spearman 6πarcsin⁡(ρ/2)=0.786\frac{6}{\pi}\arcsin(\rho/2) = 0.786 and Kendall 2πarcsin⁡ρ=0.590\frac{2}{\pi}\arcsin\rho = 0.590. Passing both variables through e(⋅)e^{(\cdot)} drops Pearson to (eρ−1)/(e−1)=0.713(e^{\rho} - 1)/(e - 1) = 0.713 while Spearman and Kendall remain 0.7860.786 and 0.5900.590. This is more than curiosity: at population level, Spearman and Kendall depend only on the part of dependence excluding marginal distributions, the copula, and are the basic example of rank dependence measures in that context.

InteractivePearson versus ranks
Data: xx versus transformed (standardized) yy
Ranks: what Spearman and Kendall see
Coefficients (dashed marks show untransformed values without an outlier)
Pearson r0.638Spearman ρ0.857Kendall τ0.701
  • data
  • least-squares line (Pearson)
1.5
Pearson rr0.638
Spearman ρS\rho_S0.857
Kendall τb\tau_b0.701
Ranks have not changed: Spearman and Kendall remain at 0.857 and 0.701. Pearson changed from 0.876 to 0.638.
Thirty points with an increasing relationship and noise. Choose a strictly increasing transformation of yy: the left plot deforms and Pearson changes, but the rank plot on the right, and with it Spearman and Kendall, remains exactly the same (the dashed mark on each bar is its untransformed, outlier-free value). Then enable the outlier and drag it: where does Pearson feel it most? And Kendall? Increase noise until the relationship is weak and repeat.

Two cautions about what rank coefficients also do not do. They detect monotone association: with Y=X2Y = X^2 on symmetric data, all three coefficients are near zero. They are not immune to outliers, only less sensitive: one extreme observation changes others’ ranks by at most one, so its influence is bounded, unlike Pearson’s. Kendall also has a direct probabilistic interpretation: τ=2P(concordant pair)−1\tau = 2\Pr(\text{concordant pair}) - 1.

Look at the data: exploratory analysis

John Tukey (1977) argued that before confirming anything one must explore: look at data in many ways without a specific hypothesis to discover which questions deserve asking. This is exploratory data analysis (EDA): a craft and workflow, not a theorem.

The two graphical tools not yet seen are the box plot and logarithmic scale.

Tukey’s box plot draws a box from Q(0.25)Q(0.25) to Q(0.75)Q(0.75) with a line at the median, and whiskers to the most distant observation within fences Q(0.25)−1.5 IQRQ(0.25) - 1.5\,\mathrm{IQR} and Q(0.75)+1.5 IQRQ(0.75) + 1.5\,\mathrm{IQR}. Everything outside is drawn as a point. In a normal distribution, fences lie 2.698 σ2.698\,\sigma from the mean and mark 0.70 %0.70\,\% of observations. This is not an outlier test: in a heavy-tailed variable it marks dozens of points that are not errors. It shows the body’s range and asks for a second look.

A logarithmic scale is the tool for multiplicative data (latencies, incomes, sizes). On a linear scale extreme values crush the rest against one side; on a log scale equal distances are equal ratios. Two signs it is needed: mean far exceeds median, and maximum is hundreds of times median. A lognormal variable becomes Gaussian on a log scale, and its ECDF with logarithmic xx axis is a normal sigmoid: a visual check.

Implementation from scratch

First, descriptive statistics without libraries: one-pass mean and variance, quantiles with Hyndman and Fan conventions, scaled MAD, trimmed mean, ECDF, and the three correlations. Each function includes a line defining it.

[ ]Minimal descriptive statistics libraryBrowser
import numpy as np

def welford(x):
    """Una pasada: n, media y M2 = sum (x_i - media)^2, sin restar números casi iguales."""
    n, mu, m2 = 0, 0.0, 0.0
    for v in x:
        n += 1
        delta = v - mu
        mu += delta / n
        m2 += delta * (v - mu)
    return n, mu, m2

def varianza(x, ddof=1):
    n, _, m2 = welford(x)
    return m2 / (n - ddof)

_AB = {4: (0, 1), 5: (.5, .5), 6: (0, 0), 7: (1, 1), 8: (1 / 3, 1 / 3), 9: (3 / 8, 3 / 8)}

def cuantil(x, p, tipo=7):
    """Cuantil de Hyndman y Fan: tipo 1 sin interpolar, tipos 4 a 9 con posicion h = (n+1-a-b)p + a."""
    s = np.sort(np.asarray(x, dtype=float)); n = len(s)
    if tipo == 1:
        return s[max(int(np.ceil(n * p - 1e-12)), 1) - 1]
    a, b = _AB[tipo]
    h = min(max((n + 1 - a - b) * p + a, 1), n)          # posicion desde 1, acotada a [1, n]
    lo = int(np.floor(h)); hi = min(lo + 1, n)
    return s[lo - 1] + (h - lo) * (s[hi - 1] - s[lo - 1])

def mad_escalada(x):
    x = np.asarray(x, dtype=float)
    return 1.482602218505602 * np.median(np.abs(x - np.median(x)))

def media_recortada(x, alfa):
    s = np.sort(np.asarray(x, dtype=float)); g = int(np.floor(alfa * len(s) + 1e-9))
    return s[g:len(s) - g].mean()

def ecdf(x):
    s = np.sort(np.asarray(x, dtype=float))
    return lambda t: np.searchsorted(s, t, side="right") / len(s)

def rangos(x):
    """Rangos 1..n con la media de los rangos en los empates."""
    x = np.asarray(x, dtype=float); orden = np.argsort(x, kind="mergesort")
    r = np.empty(len(x)); i = 0
    while i < len(x):
        j = i
        while j + 1 < len(x) and x[orden[j + 1]] == x[orden[i]]:
            j += 1
        r[orden[i:j + 1]] = (i + j) / 2 + 1
        i = j + 1
    return r

def pearson(x, y):
    x = np.asarray(x, dtype=float) - np.mean(x); y = np.asarray(y, dtype=float) - np.mean(y)
    return (x @ y) / np.sqrt((x @ x) * (y @ y))

def spearman(x, y):
    return pearson(rangos(x), rangos(y))

def kendall(x, y):
    """tau_b: (C - D) / sqrt((pares sin empate en x) * (pares sin empate en y))."""
    x = np.asarray(x, dtype=float); y = np.asarray(y, dtype=float)
    sx = np.sign(x[:, None] - x[None, :]); sy = np.sign(y[:, None] - y[None, :])
    iu = np.triu_indices(len(x), 1)
    cd = np.sum(sx[iu] * sy[iu])                         # C - D
    nx = float(np.count_nonzero(sx[iu])); ny = float(np.count_nonzero(sy[iu]))   # en float: ver la nota
    return cd / np.sqrt(nx * ny)

# comprobacion con la muestra del texto
s = [2, 3, 5, 7, 11, 13, 17, 19]
print("cuantiles p = 0.9:", {t: round(float(cuantil(s, 0.9, t)), 3) for t in (1, 4, 5, 6, 7, 8, 9)})
print("varianza:", varianza(s), "  numpy:", np.var(s, ddof=1))
F = ecdf(s)
print("ECDF en 10:", F(10), " en 2:", F(2), " en 1:", F(1))

The 0.90.9 quantile values match the table (type 7’s 17.617.6 is NumPy’s default), and the ECDF returns 0.50.5 at 1010 because four of the eight observations are at most that value.

Now the important part: variance. A classic failure is computing E[X2]−E[X]2\E[X^2] - \E[X]^2 in floating point. With huge mean and small deviation, the two quantities are nearly equal and their difference loses all digits (catastrophic cancellation).

Welford’s method does not subtract nearly equal numbers: it updates the mean and centered sum of squares with one more observation. Derive it as follows. With μk\mu_k the mean of the first kk observations, μk=μk−1+(xk−μk−1)/k\mu_k = \mu_{k-1} + (x_k - \mu_{k-1})/k. For centered sum of squares Mk=∑i≤k(xi−μk)2M_k = \sum_{i \le k}(x_i - \mu_k)^2, using the variance identity with the previous mean,

Mk=Mk−1+(xk−μk−1)(xk−μk).M_k = M_{k-1} + (x_k - \mu_{k-1})(x_k - \mu_k).

(Check it this way: ∑i≤k(xi−a)2=Mk+k(μk−a)2\sum_{i \le k}(x_i - a)^2 = M_k + k(\mu_k - a)^2 for any aa; with a=μk−1a = \mu_{k-1} and separating the final term, Mk=Mk−1+(xk−μk−1)2−k(μk−μk−1)2M_k = M_{k-1} + (x_k - \mu_{k-1})^2 - k(\mu_k - \mu_{k-1})^2. Since μk−μk−1=(xk−μk−1)/k\mu_k - \mu_{k-1} = (x_k - \mu_{k-1})/k, this is Mk−1+δ2(1−1/k)M_{k-1} + \delta^2(1 - 1/k) with δ=xk−μk−1\delta = x_k - \mu_{k-1}, and (xk−μk−1)(xk−μk)=δ (δ−δ/k)(x_k - \mu_{k-1})(x_k - \mu_k) = \delta\,(\delta - \delta/k) is the same.) Each term is a product of two numbers on the scale of spread, not mean. This is the Welford recurrence, and its version for combining two groups (Chan et al.) is used by libraries to calculate variance in blocks or in parallel.

[ ]Catastrophic cancellation versus WelfordBrowser
import numpy as np

rng = np.random.default_rng(0)
for centro in (0.0, 1e6, 1e9):
    x = centro + rng.normal(size=20_000)
    ingenua = np.mean(x ** 2) - np.mean(x) ** 2
    print(f"media {centro:>7.0e}: ingenua = {ingenua:>12.6f}   Welford = {varianza(x, ddof=0):.6f}   np.var = {np.var(x):.6f}")

# el limite de la fórmula ingenua es la resolucion de float64 en x^2
x = 1e9 + rng.normal(size=20_000)
print("espaciado de float64 cerca de x^2 =", np.spacing(1e18), "  frente a la varianza real = 1")

With mean 10910^9, squares are on the order of 101810^{18} and float64 spacing there is 128128: the desired difference, approximately 11, cannot be represented. With mean 10610^6 the naive formula already fails in the fourth digit (1.015261.01526 versus 1.015341.01534), and with mean 10910^9 it returns exactly −128-128: negative variance. Welford and NumPy agree in all three cases. The code exercise asks you to implement and verify Welford.

Second experiment: robustness. With the same library, measure the actual breakdown point rather than merely believing it.

[ ]Measure breakdown pointBrowser
import numpy as np

rng = np.random.default_rng(1)
n = 20
limpia = rng.normal(50, 8, n)
orden = rng.permutation(n)

def contaminar(k, t=1e12):
    x = limpia.copy()
    x[orden[:k]] = t
    return x

resumenes = {
    "media": np.mean,
    "mediana": np.median,
    "recortada 10 %": lambda x: media_recortada(x, 0.10),
    "desv. típica": lambda x: np.std(x, ddof=1),
    "MAD escalada": mad_escalada,
}
for nombre, T in resumenes.items():
    base = T(limpia)
    k_rotura = next(k for k in range(n + 1) if abs(T(contaminar(k)) - base) > 1e6)
    print(f"{nombre:15s} se rompe con k = {k_rotura:2d} de {n}  (fraccion {k_rotura / n:.2f})")

It matches the theorem: mean and standard deviation break with k=1k = 1, trimmed mean with k=⌊0.1⋅20⌋+1=3k = \lfloor 0.1 \cdot 20 \rfloor + 1 = 3, median and MAD with k=10k = 10. And correlations, using the functions above against scipy.stats:

[ ]Rank correlations and monotone transformationsBrowser
import numpy as np
from scipy import stats

rng = np.random.default_rng(2)
rho = 0.8
Z = rng.multivariate_normal([0, 0], [[1, rho], [rho, 1]], size=1500)
x, y = Z[:, 0], Z[:, 1]

def tres(x, y):
    return pearson(x, y), spearman(x, y), kendall(x, y)

print("datos gaussianos      :", np.round(tres(x, y), 3))
print("tras exp() en ambas   :", np.round(tres(np.exp(x), np.exp(y)), 3))
print("teoría (rho = 0.8)    :", round(rho, 3), round(6 / np.pi * np.arcsin(rho / 2), 3), round(2 / np.pi * np.arcsin(rho), 3),
      "  Pearson de e^X, e^Y:", round((np.exp(rho) - 1) / (np.e - 1), 3))

# nuestras funciones frente a scipy.stats
print("scipy                 :", np.round([stats.pearsonr(x, y)[0], stats.spearmanr(x, y)[0], stats.kendalltau(x, y)[0]], 3))

# con empates, tau_b y los rangos promedio
a = np.array([1, 2, 2, 3, 4, 4, 4, 5.]); b = np.array([2, 1, 3, 3, 5, 4, 5, 6.])
print("con empates:", round(kendall(a, b), 6), round(stats.kendalltau(a, b)[0], 6), "|", round(spearman(a, b), 6), round(stats.spearmanr(a, b)[0], 6))

# el atípico: un solo punto cambia Pearson mucho más que los rangos
x2 = np.append(x[:100], 0.0); y2 = np.append(y[:100], 12.0)
print("100 puntos         :", np.round(tres(x[:100], y[:100]), 3))
print("más un atípico (0, 12):", np.round(tres(x2, y2), 3))

Results agree with theory: Spearman and Kendall are unchanged with and without exp⁡\exp, Pearson falls from 0.810.81 to 0.730.73 (population value is 0.7130.713; with 15001500 points there is sampling noise), and our functions agree with scipy, even with ties. Outlier (0,12)(0, 12) added to one hundred points shows the difference in sensitivity: Pearson falls from 0.7780.778 to 0.4920.492, while Spearman goes from 0.7800.780 to 0.7700.770 and Kendall from 0.5930.593 to 0.5830.583.

The professional version

All this already exists and is what you should use. The equivalence table:

CalculationNumPypandasscipy.stats
mean, variancenp.mean, np.var(ddof=1).mean(), .var()tvar
median, quantilesnp.median, np.quantile(method=).median(), .quantile(q, interpolation=)mstats.mquantiles
trimmed meantrim_mean(x, 0.1)
scaled MADmedian_abs_deviation(x, scale="normal")
skewness, kurtosis.skew(), .kurt()skew, kurtosis
ECDFstats.ecdf(x)
correlationsnp.corrcoef.corr(method="pearson" | "spearman" | "kendall")pearsonr, spearmanr, kendalltau
[ ]The same analysis with pandas and scipy.statsBrowser
import numpy as np, pandas as pd
from scipy import stats

rng = np.random.default_rng(3)
x = rng.normal(50, 8, 200)
x[:6] = [400, 380, 500, 420, 900, 650]                 # 3 % de errores de captura
df = pd.DataFrame({"x": x, "y": 2 * x + rng.normal(0, 20, 200)})

print(df["x"].describe().round(2).to_string())
print()
print("media  / mediana        :", round(df.x.mean(), 2), "/", round(df.x.median(), 2))
print("sd     / MAD escalada   :", round(df.x.std(), 2), "/", round(stats.median_abs_deviation(df.x, scale="normal"), 2),
      "  (a mano:", round(float(mad_escalada(df.x)), 2), ")")
print("recortada 10 %          :", round(stats.trim_mean(df.x, 0.1), 2), " (a mano:", round(float(media_recortada(df.x, 0.1)), 2), ")")
print("asimetría / curtosis    :", round(stats.skew(df.x), 2), "/", round(stats.kurtosis(df.x), 2))
print("pandas: .skew() / .kurt():", round(df.x.skew(), 2), "/", round(df.x.kurt(), 2), "  (con correccion de sesgo: no coinciden con scipy)")
print("p95 con 3 convenciones  :", [round(float(df.x.quantile(0.95, interpolation=m)), 2) for m in ("linear", "lower", "midpoint")])
print()
print(df.corr(method="pearson").round(3).iloc[0, 1], df.corr(method="spearman").round(3).iloc[0, 1], df.corr(method="kendall").round(3).iloc[0, 1])
print("sin los 6 errores        :", df.iloc[6:].corr(method="pearson").round(3).iloc[0, 1], df.iloc[6:].corr(method="spearman").round(3).iloc[0, 1], df.iloc[6:].corr(method="kendall").round(3).iloc[0, 1])

Six entry errors (3 %3\,\% of data) suffice to show the above: mean rises from 50.950.9 (median and trimmed mean) to 65.265.2, standard deviation is 90.290.2 versus scaled MAD 8.08.0, and excess kurtosis is 48.648.6. Note correlations too: since yy was generated as 2x2x plus noise, the six errors drag their yy with them and form a high-leverage group aligned with the line. Pearson is 0.9940.994 with them and 0.6450.645 without, while Spearman goes from 0.6610.661 to 0.6290.629 and Kendall from 0.4780.478 to 0.4460.446: a summary depending on how many errors exist is not a summary of the relationship.

Three things to watch. ddof: NumPy divides by nn, pandas by n−1n - 1. Skewness and kurtosis: scipy.stats defaults to g1g_1 and g2g_2 (with nn), while pandas applies bias corrections and gives somewhat different values, especially with small nn. Quantiles: NumPy, pandas, and R agree on type 7; other programs do not. When reproducing another tool’s number, check its convention before debugging.

[ ]Anscombe with pandas: rank correlations do distinguish themBrowser
import numpy as np, pandas as pd

x = np.array([10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5.])
y = [[8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68],
     [9.14, 8.14, 8.74, 8.77, 9.26, 8.10, 6.13, 3.10, 9.13, 7.26, 4.74],
     [7.46, 6.77, 12.74, 7.11, 7.81, 8.84, 6.08, 5.39, 8.15, 6.42, 5.73]]
x4 = np.array([8, 8, 8, 8, 8, 8, 8, 19, 8, 8, 8.])
y4 = [6.58, 5.76, 7.71, 8.84, 8.47, 7.04, 5.25, 12.50, 5.56, 7.91, 6.89]
conjuntos = {"I": (x, y[0]), "II": (x, y[1]), "III": (x, y[2]), "IV": (x4, y4)}

filas = []
for nombre, (xx, yy) in conjuntos.items():
    d = pd.DataFrame({"x": xx, "y": yy})
    filas.append({"conjunto": nombre, "media x": d.x.mean(), "var y": d.y.var(), "pearson": d.corr().iloc[0, 1],
                  "spearman": d.corr(method="spearman").iloc[0, 1], "kendall": d.corr(method="kendall").iloc[0, 1]})
print(pd.DataFrame(filas).round(3).to_string(index=False))

Pearson says the same for all four; Spearman and Kendall separate them (III, nearly a line with one outlier, has ρS\rho_S near 11; IV, with one leverage point, drops). Good practice: calculate all three and distrust discrepancies.

Application: heavy-tailed latency

A realistic case bringing everything together. Service latencies are positive, multiplicative, and heavy-tailed: mostly fast requests, a slow fraction, and occasional timeouts. Generate 20,000 synthetic latencies with that structure and explore them.

[ ]Explore heavy-tailed latenciesBrowser
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(7)
n = 20_000
rapida = rng.lognormal(np.log(80), 0.45, n)                  # ms: el grueso del tráfico
lenta = rng.lognormal(np.log(600), 0.6, n)                   # 4 % de peticiones lentas (caché fría, reintentos)
lat = np.where(rng.random(n) < 0.04, lenta, rapida)
lat = np.where(rng.random(n) < 0.002, 30_000.0, lat)         # 0.2 % de tiempos de espera agotados

p50, p95, p99, p999 = (float(cuantil(lat, p)) for p in (0.50, 0.95, 0.99, 0.999))
print(f"media {lat.mean():8.1f} ms   mediana {np.median(lat):7.1f} ms   recortada 10 % {media_recortada(lat, .1):7.1f} ms")
print(f"desv. típica {lat.std(ddof=1):8.1f} ms   MAD escalada {mad_escalada(lat):7.1f} ms")
print(f"p50 {p50:.1f}   p95 {p95:.1f}   p99 {p99:.1f}   p99.9 {p999:.1f}  (ms)")
print(f"asimetría {((lat - lat.mean()) ** 3).mean() / lat.std() ** 3:.1f}   mayor / mediana = {lat.max() / np.median(lat):.0f}")
print(f"peticiones con >1 s: {np.mean(lat > 1000):.2%}   media del 1 % más lento: {np.sort(lat)[-n // 100:].mean():.0f} ms")

fig, ax = plt.subplots(1, 2, figsize=(9, 3.4))
s = np.sort(lat)
ax[0].plot(s, np.arange(1, n + 1) / n, drawstyle="steps-post")
ax[0].set_xlabel("latencia (ms), escala lineal"); ax[0].set_ylabel("ECDF"); ax[0].set_title("sin mirar la escala")
ax[1].plot(s, np.arange(1, n + 1) / n, drawstyle="steps-post")
ax[1].set_xscale("log")
for q, c in ((p50, "tab:green"), (p95, "tab:orange"), (p99, "tab:red")):
    ax[1].axvline(q, color=c, ls="--", lw=1)
ax[1].set_xlabel("latencia (ms), escala logarítmica"); ax[1].set_title("p50, p95 y p99")
plt.tight_layout(); plt.show()

The diagnosis comes from comparing summaries. The mean (174174 ms) is over twice the median (8282 ms) and describes almost no request: it is pulled by the slow 4 %4\,\% and the 0.2 %0.2\,\% of 3030 s timeouts. Standard deviation (13771377 ms, eight times the mean) is worse, because each timeout contributes 30000230000^2; with skewness 2121 and a maximum 368368 times the median, this is a textbook heavy tail. The median (8282 ms), 10% trimmed mean (8787 ms), and scaled MAD (3737 ms) describe typical behavior well, but deliberately ignore the tail experienced by waiting users. Percentiles tell the full story: p95 =217= 217 ms, p99 =940= 940 ms (0.86 %0.86\,\% of requests exceed the latter), and p99.9 =30000= 30000 ms, the timeout itself, because timeouts (0.2 %0.2\,\%) already exceed the 0.1 %0.1\,\% tail. On a linear-scale ECDF almost all mass sticks to the left and nothing is visible; on a log scale the body, slow-fraction elbow, and final timeout step appear. Which summary misleads depends on the question: for “how long does a typical request take?” the mean misleads and the median helps; for “what happens to the worst-off user?” the median misleads and high percentiles help. The honest answer is the full ECDF.

Common mistakes

Exercises

QuizA mistaken value multiplied by 1000
In sample 12.1, 11.8, 12.4, 12.0, 11.9, 12.3, 12.2, 11.7, 12.5, 12.1, 12.0 (n = 11), an entry error multiplies the fifth value, 11.9, by 1000. Which summaries remain practically unchanged?

More than one answer may be correct.

NumericBreakdown point of a trimmed mean
A mean trimmed by 10% on each side is calculated from n=50n = 50 observations (discarding ⌊0.1n⌋\lfloor 0.1 n \rfloor from each extreme). What is its finite-sample breakdown point k/nk/n? (As n→∞n \to \infty it tends to α=0.1\alpha = 0.1.)
ProofWhich minimizes what?
Prove: For any sample x1,…,xnx_1, \dots, x_n, c↦∑i(xi−c)2c \mapsto \sum_i (x_i - c)^2 is minimized at c=xˉc = \bar{x}, and c↦∑i∣xi−c∣c \mapsto \sum_i \abs{x_i - c} is minimized at the median.
0
Prove each part with the best-fitting argument: algebraic expansion for the first and the derivative of a piecewise-linear function for the second.

Step 1 of 3. For the sum of squares, which identity do you use?

CodeOne-pass variance with Welford
Implement varianza_welford(x, ddof=0), returning data variance in one pass, using Welford’s algorithm (updating mean and centered sum of squares), without storing the data or using np.var or the formula E[X2]−E[X]2\E[X^2] - \E[X]^2. x can be any iterable, including a generator. If there are insufficient data (n - ddof <= 0), return float('nan'). It must agree with np.var on data with mean 10910^9, where the naive formula fails.
def varianza_welford(x, ddof=0):
  """Varianza en una pasada (Welford). x es un iterable; ddof = 0 o 1."""
  x = list(x)                                   # esto no vale: hay que consumir x una sola vez
  n = len(x)
  # tu código: n, media y m2 actualizados dato a dato
  media = sum(x) / n
  m2 = sum(v * v for v in x) / n
  return (m2 - media ** 2) * n / (n - ddof)
Shift+Enter to run
QuizWhich plot is monotone but nonlinear?
For x=1,2,…,20x = 1, 2, \dots, 20, consider four sets of yy. In which is Spearman exactly 1 and Pearson clearly below 1?
NumericA quantile with the default convention
For sample (2,3,5,7,11,13,17,19)(2, 3, 5, 7, 11, 13, 17, 19), calculate quantile p=0.9p = 0.9 using NumPy's default convention (type 7, method='linear').
NumericKendall by hand
For x=(1,2,3,4,5,6,7,8)x = (1, 2, 3, 4, 5, 6, 7, 8) and y=(3,1,2,6,4,8,5,7)y = (3, 1, 2, 6, 4, 8, 5, 7), calculate Kendall's τ\tau. (There are 28 pairs and no ties: count discordant pairs.)
NumericHow much kurtosis fits in ten observations?
What is the maximum possible sample excess kurtosis g2g_2 of a sample of size n=10n = 10? (It is attained with one isolated observation and the other nine equal.)

Summary

Key idea
A summary is a function of data discarding almost all their information, and the right question is never “what is its mean?” but “which summary do I choose, how does it behave when data are contaminated, and what am I missing?”: choose the statistic for the data’s shape, know its breakdown point, and always plot the full distribution.
  • Mean minimizes squared sum and median absolute sum; s2s^2 with divisor n−1n - 1 is unbiased, and scaled MAD (1.4826 MAD1.4826\,\mathrm{MAD}) and IQR/1.349\mathrm{IQR}/1.349 are robust scales consistent with σ\sigma on Gaussian data.
  • Sample skewness and kurtosis are bounded (g2≤n−5+1/(n−1)g_2 \le n - 5 + 1/(n-1)), biased, and highly unstable with heavy tails; do not use them to decide normality.
  • ECDF FnF_n is the parameter-free empirical distribution; it converges uniformly to FF (Glivenko-Cantelli, DKW). Summaries are functionals of FnF_n, quantiles have nine conventions (type 7 in NumPy, pandas, and R), and high percentiles need n≳10/(1−p)n \gtrsim 10/(1-p).
  • A histogram depends on width and origin and can invent or hide modes; the ECDF cannot.
  • Breakdown point: mean 00, trimmed mean α\alpha, median 1/21/2, and quantile Q(p)Q(p) breaks with fraction min⁡(p,1−p)\min(p, 1-p). Robustness costs efficiency (10% trimming: 94% under normality) and is relative to what one wants to measure.
  • Pearson measures linear association and has unbounded influence; Spearman and Kendall measure monotone association and are invariant under increasing transformations. Calculate all three.
  • Look at data before summarizing: Anscombe and the first figure’s clouds share means, variances, and correlation and look nothing alike.