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 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 with the same summaries:
| I | II | III | IV | |
|---|---|---|---|---|
| mean of | 9.0 | 9.0 | 9.0 | 9.0 |
| variance of | 11.0 | 11.0 | 11.0 | 11.0 |
| mean of | 7.50 | 7.50 | 7.50 | 7.50 |
| variance of | 4.127 | 4.128 | 4.123 | 4.123 |
| correlation | 0.816 | 0.816 | 0.816 | 0.817 |
| least-squares line |
An analyst reading only the table concludes these are the same phenomenon. Now look at the data.
The four sets tell four different stories. I is what one imagines from a correlation of : 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, , with one outlier pulling the fit to (without it, ). In IV all 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 coordinates. With points, the set of clouds with the same means, standard deviations, and correlation is a manifold of dimension : almost the whole space remains free. Any fixed-dimensional summary leaves 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 , its order statistics , 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 and skewness does not change at all.
Mean and median as solutions to a problem
The mean and median (the middle value of , 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 ,
which is minimized uniquely at . The minimum is , 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 divisor
The sample variance and standard deviation are
The divisor (Bessel’s correction) is not arbitrary: it makes the estimator unbiased. The reason is that deviations are measured from , fitted to the same data and therefore closer to them than population mean .
Proof
Adding and subtracting and expanding, with ,
Take expectations. The left side is . Since is the mean of independent variables with variance , , and the last term contributes . Thus , and dividing by gives .
∎Two clarifications. Unbiasedness applies to , not : by Jensen’s inequality ( is concave), . With large the divisor barely matters; with dividing by instead of differs by 25%. NumPy defaults to (ddof=0), pandas uses (ddof=1): a classic trap.
Robust scales
The interquartile range and median absolute deviation measure spread without squaring, so an extreme observation barely moves them. To compare them with convert them to the same scale. If , then is the absolute value of a standard normal, whose median is ( is the standard normal CDF). Therefore
The scaled MAD is a consistent estimator of for Gaussian data and numerically comparable to . With outliers, when and scaled MAD differ greatly, something is happening. The price is efficiency: on clean Gaussian data MAD has asymptotic efficiency of 37% relative to (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,
is skewness: positive if the right tail is longer, and for symmetric distributions. is excess kurtosis: the makes it 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 , Student’s with degrees of freedom has , and uniform has . Above all, 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 , because the square of a sum of nonnegative terms contains each term’s square, and . The exact bound is attained with one observation at distance from the mean and the other at distance : then , and thus , giving ; in the same configuration, and . That these values cannot be exceeded is Dalén’s result (1987). A two-line argument gives almost the same. Normalize (so ) and let , attained at . Since , Cauchy-Schwarz gives , that is ; and because the maximum exceeds the mean. Applying the first bound to the other observations, , a convex function of whose maximum on is at an endpoint and equals . Therefore , exceeding the exact bound by only .
∎With , sample kurtosis cannot exceed however contaminated the data. A lognormal with has population excess kurtosis : no sample of fewer than observations can even attain that value. This is a bound, not an opinion.
Lessons from the figure:
- Bias is real. Even with normal data, : with , .
- Variance is enormous with heavy tails. The sample’s fourth moment has variance depending on the population eighth moment. With a of 5 degrees of freedom the fourth moment exists and almost surely, but the eighth is infinite: there is no central limit theorem at rate , and between and the 10%-90% band barely narrows.
- Some distributions have no kurtosis. A with 3 degrees of freedom has finite variance but infinite fourth moment: grows with 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 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 , then for each fixed , so and : an unbiased estimator whose uncertainty is largest at the median and vanishes in the tails. More strongly, the Glivenko-Cantelli theorem says almost surely, and the DKW inequality gives the rate: . 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 , variance is (with divisor ), and a quantile is the inverse of . Replacing unknown distribution by in a formula is called the plug-in principle, revisited with the bootstrap (lesson 16).
Quantiles and their conventions
The population quantile is . The empirical quantile, , 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)
with bounded to and different pairs . Those that matter in practice:
| Type | method= in NumPy | Use | |
|---|---|---|---|
| 1 | no interpolation | inverted_cdf | theoretical definition, |
| 6 | weibull | ; Minitab, SPSS | |
| 7 | linear | default in NumPy, pandas, and R | |
| 8 | median_unbiased | recommended by Hyndman and Fan |
For sample and , type 1 gives , type 6 gives , type 7 gives , and type 8 gives : the same sample, three different results. With large 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 has asymptotic variance , where is density: density is small in the tails and error grows. There is also a combinatorial limit. For to be more than the maximum, is needed: if , 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 .
Histogram versus ECDF
The histogram is the usual mental image of a distribution and has two analyst-chosen parameters: bin width and origin. With bins , it estimates density as if is in bin and observations fall there. Choosing balances bias and variance: a large width oversmooths (integrated squared bias of order ) and a small one leaves noise (variance of order ), and Scott’s () and Freedman-Diaconis’ () rules arise from minimizing integrated squared error under mild assumptions ( 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.
The ECDF also lets us compare two samples without choosing a bin width. The Kolmogorov-Smirnov distance between and the ECDF of another sample is , the largest vertical distance, shown as a segment in the figure. If both samples come from the same continuous distribution, asymptotically has the Kolmogorov distribution and exceeds with probability . 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 clean observations have finite minimum and maximum. At most corrupted observations can lie below the clean minimum, so if , stays above it; likewise at most can lie above the clean maximum, and if , stays below it. This bounds it. If , the adversary places observations at and is one of them; if , it places them at . (1): one observation at changes the mean by , unbounded. (2): for odd , the median is , bounded if , or ; it breaks with . For even it is half the sum of and , and breaking either suffices: . (3): the trimmed mean averages ; the first is bounded if , and the last if , both true for and failing at .
∎The same argument gives any quantile’s breakdown point: breaks with fraction . The p99 breakdown point is , which is its function rather than a defect: it should see the tail. Robustness is always relative to what you want to measure.
Two nuances the figure teaches. First, before breaking, the median does move: with , contaminant value does not matter (whether is or , 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 estimator | Breakdown point | Asymptotic efficiency (normal) |
|---|---|---|
| mean | ||
| 5% trimmed mean | ||
| 10% trimmed mean | ||
| 20% trimmed mean | ||
| median |
Trimming from each side costs efficiency on perfectly Gaussian data and buys a 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 :
For the mean, : an unbounded line, another view of breakdown with . 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 is Hampel’s influence function (mean: ; median: ).
Association: covariance, Pearson, Spearman, and Kendall
With two variables, the best-known association summary is correlation. Given pairs , sample covariance is and the Pearson coefficient,
is the sample analog of population covariance and correlation. It has a geometric interpretation: centering the two data vectors, and , gives , the cosine of the angle between them in . By Cauchy-Schwarz, , with equality if and only if points lie exactly on a line.
The least-squares line has slope , leaving squared residual . Thus is the fraction of variation explained by a line in . That is why each Anscombe set, with , looks equally “explained”: is a linear summary.
Pearson sees only linear association. If is symmetric and , there is perfect dependence and is (almost) zero: zero correlation does not imply independence. It has unbounded influence: one distant point controls , as it controls . Two alternatives examine only order.
Both equal if and only if is a strictly increasing function of (and if decreasing), and share the key property:
Proof
Strictly increasing means and : it preserves order and ties, so ranks of equal those of , and each pair is concordant, discordant, or tied exactly when it was before. Likewise for . Spearman and Kendall depend only on ranks and signs of differences.
∎Pearson does not share this property. For a standard Gaussian pair with correlation , the three are approximately: Pearson , Spearman and Kendall . Passing both variables through drops Pearson to while Spearman and Kendall remain and . 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.
Two cautions about what rank coefficients also do not do. They detect monotone association: with 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: .
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 to with a line at the median, and whiskers to the most distant observation within fences and . Everything outside is drawn as a point. In a normal distribution, fences lie from the mean and mark 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 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.
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 quantile values match the table (type 7’s is NumPy’s default), and the ECDF returns at because four of the eight observations are at most that value.
Now the important part: variance. A classic failure is computing 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 the mean of the first observations, . For centered sum of squares , using the variance identity with the previous mean,
(Check it this way: for any ; with and separating the final term, . Since , this is with , and 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.
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 , squares are on the order of and float64 spacing there is : the desired difference, approximately , cannot be represented. With mean the naive formula already fails in the fourth digit ( versus ), and with mean it returns exactly : 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.
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 , trimmed mean with , median and MAD with . And correlations, using the functions above against scipy.stats:
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 , Pearson falls from to (population value is ; with points there is sampling noise), and our functions agree with scipy, even with ties. Outlier added to one hundred points shows the difference in sensitivity: Pearson falls from to , while Spearman goes from to and Kendall from to .
The professional version
All this already exists and is what you should use. The equivalence table:
| Calculation | NumPy | pandas | scipy.stats |
|---|---|---|---|
| mean, variance | np.mean, np.var(ddof=1) | .mean(), .var() | tvar |
| median, quantiles | np.median, np.quantile(method=) | .median(), .quantile(q, interpolation=) | mstats.mquantiles |
| trimmed mean | trim_mean(x, 0.1) | ||
| scaled MAD | median_abs_deviation(x, scale="normal") | ||
| skewness, kurtosis | .skew(), .kurt() | skew, kurtosis | |
| ECDF | stats.ecdf(x) | ||
| correlations | np.corrcoef | .corr(method="pearson" | "spearman" | "kendall") | pearsonr, spearmanr, kendalltau |
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 ( of data) suffice to show the above: mean rises from (median and trimmed mean) to , standard deviation is versus scaled MAD , and excess kurtosis is . Note correlations too: since was generated as plus noise, the six errors drag their with them and form a high-leverage group aligned with the line. Pearson is with them and without, while Spearman goes from to and Kendall from to : a summary depending on how many errors exist is not a summary of the relationship.
Three things to watch. ddof: NumPy divides by , pandas by . Skewness and kurtosis: scipy.stats defaults to and (with ), while pandas applies bias corrections and gives somewhat different values, especially with small . Quantiles: NumPy, pandas, and R agree on type 7; other programs do not. When reproducing another tool’s number, check its convention before debugging.
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 near ; 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.
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 ( ms) is over twice the median ( ms) and describes almost no request: it is pulled by the slow and the of s timeouts. Standard deviation ( ms, eight times the mean) is worse, because each timeout contributes ; with skewness and a maximum times the median, this is a textbook heavy tail. The median ( ms), 10% trimmed mean ( ms), and scaled MAD ( ms) describe typical behavior well, but deliberately ignore the tail experienced by waiting users. Percentiles tell the full story: p95 ms, p99 ms ( of requests exceed the latter), and p99.9 ms, the timeout itself, because timeouts () already exceed the 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
More than one answer may be correct.
Step 1 of 3. For the sum of squares, which identity do you use?
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 . 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 , 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)method='linear').Summary
- Mean minimizes squared sum and median absolute sum; with divisor is unbiased, and scaled MAD () and are robust scales consistent with on Gaussian data.
- Sample skewness and kurtosis are bounded (), biased, and highly unstable with heavy tails; do not use them to decide normality.
- ECDF is the parameter-free empirical distribution; it converges uniformly to (Glivenko-Cantelli, DKW). Summaries are functionals of , quantiles have nine conventions (type 7 in NumPy, pandas, and R), and high percentiles need .
- A histogram depends on width and origin and can invent or hide modes; the ECDF cannot.
- Breakdown point: mean , trimmed mean , median , and quantile breaks with fraction . 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.