Module 4 · Intermediate · Relationships between variables

Correlation explained: Pearson and Spearman

Correlation measures how closely two columns follow a line, from −1 to +1. See what each value looks like, why to always plot, and when to use Spearman.

By theprogrammers team · · 11 min read

In covariance explained, study hours and marks had a positive covariance, but converting hours to minutes made it 60 times bigger. A measure of "how strongly do these move together" shouldn't depend on whether you measure in hours or minutes. Correlation fixes this. It's covariance with the units taken out, and it always lands between −1 and +1.

Correlation is one of the most used numbers in data analysis: it's the first thing people check when they ask "which features matter?" It's also one of the most misread. A correlation of 0 doesn't mean "no relationship", and four datasets with identical correlations can look nothing alike. You'll see what each value of correlation looks like, compute it two ways, meet a famous warning about trusting the number alone, and learn when to use Spearman's version instead of the usual Pearson's.

What you need first: covariance explained and z-scores and standardisation.

Key terms

  • Correlation coefficient (r): a number from −1 to +1 measuring how closely two columns follow a straight line.
  • Pearson correlation: the standard correlation, covariance divided by both standard deviations.
  • Spearman correlation: Pearson's correlation calculated on the ranks of the values instead of the values themselves. It measures any steadily rising or falling relationship, not just straight lines.
  • Monotonic relationship: one where y always rises as x rises (or always falls), though not necessarily in a straight line.
  • Rank: a value's position when the column is sorted: 1 for the smallest, 2 for the next, and so on.

From covariance to correlation

Covariance had the units of both columns multiplied together. Divide by both standard deviations, and the units cancel:

r = cov(x, y) ÷ (SD(x) × SD(y))

There's an easier way to see it. Standardise both columns, turning each value into a z-score (how many SDs from the mean). Then the covariance of the z-scores is the correlation. Correlation is the average product of z-scores. Since z-scores have no units, neither does correlation.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({"hours": [2, 3, 5, 6, 8, 9, 11, 12],
                   "marks": [45, 52, 50, 60, 68, 75, 74, 84]})
z = (df - df.mean()) / df.std()

print("cov ÷ (SD × SD):     ", round(df["hours"].cov(df["marks"]) / (df["hours"].std() * df["marks"].std()), 4))
print("covariance of z-scores:", round(z["hours"].cov(z["marks"]), 4))
print("pandas .corr():      ", round(df["hours"].corr(df["marks"]), 4))
print("in minutes:          ", round((df["hours"] * 60).corr(df["marks"]), 4))
cov ÷ (SD × SD):      0.9669
covariance of z-scores: 0.9669
pandas .corr():       0.9669
in minutes:           0.9669

All three routes give the same number, and converting hours to minutes doesn't change it at all. The correlation is close to +1: these eight students almost lie on a rising straight line.

What each value looks like

The only way to get a feel for correlation is to see it. Here are simulated datasets aiming at correlations of 0.95, 0.5, 0, −0.5 and −0.95; random noise makes each land close to its target. Before looking, guess what a correlation of 0.5 looks like:

rng = np.random.default_rng(3)
fig, axes = plt.subplots(2, 3, figsize=(11, 7))
for ax, target in zip(axes.ravel()[:5], [0.95, 0.5, 0.0, -0.5, -0.95]):
    x = rng.normal(size=300)
    y = target * x + np.sqrt(1 - target**2) * rng.normal(size=300)
    ax.scatter(x, y, s=10, color="#c2410c", alpha=0.6)
    ax.set_title(f"r = {np.corrcoef(x, y)[0, 1]:.2f}")
x = rng.uniform(-3, 3, 300)
y = x**2 + rng.normal(scale=0.5, size=300)
axes[1, 2].scatter(x, y, s=10, color="#0f766e", alpha=0.6)
axes[1, 2].set_title(f"a U-shape: r = {np.corrcoef(x, y)[0, 1]:.2f}")
for ax in axes.ravel():
    ax.set_xticks([])
    ax.set_yticks([])
plt.tight_layout()
plt.show()
Six scatter plots. r = 0.96: points in a tight rising band. r = 0.56: a loose rising cloud. r = 0.04: a round cloud with no direction. r = −0.45: a loose falling cloud. r = −0.95: a tight falling band. The sixth, in green, is a clear U-shaped curve whose correlation is close to 0.
  • y = target * x + np.sqrt(1 - target**2) * noise is a standard recipe for making two columns with roughly the target correlation: a share of x plus the right amount of random noise.
  • np.corrcoef(x, y) returns a 2 × 2 correlation matrix; [0, 1] picks the correlation between x and y.

