Sub topic 14
Reading results carefully: missing data, confounding, and small groups
The earlier chapters produced numbers: missing counts, group means, a correlation table. This chapter covers how far to trust those numbers. It assumes you can run the train.csv code from the previous chapters, that df is the Titanic DataFrame, and that you know groupby, boolean masks, and value_counts. It covers three problems that mislead first-time analysts: missing data that is not random, confounding, and rates built on few rows.
Why a correct number can still mislead
Every output so far was computed correctly. The risk lies in what you conclude from it. A group mean answers "what fraction of these rows survived?" It does not answer "why?", and it does not say how reliable the fraction is. Before you write down a finding, run it through three checks.
Missing data
You already counted missing values. The next question is whether the rows with missing values differ from the others. If they do, any statistic computed on the non-missing rows describes a biased subset.
Age is missing for about 20% of passengers. Compare survival and class for rows with and without an age:
import pandas as pd
df = pd.read_csv("train.csv")
df["AgeMissing"] = df["Age"].isna()
print(df.groupby("AgeMissing")["Survived"].agg(["count", "mean"]))
print(pd.crosstab(df["Pclass"], df["AgeMissing"], normalize="columns").round(2))Two things show up. Passengers with no recorded age survived less often (roughly 29% against 41%). And most of the missing ages belong to third-class passengers. So the missing ages are not scattered at random. Any age analysis that drops those rows under-represents third class, and third class had the lowest survival.
Statisticians describe three situations:
- Missing completely at random: the gaps have no relation to any variable. This is rare in real data.
- Missing at random: the gaps depend on other columns you have, such as class. Grouping by those columns can partly correct for them.
- Missing not at random: the gap depends on the missing value itself, or on something you did not record.
Cabin is missing for about 77% of rows. Here the missingness is informative in itself. A cabin was probably recorded mainly for passengers whose records survived or who were in first class. Comparing survival for df["Cabin"].isna() against the rest shows a large gap, but it reflects how the record was made, not the effect of a cabin.
Pandas helps with one more habit. Many functions skip missing values silently. df["Age"].mean() averages over 714 values, not 891. groupby also drops rows whose group key is missing unless you pass dropna=False. Always check the count column next to any mean.
Confounding
A confounder is a variable that is related to both the thing you group by and the outcome. It creates a pattern that looks like a direct link.
Survival differs by class, and it differs by sex. Fare is strongly related to class, and the correlation table showed Fare correlating positively with survival. A tempting reading is "paying more bought safety". Class sits behind both Fare and survival, so Fare may add little once class is held fixed.
The remedy at this stage is simple: compare within strata. A stratum is a subgroup in which the confounder is held constant. You have already used this pattern with two grouping keys:
import pandas as pd
df = pd.read_csv("train.csv")
by_class_sex = df.groupby(["Pclass", "Sex"])["Survived"].agg(["count", "mean"])
print(by_class_sex.round(2))
print(df.groupby("Pclass")["Sex"].apply(lambda s: (s == "male").mean()).round(2))Within each class, women survived far more often than men: about 97% and 37% in first class, 92% and 16% in second, 50% and 13% in third. Sex matters inside every class, so it is not just a stand-in for class. Class also still matters within each sex, although the gap among men is smaller than the overall class gap suggests.
The second statement prints the share of men in each class. Third class had a much higher share of men than first or second. That imbalance means the overall class gap mixes a class effect with a sex composition effect.
Sometimes the stratified picture reverses the overall one. This is called Simpson's paradox. It happens when group sizes are unevenly spread across strata. You will not always meet it, but when an overall trend and a within-group trend disagree, trust neither until you understand why.
Stratifying reduces confounding from the variables you split on. It does nothing about variables you did not record, such as where on the ship a person was when the ship struck the iceberg. A table of survival rates describes who survived. It does not establish why.
Small groups
Every mean is an estimate from the rows in that group. A group of 10 rows gives a rate that can swing wildly if two passengers had gone the other way. Larger groups give steadier rates.
Add a rough uncertainty range to every group rate. A standard approximation for a proportion p from n rows is a standard error of sqrt(p * (1 - p) / n). A range of about 1.96 standard errors either side gives an approximate 95% interval.
import numpy as np
import pandas as pd
df = pd.read_csv("train.csv")
df["AgeGroup"] = pd.cut(
df["Age"],
bins=[0, 12, 18, 40, 60, 120],
labels=["child", "teen", "adult", "middle_aged", "senior"],
)
stats = df.groupby("AgeGroup", observed=True)["Survived"].agg(["count", "mean"])
stats["se"] = np.sqrt(stats["mean"] * (1 - stats["mean"]) / stats["count"])
stats["low"] = (stats["mean"] - 1.96 * stats["se"]).clip(lower=0)
stats["high"] = (stats["mean"] + 1.96 * stats["se"]).clip(upper=1)
print(stats.round(2))Read the low and high columns. Wide ranges mean the rate is poorly pinned down, and two groups whose ranges overlap heavily should not be called different on the strength of the means alone. The senior group is small, so its range is wide.
The normal approximation behaves badly when n is very small or when p is close to 0 or 1. A group of five passengers with all five surviving gives a standard error of zero, which is clearly wrong. Treat the formula as a warning light for small groups, not as a precise result. A Wilson interval, available in statsmodels, is a better choice when you need accuracy.
Small groups multiply as you add keys. Grouping by class, sex, and age group splits 891 rows into 30 cells, and some cells will hold only a handful of passengers. Print count every time.
Other traps worth naming
- Binning choices change the story. Different
binsinpd.cutmove people between groups. Try a second set of cut points and see whether the pattern holds. - Many comparisons produce false alarms. If you look at 30 subgroups, a few will look striking by chance.
- This is one dataset of one event. The
train.csvfile is also only a subset of the full passenger list, so a rate here is not a rate for everyone aboard. - Correlation of 0 does not mean "no relationship". Pearson correlation measures straight-line association. It also ignores non-numeric columns such as
Sex, unless you encode them.
A habit for each result
For each result you are about to record, ask:
- Which rows were left out, and do they differ from the rows kept?
- What else changes along with the grouping variable?
- How many rows stand behind each number?
Write the answers next to the finding. The next chapter turns this into a short written record.
Exercise
Passengers with a missing Age survived at about 29%, against about 41% for passengers with a known Age. A colleague concludes "being old caused lower survival, so the missing ages must be mostly elderly." Name two problems with this reasoning and one check you could run in pandas.
Show answer
First, the claim assumes missing ages are elderly, but nothing in the data says so. An age is missing, so you cannot know it. The crosstab of Pclass against AgeMissing shows that most missing ages are in third class, which had low survival for reasons connected to class. Second, even if missingness correlates with lower survival, that does not show age caused it. Class (and sex mix) is a confounder. A check: run df.groupby(["Pclass", "AgeMissing"])["Survived"].agg(["count", "mean"]) and see whether the survival gap between missing and known ages shrinks once class is held fixed.
Exercise
A group has count 8 and a survival mean of 0.75, while another has count 400 and a mean of 0.70. Which rate do you trust more, and what would you add to the table to show this?
Show answer
Trust the rate from 400 rows more. The rate from 8 rows can change by 0.125 with a single passenger. Add a standard error column, sqrt(p * (1 - p) / n), and low and high columns of mean minus and plus 1.96 times that, so the wide range for the small group is visible.