A dataset with 9 numeric columns has 36 pairs of columns. Checking each pair's correlation one at a time is slow, and you'd never spot the patterns. A correlation matrix puts all of them in one table, and a heatmap colours that table so the strong relationships jump out at a glance. It's one of the first charts drawn in almost every data science project.
Here you'll build one for the 20,640 California housing districts, make it readable (most default heatmaps aren't), and use it to answer the two questions that matter before modelling: which features move with the target, and which features are near-copies of each other. Then you'll check what the heatmap can't show you.
What you need first: correlation explained, correlation vs causation and the transpose of a matrix (for what "symmetric" means).
Key terms
- Correlation matrix: a table with the correlation between every pair of columns. Row i, column j holds corr(column i, column j).
- Heatmap: a chart that colours each cell of a table by its value.
- Diverging colour map: a colour scale with one colour for negative values, another for positive, and a neutral colour at 0.
- Redundant features: features so strongly correlated that they carry almost the same information.
- Multicollinearity: strong correlation among the input features of a linear model, which makes its coefficients unstable.
The correlation matrix
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").
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.datasets import fetch_california_housing
pd.set_option("display.width", 140)
pd.set_option("display.max_columns", 12)
housing = fetch_california_housing(as_frame=True).frame
corr = housing.corr()
print(corr.round(2))
MedInc HouseAge AveRooms AveBedrms Population AveOccup Latitude Longitude MedHouseVal
MedInc 1.00 -0.12 0.33 -0.06 0.00 0.02 -0.08 -0.02 0.69
HouseAge -0.12 1.00 -0.15 -0.08 -0.30 0.01 0.01 -0.11 0.11
AveRooms 0.33 -0.15 1.00 0.85 -0.07 -0.00 0.11 -0.03 0.15
AveBedrms -0.06 -0.08 0.85 1.00 -0.07 -0.01 0.07 0.01 -0.05
Population 0.00 -0.30 -0.07 -0.07 1.00 0.07 -0.11 0.10 -0.02
AveOccup 0.02 0.01 -0.00 -0.01 0.07 1.00 0.00 0.00 -0.02
Latitude -0.08 0.01 0.11 0.07 -0.11 0.00 1.00 -0.92 -0.14
Longitude -0.02 -0.11 -0.03 0.01 0.10 0.00 -0.92 1.00 -0.05
MedHouseVal 0.69 0.11 0.15 -0.05 -0.02 -0.02 -0.14 -0.05 1.00
housing.corr() computes the Pearson correlation of every pair of numeric columns. Non-numeric columns would be skipped (with a warning in recent pandas), so select or encode them first.
Before reading it, notice its structure:
- The diagonal is all 1s: every column is perfectly correlated with itself.
- It's symmetric: corr(A, B) = corr(B, A), so the top-right triangle mirrors the bottom-left. Half the table is repeated information.
Even so, 81 numbers are hard to read. Colour helps.
A heatmap that's easy to read
mask = np.triu(np.ones_like(corr, dtype=bool))
fig, ax = plt.subplots(figsize=(9, 7))
sns.heatmap(corr, mask=mask, annot=True, fmt=".2f", cmap="RdBu_r", vmin=-1, vmax=1,
center=0, square=True, linewidths=0.5, cbar_kws={"shrink": 0.8}, ax=ax)
ax.set_title("Correlations between California housing columns")
plt.show()
Each setting fixes a common problem with default heatmaps:
mask=np.triu(...)hides the upper triangle and the diagonal, which repeat information.np.triumarks the cells on and above the diagonal.annot=True, fmt=".2f"writes each correlation in its cell, to two decimal places, so you don't have to guess numbers from colours.cmap="RdBu_r"withvmin=-1, vmax=1, center=0uses a diverging colour map: red for positive, blue for negative, white for 0, on a fixed scale. Without a fixed scale, seaborn stretches colours to the data's own range, and a weak correlation of 0.2 can look as dark as a strong one.
Question 1: which features move with the target?
The target is MedHouseVal. Pull out its column and sort by strength, ignoring the sign:
target_corr = corr["MedHouseVal"].drop("MedHouseVal")
print(target_corr.reindex(target_corr.abs().sort_values(ascending=False).index).round(3))
MedInc 0.688
AveRooms 0.152
Latitude -0.144
HouseAge 0.106
AveBedrms -0.047
Longitude -0.046
Population -0.025
AveOccup -0.024
Name: MedHouseVal, dtype: float64
.drop("MedHouseVal")removes the target's correlation with itself..abs().sort_values(...)sorts by size regardless of sign;reindexputs the original signed values in that order.
Median income dominates. The other single-feature correlations are weak. That doesn't make those features useless: location, for example, matters a lot for house prices, but as coordinates it isn't a straight-line effect. Price doesn't rise steadily as you go north; it peaks near the coast and the big cities. A correlation can't see that. A model such as a random forest can.
Question 2: which features are near-copies?
Look for strong correlations between features (not with the target). List every pair above a threshold:
features = corr.drop(index="MedHouseVal", columns="MedHouseVal")
pairs = features.where(np.tril(np.ones(features.shape, dtype=bool), k=-1)).stack()
strong = pairs[pairs.abs() > 0.5].sort_values(key=abs, ascending=False)
print(strong.round(3))
Longitude Latitude -0.925
AveBedrms AveRooms 0.848
dtype: float64
np.tril(..., k=-1)keeps only the cells below the diagonal, so each pair appears once..where(...)blanks out the other cells, and.stack()turns the table into a list of (row, column) pairs, dropping the blanks.
Two pairs stand out:
- Average rooms and average bedrooms (about 0.85): homes with more rooms have more bedrooms. The two features carry much the same information. For a linear model, such pairs cause multicollinearity: the model can't tell which one deserves the credit, so their coefficients can swing wildly while predictions stay similar. Common fixes are dropping one, combining them (rooms per bedroom), or using regularisation.
- Latitude and longitude (about −0.92): moving north tends to mean moving west. That's not a fact about houses, it's the shape of California, which runs from the south-east up to the north-west. Plot it:
fig, ax = plt.subplots(figsize=(5.5, 6))
sc = ax.scatter(housing["Longitude"], housing["Latitude"], c=housing["MedHouseVal"], s=2, cmap="viridis")
fig.colorbar(sc, label="Median house value ($100,000s)")
ax.set_xlabel("Longitude")
ax.set_ylabel("Latitude")
ax.set_title("r = −0.92 is the shape of California")
plt.show()
c=housing["MedHouseVal"] colours each dot by its house value; fig.colorbar adds the scale.
The map shows what the correlation table couldn't: the expensive districts cluster along the coast around the big cities. A strong correlation between two features can come from geography, from how the data was collected, or from a real relationship. Always ask what's behind it.
Pearson or Spearman heatmap?
housing.corr(method="spearman") gives the rank-based version. Compare the two for the columns with outliers:
compare = pd.DataFrame({"Pearson": corr["MedHouseVal"], "Spearman": housing.corr(method="spearman")["MedHouseVal"]})
print(compare.drop("MedHouseVal").round(3))
Pearson Spearman
MedInc 0.688 0.677
HouseAge 0.106 0.075
AveRooms 0.152 0.263
AveBedrms -0.047 -0.125
Population -0.025 0.004
AveOccup -0.024 -0.257
Latitude -0.144 -0.166
Longitude -0.046 -0.070
Where the two disagree, the relationship is curved or distorted by outliers. AveOccup shows the biggest gap, as in correlation explained. For skewed data like this, drawing the Spearman heatmap as well is a quick extra check.
What a heatmap can't show
- Curved relationships. Location affects price strongly, but not in a straight line.
- Relationships with categories. Text columns such as a city name don't appear. For two categories, use contingency tables; for a category against a number, compare group means.
- Interactions. A feature that matters only together with another, such as room count mattering differently in cities and villages.
- Causes. As correlation vs causation showed, none of these numbers say why.
Where machine learning uses correlation matrices
- First look at features: which features relate to the target, and which are redundant, before choosing a model.
- Feature selection: dropping one of each highly correlated pair simplifies models and speeds training, especially for linear models.
- Leakage checks: a feature with a near-perfect correlation with the target deserves suspicion. It may contain the answer.
- PCA: the covariance or correlation matrix is the input to principal component analysis, which combines correlated features into fewer new ones.
Common mistakes
- No fixed colour scale. Always set
vmin=-1, vmax=1, center=0. - Showing the full symmetric matrix. Mask one triangle; it halves the clutter.
- Dropping features because of low correlation with the target. They may matter in a curved or combined way.
- Huge heatmaps. With 100 features, the chart is unreadable; list the strongest pairs instead.
Practice
- Without code, how many distinct pairs are there in a correlation matrix of 9 columns?
Show the answer
9 × 8 ÷ 2 = 36: each column pairs with 8 others, and each pair is counted twice. That's C(9, 2) from permutations and combinations.
- Predict, then check: what's the correlation between
AveRoomsand the new featureAveRooms / AveBedrms(rooms per bedroom)?
Show the answer
Positive, but much weaker than rooms with bedrooms, because the ratio removes the "bigger home" effect that both share.
ratio = housing["AveRooms"] / housing["AveBedrms"]
print(round(housing["AveRooms"].corr(ratio), 3), round(ratio.corr(housing["MedHouseVal"]), 3))
0.447 0.384
The second number shows the ratio is more strongly correlated with house value (0.38) than room count itself (0.15): it captures something room count alone doesn't, a good sign for a new feature.
- Draw the heatmap for the penguins' four numeric columns. Which pair is most strongly correlated?
Show the answer
penguins = sns.load_dataset("penguins")
print(penguins.select_dtypes("number").corr().round(2))
bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
bill_length_mm 1.00 -0.24 0.66 0.60
bill_depth_mm -0.24 1.00 -0.58 -0.47
flipper_length_mm 0.66 -0.58 1.00 0.87
body_mass_g 0.60 -0.47 0.87 1.00
Flipper length and body mass, at about 0.87. (Draw it with the same sns.heatmap call as above.) Note the negative bill length against bill depth: that's Simpson's paradox from correlation vs causation, hiding in a heatmap.
- Why does a heatmap without
vminandvmaxmislead?
Show the answer
Seaborn stretches the colours to fit the data's own range. If the strongest correlation is 0.3, it gets the darkest colour, so weak correlations look strong. A fixed −1 to +1 scale keeps colours honest.
- A feature has a correlation of 0.98 with the target in your training data. What should you check before celebrating?
Show the answer
Whether it leaks the answer: for example, a "final payment status" column when predicting default, or something recorded after the outcome. Check when and how it was collected. Real predictive features rarely correlate that perfectly.
Interview questions
How would you use a correlation matrix in feature selection?
Rank features by their correlation with the target as a first screen, and find highly correlated feature pairs (say above 0.8 in absolute value) to remove redundancy, keeping the more interpretable or more predictive one. Remember it only captures pairwise linear relationships, so check non-linear effects and interactions with models or plots.
What is multicollinearity, and why does it matter?
Strong correlation among a linear model's predictors. Coefficients become unstable and hard to interpret, with large standard errors, even if predictions remain fine. Detect it with the correlation matrix or variance inflation factors; handle it by dropping or combining features, or with ridge regularisation.
Key takeaways
- A correlation matrix holds every pairwise correlation; it's symmetric with 1s on the diagonal.
- A readable heatmap masks one triangle, writes the numbers, and uses a diverging colour map fixed from −1 to +1.
- Read the target column to rank features, and the off-diagonal cells to find redundant pairs.
- Strong feature pairs can come from geography or data collection, not just real relationships.
- Heatmaps miss curves, categories, interactions and causes; use them as a first look, not a verdict.
Frequently asked questions
Should I use df.corr() or np.corrcoef?
For DataFrames, df.corr(): it keeps column names and handles missing values pair by pair. np.corrcoef works on plain arrays and expects each row to be a variable unless you pass rowvar=False.
What about missing values?
df.corr() uses every row where both columns in a pair have values. Different pairs can therefore use different rows, which is worth knowing when columns have many gaps.
What threshold counts as "highly correlated"?
There's no universal rule; 0.8 or 0.9 in absolute value is common for flagging redundancy. Judge by the model: linear models are more sensitive to correlated features than tree-based ones.
What to learn next
- Measure relationships between categories in contingency tables.
- Revisit what each value looks like in correlation explained.
- See regularisation handle correlated features in regularisation explained.