Overview
Plot two variables against each other. If the points climb together along a line, the correlation is near 1. If one falls as the other rises, it is near -1. If there is no steady pattern, it is near 0. Pearson's coefficient measures how well a straight line fits. Spearman's replaces each value by its rank, its position in the sorted order, so it measures whether the relation is monotone, meaning always rising or always falling, even when it curves. Kendall's looks at every pair of observations and counts how often the two variables agree on which one is larger. The last two care only about order, so a single extreme value cannot dominate them.
A short history
Francis Galton described correlation in the 1880s while studying how the heights of parents and children are related. Karl Pearson gave the product moment coefficient its mathematical form in 1896. Charles Spearman proposed a rank based version in 1904 for psychological test scores, and Maurice Kendall introduced the tau coefficient in 1938. Together they made it possible to state the strength of a relationship as a single number.
How it works
- Pair the two variables row by row. Both must have the same length.
- For Pearson, subtract each variable's mean, multiply the deviations pair by pair, sum, and divide by the product of the two root sums of squares.
- For Spearman, replace each variable by its ranks, giving tied values the average of the ranks they cover, then compute Pearson on the ranks.
- For Kendall, go through every pair of observations and count concordant pairs (same order in both variables) and discordant pairs (opposite order), then correct for ties.
- Use matrix to get the coefficient for every pair of columns in a table.
- Use p_value to test the hypothesis of no correlation: a t distribution for Pearson and Spearman, a normal approximation for Kendall.
Watch out for
- A coefficient near zero does not mean no relation. A parabola gives a Pearson correlation of 0 because the rising and falling halves cancel.
- Pearson's coefficient is sensitive to outliers, because one extreme pair contributes a very large product of deviations.
- Correlation says nothing about cause. Two variables can move together because a third one drives both.
- Kendall's coefficient here compares every pair, so its cost grows with . Keep it to a few thousand rows.
- If one variable is constant the coefficient is undefined, since the denominator is zero, and the template returns NaN.
Use cases
When to use it
Pearson for roughly linear relations between numeric columns. Spearman or Kendall for ordinal data, skewed data, data with outliers, or relations that curve but keep one direction.
In industry
- Finance
- Portfolio managers estimate correlations between asset returns to judge how much diversification a combination of holdings provides.
- Psychology and education
- Researchers correlate test scores with later outcomes to check whether a test measures what it claims to, using Spearman's coefficient for ranked data.
- Feature analysis in ML
- Teams compute a correlation matrix of numeric features to find near duplicate columns before fitting a linear model.
Choosing it: what must hold
- Two variables measured on the same observations, with pairs that are independent of each other.
- For Pearson, a roughly linear relationship without strong outliers, on interval or ratio data.
- For Spearman or Kendall, a relationship that is monotonic: one variable tends to rise as the other rises.
- Enough pairs that the estimate is stable; a handful of points can give a high value by chance.
When to choose something else
| If | Use instead |
|---|---|
| One or both variables are categorical | Association analysis with chi-square, Cramer's V or ANOVA |
| The relationship may be curved and not monotonic, such as a U shape | Mutual information, and a scatter plot to see the shape |
| You need the effect in the variables' own units, not a unit free number | Covariance, or the slope from linear regression |
Math foundations
Pearson's r
The covariance of the two variables divided by the product of their standard deviations. The division removes the units and confines the result to the range from -1 to 1.
Spearman's rho
Pearson's formula applied to ranks. It equals 1 whenever always rises with , whatever the shape of the curve.
Spearman without ties
When no values are tied, the rank formula simplifies to this. It shows that rho falls as the ranks of the two variables disagree more.
Kendall's tau-b
The surplus of agreeing pairs over disagreeing pairs. The denominator removes pairs tied in and pairs tied in , so the value can still reach 1 or -1 when ties exist.
Test of no correlation
Under no correlation this follows a t distribution with degrees of freedom. It is exact for Pearson with normal data and an approximation for Spearman.
Symbols
- the i-th pair of observations
- the means of the two variables
- number of pairs
- difference between the rank of x and the rank of y for observation i
- number of concordant and discordant pairs of observations
- total number of pairs of observations
- number of pairs tied in x, and tied in y
Worked by hand
Five pairs: and . Both means are 3, and the values are already their own ranks.
Pearson and Spearman agree at 0.6 because the data are ranks. Kendall gives 0.4: of the 10 pairs, 7 agree in order and 3 disagree. Kendall values are usually smaller than Spearman values for the same data.
Visual example
Loading the example.
Try this
- Load the curve that always rises: Spearman and Kendall read 1 while Pearson stays below it.
- Load the pattern with one far point, then drag that point back into the cloud and watch Pearson collapse.
- On the straight line, drag one point far off the line and compare how much each coefficient moves.
Code sample
import numpy as np
from impl import Correlation
from config import CorrelationConfig
x = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
y = np.array([3.0, 1.0, 2.0, 5.0, 4.0])
print(Correlation().coefficient(x, y)) # 0.6
print(Correlation(CorrelationConfig(method="kendall")).coefficient(x, y)) # 0.4
print(Correlation().p_value(x, y))
print(Correlation(CorrelationConfig(method="spearman")).matrix(np.column_stack([x, y, x * y])))Read the implementation (147 lines)
"""Correlation: Pearson's r, Spearman's rho and Kendall's tau-b, with a two-sided p-value.
NumPy and the standard library only. Kendall's tau compares every pair of points, so it costs O(n^2) memory and
time; that is fine for the few thousand rows of an exploratory look.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import CorrelationConfig
except ImportError: # run from the template's own folder
from config import CorrelationConfig
def rankdata(values) -> np.ndarray:
"""Ranks starting at 1; tied values share the average of the ranks they cover. values: shape (n,)."""
x = np.asarray(values, dtype=float).ravel()
order = np.argsort(x, kind="mergesort")
ranks = np.empty(x.size, dtype=float)
sorted_x = x[order]
start = 0
while start < x.size:
stop = start
while stop + 1 < x.size and sorted_x[stop + 1] == sorted_x[start]:
stop += 1
ranks[order[start:stop + 1]] = 0.5 * (start + stop) + 1.0
start = stop + 1
return ranks
def _beta_continued_fraction(a: float, b: float, x: float) -> float:
"""Continued fraction of the incomplete beta function (modified Lentz method)."""
tiny = 1e-300
c, d = 1.0, 1.0 - (a + b) * x / (a + 1.0)
d = 1.0 / (d if abs(d) > tiny else tiny)
h = d
for m in range(1, 500):
for numerator in (
m * (b - m) * x / ((a + 2 * m - 1.0) * (a + 2 * m)),
-(a + m) * (a + b + m) * x / ((a + 2 * m) * (a + 2 * m + 1.0)),
):
d = 1.0 + numerator * d
d = 1.0 / (d if abs(d) > tiny else tiny)
c = 1.0 + numerator / c
c = c if abs(c) > tiny else tiny
delta = d * c
h *= delta
if abs(delta - 1.0) < 1e-15:
break
return h
def betainc(a: float, b: float, x: float) -> float:
"""Regularised incomplete beta function I_x(a, b), for a, b > 0 and 0 <= x <= 1."""
if x <= 0.0:
return 0.0
if x >= 1.0:
return 1.0
log_front = math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log1p(-x)
if x < (a + 1.0) / (a + b + 2.0):
return math.exp(log_front) * _beta_continued_fraction(a, b, x) / a
return 1.0 - math.exp(log_front) * _beta_continued_fraction(b, a, 1.0 - x) / b
def _pearson(x: np.ndarray, y: np.ndarray) -> float:
dx, dy = x - x.mean(), y - y.mean()
denominator = math.sqrt(float(dx @ dx) * float(dy @ dy))
return float("nan") if denominator == 0 else float(np.clip(dx @ dy / denominator, -1.0, 1.0))
def _kendall_parts(x: np.ndarray, y: np.ndarray) -> tuple[float, float, float, float]:
"""Returns (S, n0, ties_x, ties_y): concordant minus discordant pairs, all pairs, pairs tied in x, in y."""
sign_x = np.sign(x[:, None] - x[None, :])
sign_y = np.sign(y[:, None] - y[None, :])
n = x.size
s = float(np.sum(sign_x * sign_y)) / 2.0
ties_x = (float(np.sum(sign_x == 0)) - n) / 2.0
ties_y = (float(np.sum(sign_y == 0)) - n) / 2.0
return s, n * (n - 1) / 2.0, ties_x, ties_y
class Correlation:
"""Correlation coefficient between two variables, or between all columns of a table."""
def __init__(self, config: CorrelationConfig | None = None) -> None:
self.config = config or CorrelationConfig()
@staticmethod
def _pair(x, y) -> tuple[np.ndarray, np.ndarray]:
x = np.asarray(x, dtype=float).ravel()
y = np.asarray(y, dtype=float).ravel()
if x.size != y.size:
raise ValueError(f"x and y must have the same length, got {x.size} and {y.size}")
keep = ~(np.isnan(x) | np.isnan(y)) # a pair with a missing side is dropped
x, y = x[keep], y[keep]
if x.size < 2:
raise ValueError("at least two complete pairs are needed")
return x, y
def coefficient(self, x, y) -> float:
"""Correlation of x and y, both of shape (n,). In [-1, 1]; NaN when one side is constant."""
x, y = self._pair(x, y)
if self.config.method == "pearson":
return _pearson(x, y)
if self.config.method == "spearman":
return _pearson(rankdata(x), rankdata(y))
s, n0, ties_x, ties_y = _kendall_parts(x, y)
denominator = math.sqrt((n0 - ties_x) * (n0 - ties_y))
return float("nan") if denominator == 0 else s / denominator
def matrix(self, table) -> np.ndarray:
"""Correlation of every pair of columns. table: shape (n, d). Returns shape (d, d), ones on the diagonal."""
table = np.asarray(table, dtype=float)
if table.ndim != 2:
raise ValueError(f"table must be 2-D (rows, columns), got shape {table.shape}")
d = table.shape[1]
out = np.eye(d)
for i in range(d):
for j in range(i + 1, d):
out[i, j] = out[j, i] = self.coefficient(table[:, i], table[:, j])
return out
def p_value(self, x, y) -> float:
"""Two-sided p-value of "no correlation".
Pearson and Spearman use the t distribution with n - 2 degrees of freedom (exact for Pearson with normal
data, an approximation for Spearman). Kendall uses the normal approximation without a tie correction.
"""
x, y = self._pair(x, y)
n = x.size
r = self.coefficient(x, y)
if math.isnan(r):
return float("nan")
if self.config.method == "kendall":
s = _kendall_parts(x, y)[0]
z = s / math.sqrt(n * (n - 1) * (2 * n + 5) / 18.0)
return math.erfc(abs(z) / math.sqrt(2.0))
if n < 3:
return float("nan")
if abs(r) >= 1.0:
return 0.0
df = n - 2
t_squared = r * r * df / (1.0 - r * r)
return betainc(df / 2.0, 0.5, df / (df + t_squared))- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 10, run with
python3 -m unittest -v
Practice
Compute Correlation().coefficient on the five pairs above, then again with CorrelationConfig(method="kendall") and method="spearman". Replace the last y value by 400 and recompute all three. Note which coefficient moved and which did not, and call p_value to see whether five points can support any conclusion.
Check on learning
- You change one y value from 4 to 400. Pearson's coefficient changes but Spearman's and Kendall's do not. Why?
A way to think about it
Ask what each coefficient reads from the data. The rank of that point is the same before and after.
- For on values of spread evenly around zero, all three coefficients are near zero. Is there a relation, and what would detect it?
A way to think about it
The relation is perfect but not monotone. Think of a measure that does not assume direction, or split the data at zero.
- With 100 000 rows a correlation of 0.02 has a tiny p-value. Should you act on it?
A way to think about it
Look at how enters the t statistic. Then consider , the share of variance one variable explains in the other.
- Ice cream sales and drowning deaths are strongly correlated across months. How would you test the idea that a third variable explains both?
A way to think about it
Name the candidate, then look at the correlation within groups where that variable is held roughly constant.
- Why can Kendall's tau be read directly as a difference of probabilities, and why is that sometimes easier to explain than Pearson's r?
A way to think about it
Without ties, is the chance that a random pair agrees in order and the chance that it disagrees.