Learning path: Explore a Dataset Before You Model · Step 5 of 6
Correlation and Heatmaps: Covariance, df.corr() and What They Miss
Put one number on "these two columns move together": why covariance depends on units, how correlation fixes it, scanning every pair with df.corr() and a seaborn heatmap, and the two traps correlation can't see.
What you will learn
- Explain why covariance depends on the units and correlation does not
- Compute a correlation matrix with df.corr(numeric_only=True) and draw it with sns.heatmap
- Encode a text column as 0 and 1 so it shows up next to the label
- Recognise what correlation misses: causes, curves and near-duplicate columns
Before you start
- Reading a CSV with pandas
- Scatter Plots and Pair Plots
When ice-cream sales go up, so do sunburns: both rise together. When it gets warmer, fewer coats are sold: one goes up, the other goes down. And shoe size against exam score shows no pattern at all.
Two columns can move together, move in opposite directions, or have nothing to do with each other. In Scatter Plots and Pair Plots you saw this as dots. Correlation turns each of these pictures into one number, and a heatmap lets you scan every pair at once.
Load the data
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
iris = pd.read_csv("iris.csv")
insurance = pd.read_csv("insurance.csv")
Covariance: the direction, but it depends on the units
Here are five students: hours studied and exam score.
hours = np.array([1, 2, 3, 4, 5])
score = np.array([52, 58, 61, 69, 75])
print(np.cov(hours, score)[0, 1])
print(np.cov(hours * 60, score)[0, 1])
14.25
855.0
The covariance is 14.25. It's positive, so when hours go up, scores go up. That's useful.
But count the same study time in minutes and covariance jumps to 855. Same students, same relationship, a very different number. Covariance tells you the direction, but not how strong the link is.
Correlation: the same story, scaled from -1 to 1
Correlation fixes that by dividing out the units: take the covariance and divide it by the spread of both columns. What's left always lands between -1 and +1.
- +1: a perfect upward straight line.
- -1: a perfect downward straight line.
- 0: no straight-line link at all.
r1 = np.corrcoef(hours, score)[0, 1]
r2 = np.corrcoef(hours * 60, score)[0, 1]
print(r1.round(3), r2.round(3))
0.992 0.992
0.992, very strong, and the same in hours or minutes. The units cancel out.
Every column against every other: df.corr()
For a whole table, pandas has one call. numeric_only=True keeps the number columns and leaves out text, like species.
corr = iris.corr(numeric_only=True)
corr.round(2)
sepal_length sepal_width petal_length petal_width
sepal_length 1.00 -0.12 0.87 0.82
sepal_width -0.12 1.00 -0.43 -0.37
petal_length 0.87 -0.43 1.00 0.96
petal_width 0.82 -0.37 0.96 1.00
Every cell is one pair. The diagonal is 1.00, because a column is perfectly correlated with itself. The grid is also a mirror: the top-right half repeats the bottom-left half.
The same numbers as a heatmap
A grid of numbers is hard to scan, so colour it.
sns.heatmap(corr, annot=True, fmt=".2f",
cmap="coolwarm", vmin=-1, vmax=1)
plt.show()

annot=Truewrites the number in each cell, andfmt=".2f"keeps two decimals.cmap="coolwarm": dark red is a strong positive link, dark blue a strong negative one.vmin=-1, vmax=1pin the colour scale, so a colour means the same thing in every heatmap you draw.
Look away from the diagonal. The warmest cell is petal length with petal width, at 0.96.
Why 0.96 matters: multicollinearity
Say you feed both petal length and petal width to a linear model. At 0.96 they carry almost the same information. That's called multicollinearity, like hearing the same news twice.
With two near copies, a linear model can't decide how to share the weight between them, so its results get unstable. You'd often keep just one of the pair. Tree models mostly don't mind.
Correlation with the label
The most useful column of the grid is the one for your label. In the insurance data the label is charges:
ins_corr = insurance.corr(numeric_only=True)
ins_corr[["charges"]].round(2)
charges
age 0.30
bmi 0.20
children 0.07
charges 1.00
Age 0.30, BMI 0.20, children almost nothing. But where is smoker? It's text, so corr quietly skipped it.
Turn smoker into 0 and 1
is_smoker = insurance["smoker"] == "yes"
insurance["smoker_yes"] = is_smoker.astype(int)
pair = ["smoker_yes", "charges"]
insurance[pair].corr().round(2)
smoker_yes charges
smoker_yes 1.00 0.79
charges 0.79 1.00
0.79, by far the strongest link to charges. The most important column was missing from the grid. Never trust a correlation grid blindly: check what it left out.
Correlation is not causation
Ice-cream sales and sunburns rise and fall together, a strong correlation. But ice cream doesn't cause sunburn. The sun causes both. Correlation tells you two columns move together, never why.
Correlation only sees straight lines
x = np.arange(-5, 6)
y = x ** 2
print(np.corrcoef(x, y)[0, 1].round(2))
0.0
x runs from -5 to 5 and y is x squared, a perfect U shape. Yet the correlation is 0.0. The best straight line through a U is flat, so even a perfect curve can score zero. Always look at the scatter plot too.
Common mistakes
- Comparing covariances across units. 14.25 and 855 are the same relationship. Use correlation.
- Forgetting text columns.
corr(numeric_only=True)drops them silently; encode the important ones first. - Reading 0 as "no relationship". It means no straight-line relationship.
- Reading a link as a cause. Look for a third factor, like the sun.
- Keeping both columns of a 0.96 pair in a linear model without thinking about it.
Quick recap
| Idea | Code | Result here |
|---|---|---|
| Covariance | np.cov(a, b)[0, 1] | 14.25 in hours, 855.0 in minutes |
| Correlation | np.corrcoef(a, b)[0, 1] | 0.992 in both |
| Every pair | df.corr(numeric_only=True) | Petal length and width: 0.96 |
| Heatmap | sns.heatmap(corr, annot=True, vmin=-1, vmax=1) | Colour per pair |
| Link to the label | corr[["charges"]] | smoker_yes 0.79, age 0.30 |
| Curves | y = x ** 2 | r = 0.0 |
Before you use any of this to choose features, remember the rule from Train-Test Split and Data Leakage: in a real project, explore the training part only.
Try it yourself
In iris, which column is the most negatively correlated with petal_length? Find it in the table, then in your own heatmap.
The notebook and both datasets are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Finding Outliers: Box Plots, Violin Plots and the IQR Rule
Next →Train-Test Split and Data Leakage: Split First, Learn After
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
First Look at a Dataset: 6 Checks Before You Plot or Model
Six quick pandas checks that tell you what's inside a dataset: size, types, gaps, spread, label balance and duplicates. Shown on 142,193 days of Australian weather.
Plotting Distributions with seaborn: Histograms, KDE, Counts and log1p
Look at one column at a time: read the peak and the tail of a histogram, compare groups with hue, count categories, and tame a long tail with log1p. Shown on restaurant bills and iris flowers.
Scatter Plots and Pair Plots: See How Two Columns Relate
Draw one dot per row with seaborn scatterplot, colour the dots by group with hue, turn a clean split into a one-line rule, and read every pair at once with pairplot. Shown on iris and tips.
Finding Outliers: Box Plots, Violin Plots and the IQR Rule
Read a box plot from its five numbers, flag outliers with the 1.5 x IQR rule in pandas, compare groups with box and violin plots, and cap extreme values with clip. Shown on 244 restaurant bills.