Sub topic 13
Checking correlations between numeric columns
This chapter assumes you can load the Titanic train.csv into a DataFrame called df, select columns, and use groupby. It also assumes you have met the AgeGroup column from the earlier chapter on derived columns. You need pandas and matplotlib installed.
By the end you will be able to compute a correlation matrix, read it, and say what it does and does not show.
What a correlation coefficient measures
A correlation coefficient is a single number between -1 and 1. It describes how closely two numeric columns move together in a straight-line pattern.
- A value near 1 means that when one column is high, the other tends to be high too.
- A value near -1 means that when one column is high, the other tends to be low.
- A value near 0 means there is no clear straight-line relationship.
pandas computes the Pearson coefficient by default. It is sensitive to outliers and only detects linear patterns. Two columns can have a strong curved relationship and still produce a coefficient near 0.
The coefficient says nothing about size. A correlation of 0.3 does not mean one column changes by 30% of the other. It also says nothing about cause, a point the last section returns to.
Computing the correlation matrix
DataFrame.corr() compares every pair of numeric columns and returns a square table. Recent pandas versions raise an error if the frame has text columns and you do not tell corr to skip them, so pass numeric_only=True.
import pandas as pd
df = pd.read_csv("train.csv")
corr = df.corr(numeric_only=True)
print(corr["Survived"].sort_values(ascending=False))corr["Survived"] selects one column of the matrix. That column holds the correlation of every numeric column with Survived. Sorting puts the strongest positive relationship first and the strongest negative one last. The first entry is always Survived itself, with a value of exactly 1.
On the Titanic data you should see Fare with a modest positive value (around 0.26) and Pclass with a moderate negative value (around -0.34). Lower class numbers mean higher class, so richer passengers survived more often, and the negative sign on Pclass is consistent with that.
Which columns are included
numeric_only=True keeps columns with numeric dtypes. In this dataset that includes some columns that are not really quantities:
| Column | Dtype | Meaningful in a correlation? |
|---|---|---|
| `PassengerId` | int64 | No. It is an arbitrary row label. |
| `Survived` | int64 | Yes. It is a 0/1 flag, so the result is a point-biserial correlation. |
| `Pclass` | int64 | With care. It is an ordered category (1, 2, 3), not a measured amount. |
| `Age` | float64 | Yes. |
| `SibSp`, `Parch` | int64 | Yes. They are small counts. |
| `Fare` | float64 | Yes, but it is strongly right-skewed. |
Sex and Embarked are text, so they are dropped. If you want sex in the matrix, you must encode it as numbers yourself. This is a choice you make, not something the correlation does for you.
encoded = df.assign(IsFemale=(df["Sex"] == "female").astype(int))
print(encoded.corr(numeric_only=True)["Survived"].sort_values(ascending=False))IsFemale should come out at about 0.54, larger than any other value in the matrix. A correlation matrix without it would have hidden the strongest relationship.
Missing values and pairwise deletion
Age has missing values. corr handles them with pairwise deletion: for each pair of columns, it drops only the rows where one of those two is missing and computes the coefficient from the rest.
This has a consequence. Different cells of the matrix can rest on different numbers of rows. The Age entries use about 714 passengers, while the Fare and Pclass entries use all 891. If the passengers with missing ages differ systematically from the others, the numbers are not directly comparable. The missing-data chapter explained why that can happen.
To force every cell to use the same rows, drop incomplete rows first.
complete = df[["Survived", "Pclass", "Age", "SibSp", "Parch", "Fare"]].dropna()
print(len(complete))
print(complete.corr())Compare this matrix with the full one. Small differences are normal. Large differences are a signal that the missing ages matter.
Reading the whole matrix
Look at the full matrix, not only the Survived column. Correlations among the predictors tell you which columns carry overlapping information.
cols = ["Survived", "Pclass", "Age", "SibSp", "Parch", "Fare"]
print(df[cols].corr().round(2))Two relationships to look for:
PclassandFareare strongly negatively correlated. First-class tickets cost more, so the two columns partly measure the same thing.SibSpandParchare positively correlated. Passengers traveling with a spouse or siblings often travel with parents or children too, as part of a family.
Because the matrix is symmetric, the cell for (Age, Fare) equals the cell for (Fare, Age). The diagonal is always 1. You only need to read one triangle.
Drawing the matrix as a heatmap
Colors make a larger matrix easier to scan. matplotlib can draw one without extra libraries.
import matplotlib.pyplot as plt
corr = df[cols].corr()
fig, ax = plt.subplots(figsize=(6, 5))
im = ax.imshow(corr, cmap="coolwarm", vmin=-1, vmax=1)
ax.set_xticks(range(len(cols)), labels=cols, rotation=45, ha="right")
ax.set_yticks(range(len(cols)), labels=cols)
fig.colorbar(im, label="Pearson correlation")
plt.tight_layout()
plt.show()Setting vmin=-1 and vmax=1 fixes the color scale, so a pale cell always means a weak correlation. Without it, matplotlib stretches the scale to the data and weak values can look strong.
Why correlation can mislead
A coefficient is a one-number summary of a whole scatter of points. Several things can make it a poor summary.
Outliers and skew
Fare has a long right tail: a few passengers paid more than 500 while most paid under 50. Extreme points can pull a Pearson coefficient up or down. Spearman correlation uses ranks instead of raw values, so it is less affected. Compare the two.
print(df[["Fare", "Survived"]].corr(method="pearson").loc["Fare", "Survived"])
print(df[["Fare", "Survived"]].corr(method="spearman").loc["Fare", "Survived"])If the two values differ a lot, the shape of the distribution is influencing the result. Here Spearman comes out higher (about 0.32), which suggests the relationship is stronger and more consistent across most passengers than the Pearson value implies.
Binary and ordered columns
Survived takes only two values, and Pclass only three. The coefficient still works, but a scatter plot of such columns is just stacked dots. For these, the group means from the groupby chapter are more informative. A table showing survival rate by class tells the same story with units you can read.
Confounding and causation
Correlation tells you that two columns move together. It does not tell you why. Fare correlates with survival, but fare is also tied to class, cabin location, and sex ratio within a class. Paying more may not have saved anyone. The fare may simply stand in for where a passenger was on the ship and who they were.
A third variable that influences both columns is called a confounder. You can check for one by comparing groups. For example, see whether the fare pattern holds inside each class.
print(
df.groupby("Pclass")[["Fare", "Survived"]]
.corr()
.loc[(slice(None), "Fare"), "Survived"]
)If the correlation shrinks inside each class, much of the overall value came from class differences. This is a check, not a proof, because other confounders you have not measured may remain.
Strength is relative
There is no universal cutoff for a "strong" correlation. Treat the sign and the rough size as a pointer to where to look next. A value of 0.1 on 891 rows can be real but small. A value of 0.6 on 12 rows could be luck.
A repeatable routine
Common errors
- Calling
df.corr()withoutnumeric_only=Trueon a mixed-type frame raises aValueErrorin current pandas. - Reading
Pclassas if a one-unit step meant the same change everywhere. The gap between class 1 and class 2 need not equal the gap between 2 and 3. - Comparing cells that rest on different row counts without noticing the pairwise deletion.
- Treating a coefficient near 0 as "unrelated". A curved or grouped pattern can hide behind it.
- Ignoring the sign. A coefficient of -0.34 is as strong as +0.34.
Exercise
You compute df.corr(numeric_only=True) and see that Age has a correlation of about -0.08 with Survived. A colleague says "age does not matter for survival." Name two reasons this conclusion is not justified, and one check you could run.
Show answer
First, Pearson correlation only captures straight-line relationships. Survival may be high for children and lower for adults, which is a non-linear pattern a near-zero coefficient can hide. Second, about 20% of Age values are missing, and pairwise deletion means the coefficient reflects only passengers with a recorded age, who may differ from the rest. A check: group by AgeGroup and compare count and mean of Survived, as in the groupby chapter. Children should show a higher survival rate than the coefficient suggests. You could also compare the result after dropna with the full matrix.
Exercise
Write code that adds an IsFemale column to df and prints its Spearman correlation with Survived, then say why Spearman is acceptable here.
Show answer
Code: df["IsFemale"] = (df["Sex"] == "female").astype(int) followed by print(df[["IsFemale", "Survived"]].corr(method="spearman").loc["IsFemale", "Survived"]). Spearman works on ranks, so it handles two-valued columns without assuming a particular spread of values. With both columns coded 0/1, it gives the same result as Pearson, about 0.54, so the choice does not change the answer here.