Sub topic 10
Adding derived columns such as age groups
This chapter assumes you can load the Titanic CSV into a DataFrame called df, and that you know how to select columns and filter rows with boolean masks. It also assumes you have already looked at missing values, because Age has many of them.
Why derive a column
A derived column is a new column computed from existing ones. In exploration, the most common reason is to turn a continuous number into groups that are easier to compare. Survival rate for 891 individual ages is noisy. Survival rate for five age groups is readable.
The rule for this chapter: add new columns, and leave the raw columns alone. If you overwrite Age, you lose the original values and cannot redo the analysis with different groups.
Binning with pd.cut
pd.cut sorts numbers into intervals you define. You supply the bin edges and a label for each bin.
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"],
)
print(df["AgeGroup"].value_counts(dropna=False))With five bins you need six edges, and you need exactly five labels. A mismatch raises a ValueError.
Two details matter here.
- Intervals are closed on the right by default. The bin
(12, 18]includes 18 but excludes 12, so a 12-year-old is achildand an 18-year-old is ateen. Passright=Falseto flip this. - A value outside every bin, or a missing value, becomes
NaNin the new column. Passengers with noAgeget noAgeGroup. Usingdropna=Falseinvalue_countsshows them as a separate count, so you do not forget them.
Deriving columns from other columns
Not every derived column needs bins. Arithmetic and comparisons also produce columns.
df["FamilySize"] = df["SibSp"] + df["Parch"] + 1
df["IsAlone"] = df["FamilySize"] == 1
df["AgeKnown"] = df["Age"].notna()
print(df[["FamilySize", "IsAlone", "AgeKnown"]].head())FamilySize counts the passenger plus siblings, spouses, parents, and children aboard. IsAlone is a boolean column. AgeKnown records which rows had a missing Age. Keeping that flag lets you later check whether passengers with missing ages differ from the rest, which is more honest than silently dropping them.
Checking your work
After creating a column, verify it before you rely on it.
- Compare counts. The group counts plus the missing count should equal the number of rows.
- Spot-check edges. Look at the rows whose
Ageis exactly 12, 18, or 40 and confirm they landed in the group you expected. - Confirm the raw column is unchanged.
print(df["AgeGroup"].value_counts(dropna=False).sum() == len(df))
print(df.loc[df["Age"].isin([12, 18, 40]), ["Age", "AgeGroup"]].drop_duplicates())Common errors
- Wrong number of labels. You need one fewer label than edges.
- Bins that miss values. If the first edge is
1, a baby aged0.42falls outside and becomesNaN. This is why the first edge above is0. - Overwriting the source. Writing
df["Age"] = pd.cut(...)destroys the numbers. Always assign to a new name. - Choosing bins after seeing results. Edges picked to make a pattern look strong can mislead. Pick them from meaningful ages first, then look.
Exercise
A passenger is exactly 18 years old. With bins=[0, 12, 18, 40, 60, 120] and the default settings of pd.cut, which bin does that passenger fall into, and what argument would move them to the next bin?
Show answer
They fall in the bin (12, 18], so they are a "teen", because intervals include their right edge by default. Passing right=False makes intervals include the left edge instead, which puts an 18-year-old into [18, 40), the "adult" group.
Exercise
Write one line that adds a boolean column called IsChild that is True for passengers younger than 13, and explain what value it holds for a passenger whose Age is missing.
Show answer
df["IsChild"] = df["Age"] < 13. A missing Age compared with a number gives False, not missing, so these passengers are counted as not children. If that matters, keep the AgeKnown flag or use the AgeGroup column, which stays NaN.