Three things to notice:

  1. The sign is the direction: positive rises, negative falls.
  2. The size is how tightly points hug a line, not how steep the line is. A correlation of 0.5 is a loose cloud with a visible tilt, weaker than most people expect.
  3. The U-shape has a correlation near 0, yet y depends completely on x. Pearson correlation only detects straight-line relationships. A correlation of 0 means "no straight line", not "no relationship".

A rough guide for reading the size, though it depends on the field:

rDescription
Below 0.1Negligible
0.1 to 0.3Weak
0.3 to 0.5Moderate
0.5 to 0.7Strong
Above 0.7Very strong

Always plot: Anscombe's quartet

In 1973 the statistician Francis Anscombe made four small datasets with almost identical means, standard deviations and correlations. Predict: will their scatter plots look alike?

import seaborn as sns

anscombe = sns.load_dataset("anscombe")
print(anscombe.groupby("dataset").apply(lambda g: round(g["x"].corr(g["y"]), 3), include_groups=False))

fig, axes = plt.subplots(1, 4, figsize=(13, 3.3), sharex=True, sharey=True)
for ax, (name, group) in zip(axes, anscombe.groupby("dataset")):
    ax.scatter(group["x"], group["y"], color="#c2410c")
    ax.set_title(f"dataset {name}: r = {group['x'].corr(group['y']):.2f}")
plt.tight_layout()
plt.show()
dataset
I      0.816
II     0.816
III    0.816
IV     0.817
dtype: float64
Four scatter plots with the same correlation of 0.82. Dataset I is a noisy rising line. Dataset II is a smooth curve that rises then falls. Dataset III is an almost perfect straight line with one outlier far above it. Dataset IV has all points at the same x value except one far to the right, which alone creates the correlation.

groupby("dataset") splits the data into the four datasets; include_groups=False stops pandas passing the grouping column into the function.

Same correlation, four completely different stories:

  • I is what correlation is designed for: a straight-line trend with noise.
  • II is a curve. The correlation is high, but a straight line is the wrong description.
  • III would be a perfect line, except one outlier drags the correlation down.
  • IV has no relationship at all, except one extreme point that creates the whole correlation.

The lesson: a correlation is a summary, not a description. Always look at the scatter plot.

Spearman: when the relationship isn't straight

Many real relationships rise steadily but not in a straight line: income and spending, experience and salary, house size and price. Spearman's correlation measures how consistently y rises (or falls) as x rises, whatever the curve's shape. It replaces each value by its rank and then computes the ordinary Pearson correlation on the ranks:

x = np.arange(1, 21)
curve = pd.DataFrame({"x": x, "y": np.exp(x / 3)})          # always rising, but sharply curved
print("Pearson: ", round(curve["x"].corr(curve["y"]), 3))
print("Spearman:", round(curve["x"].corr(curve["y"], method="spearman"), 3))
print("Pearson on ranks:", round(curve["x"].rank().corr(curve["y"].rank()), 3))
Pearson:  0.798
Spearman: 1.0
Pearson on ranks: 1.0
  • method="spearman" asks pandas for Spearman's correlation.
  • .rank() replaces each value by its position in sorted order; Pearson on the ranks gives the same number as Spearman.

Every rise in x comes with a rise in y, so Spearman's correlation is exactly 1. Pearson's is lower, because the points curve away from a straight line.

Ranks also make Spearman's correlation resistant to outliers, in the same way the median is: an extreme value just becomes the top rank, however extreme it is. Try it on dataset III from Anscombe's quartet:

iii = anscombe[anscombe["dataset"] == "III"]
print("Pearson: ", round(iii["x"].corr(iii["y"]), 3))
print("Spearman:", round(iii["x"].corr(iii["y"], method="spearman"), 3))
Pearson:  0.816
Spearman: 0.991

The outlier pulls Pearson's correlation down; Spearman's, working with ranks, barely notices it.

PearsonSpearman
MeasuresStraight-line relationshipsAny steadily rising or falling relationship
UsesThe valuesThe ranks of the values
OutliersSensitiveResistant
Works for ordered categories (ratings 1 to 5)?Not idealYes

Real data: which features move with house value?

Back to the 20,640 California districts. Covariance couldn't compare features in different units; correlation can:

Download the data: california-housing.csv (1.9 MB), or from the original source, StatLib at Carnegie Mellon University. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("california-housing.csv").

from sklearn.datasets import fetch_california_housing

housing = fetch_california_housing(as_frame=True).frame
cols = ["MedInc", "HouseAge", "AveRooms", "AveOccup", "Population"]
result = pd.DataFrame({
    "Pearson": [housing[c].corr(housing["MedHouseVal"]) for c in cols],
    "Spearman": [housing[c].corr(housing["MedHouseVal"], method="spearman") for c in cols],
}, index=cols)
print(result.round(3))
            Pearson  Spearman
