Sign in

Correlation

Correlation coefficient

Correlation is a number between -1 and 1 that says how closely two variables move together: Pearson, Spearman or Kendall.

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

  1. Pair the two variables row by row. Both must have the same length.
  2. 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.
  3. For Spearman, replace each variable by its ranks, giving tied values the average of the ranks they cover, then compute Pearson on the ranks.
  4. 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.
  5. Use matrix to get the coefficient for every pair of columns in a table.
  6. 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 n2n^{2}. 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

IfUse instead
One or both variables are categoricalAssociation analysis with chi-square, Cramer's V or ANOVA
The relationship may be curved and not monotonic, such as a U shapeMutual information, and a scatter plot to see the shape
You need the effect in the variables' own units, not a unit free numberCovariance, or the slope from linear regression

Math foundations

  1. Pearson's r

    r=∑i=1n(xi−xˉ)(yi−yˉ)∑i=1n(xi−xˉ)2  ∑i=1n(yi−yˉ)2r = \frac{\sum_{i=1}^{n} (x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum_{i=1}^{n} (x_i - \bar{x})^{2}} \; \sqrt{\sum_{i=1}^{n} (y_i - \bar{y})^{2}}}

    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.

  2. Spearman's rho

    ρ=r(rank⁡(x), rank⁡(y))\rho = r\big(\operatorname{rank}(x),\, \operatorname{rank}(y)\big)

    Pearson's formula applied to ranks. It equals 1 whenever yy always rises with xx, whatever the shape of the curve.

  3. Spearman without ties

    ρ=1−6∑i=1ndi2n (n2−1)\rho = 1 - \frac{6 \sum_{i=1}^{n} d_i^{2}}{n\,(n^{2} - 1)}

    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.

  4. Kendall's tau-b

    τb=C−D(n0−n1)(n0−n2),n0=n(n−1)2\tau_b = \frac{C - D}{\sqrt{(n_0 - n_1)(n_0 - n_2)}}, \qquad n_0 = \frac{n(n-1)}{2}

    The surplus of agreeing pairs over disagreeing pairs. The denominator removes pairs tied in xx and pairs tied in yy, so the value can still reach 1 or -1 when ties exist.

  5. Test of no correlation

    t=rn−21−r2t = r \sqrt{\frac{n-2}{1-r^{2}}}

    Under no correlation this follows a t distribution with n−2n - 2 degrees of freedom. It is exact for Pearson with normal data and an approximation for Spearman.

Symbols

xi,yix_i, y_i
the i-th pair of observations
xˉ,yˉ\bar{x}, \bar{y}
the means of the two variables
nn
number of pairs
did_i
difference between the rank of x and the rank of y for observation i
C,DC, D
number of concordant and discordant pairs of observations
n0n_0
total number of pairs of observations
n1,n2n_1, n_2
number of pairs tied in x, and tied in y

Worked by hand

Five pairs: x=1,2,3,4,5x = 1, 2, 3, 4, 5 and y=3,1,2,5,4y = 3, 1, 2, 5, 4. Both means are 3, and the values are already their own ranks.

∑(xi−3)(yi−3)=(−2)(0)+(−1)(−2)+(0)(−1)+(1)(2)+(2)(1)=6\sum (x_i - 3)(y_i - 3) = (-2)(0) + (-1)(-2) + (0)(-1) + (1)(2) + (2)(1) = 6
∑(xi−3)2=10,∑(yi−3)2=0+4+1+4+1=10\sum (x_i - 3)^{2} = 10, \qquad \sum (y_i - 3)^{2} = 0 + 4 + 1 + 4 + 1 = 10
r=610 10=0.6r = \frac{6}{\sqrt{10}\,\sqrt{10}} = 0.6
ρ=1−6×(4+1+1+1+1)5×24=1−48120=0.6\rho = 1 - \frac{6 \times (4 + 1 + 1 + 1 + 1)}{5 \times 24} = 1 - \frac{48}{120} = 0.6
τb=7−310=0.4\tau_b = \frac{7 - 3}{10} = 0.4

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

  1. 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.

  2. For y=x2y = x^{2} on values of xx 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.

  3. 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 nn enters the t statistic. Then consider r2r^{2}, the share of variance one variable explains in the other.

  4. 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.

  5. 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, C/n0C / n_0 is the chance that a random pair agrees in order and D/n0D / n_0 the chance that it disagrees.