MedInc        0.688     0.677
HouseAge      0.106     0.075
AveRooms      0.152     0.263
AveOccup     -0.024    -0.257
Population   -0.025     0.004

Median income has by far the strongest relationship with house value. Look at AveOccup (people per household): its Pearson correlation is almost 0, but its Spearman correlation is clearly negative. A few absurd districts with hundreds of occupants (found in summary statistics in pandas) wreck Pearson's correlation; Spearman's ranks see through them, revealing that more crowded districts tend to have cheaper homes.

Where machine learning uses correlation

  • Feature screening: features with a strong correlation with the target are candidates for a model. A weak Pearson correlation doesn't rule a feature out, though: it might have a curved relationship (check Spearman, or plot it), or matter only together with other features.
  • Redundant features: two features correlated at 0.95 carry almost the same information. Linear models can become unstable with such pairs (called multicollinearity), so one is often dropped or regularisation is used.
  • Data leakage detection: a feature with a suspiciously perfect correlation with the target, such as 0.99, may be leaking the answer. The data leakage lesson in the ML course covers this.
  • Checking predictions: the correlation between a regression model's predictions and the true values is a quick sanity check; its square is closely related to R².

Common mistakes

  • Reading a correlation of 0 as "no relationship". It only rules out a straight line.
  • Trusting the number without a plot. Anscombe's quartet shows four stories behind one value.
  • Using Pearson on curved or outlier-heavy data. Use Spearman, or transform the data first.
  • Treating correlation as cause. That's big enough for its own lesson: correlation vs causation.

Practice

  1. What correlation do you get between a column and itself? Between a column and minus itself?
Show the answer

+1 and −1. Every point lies exactly on a rising line in the first case and a falling line in the second.

  1. Predict, then check: if you add 10 marks to every student's score, does the correlation between hours and marks change?
Show the answer

No. Adding a constant shifts the mean but doesn't change any z-score.

print(round(df["hours"].corr(df["marks"] + 10), 4))
0.9669
  1. A scatter plot shows a perfect upside-down U. Roughly what will Pearson's correlation be? Spearman's?
Show the answer

Both near 0. Pearson finds no straight line, and the relationship isn't monotonic either: it rises then falls, so ranks don't rise steadily. Neither measure detects a U-shape; only the plot does.

  1. In the California data, find the Pearson and Spearman correlations between MedInc and AveRooms. Is the relationship positive?
Show the answer
print(round(housing["MedInc"].corr(housing["AveRooms"]), 3), round(housing["MedInc"].corr(housing["AveRooms"], method="spearman"), 3))
0.327 0.644

Positive in both: richer districts tend to have bigger homes. Spearman's is larger, because a few districts with extreme average room counts weaken Pearson's.

  1. A colleague drops a feature because its correlation with the target is 0.05. What might they miss?
Show the answer

A curved or U-shaped relationship (check a plot or Spearman), a relationship hidden by outliers, or a feature that matters only in combination with others, which tree-based models can use. Low correlation is a reason to look closer, not an automatic reason to drop.

Interview questions

What's the difference between Pearson and Spearman correlation?

Pearson measures the strength of a linear relationship using the values; it's sensitive to outliers. Spearman is Pearson's correlation on ranks, so it measures monotonic relationships of any shape and is robust to outliers. Use Spearman for curved monotonic relationships, ordinal data or heavy-tailed data.

Can two variables be strongly related but have zero correlation?

Yes. Pearson correlation only captures linear association. y = x² on symmetric x has near-zero correlation despite perfect dependence. Zero correlation means no linear relationship, not independence.

Key takeaways

  • Correlation is covariance divided by both SDs: the average product of z-scores, always between −1 and +1, with no units.
  • The sign gives the direction; the size gives how tightly points follow a straight line.
  • A correlation of 0 rules out only a straight line; curves and U-shapes can hide behind it.
  • Anscombe's quartet: identical correlations, different stories. Always plot.
  • Spearman's correlation uses ranks: it measures any steady rise or fall and resists outliers.

Frequently asked questions

Is correlation the same as the slope of a line?

No. Slope says how much y changes per unit of x, in units. Correlation says how tightly points follow a line, with no units. A shallow line can have a correlation of 0.99, and a steep one 0.3.

What's Kendall's tau?

Another rank-based correlation, counting pairs of rows that are in the same order in both columns. It behaves much like Spearman's and is often preferred for small samples. pandas offers it with method="kendall".

How many rows do I need for a reliable correlation?

With 10 rows, correlations swing wildly by chance; a value of 0.5 can easily appear from unrelated data. With hundreds of rows, they're much more stable. The hypothesis testing module shows how to test whether a correlation could be chance.

What to learn next

  1. Avoid the biggest misreading in correlation vs causation.
  2. See every pair at once in correlation matrix and heatmap in Python.
  3. Revisit the building block in covariance explained.