Sub topic 10
Adding Derived Columns Such as Age Groups
A derived column is a new column computed from existing ones. In exploratory analysis, derived columns turn raw values into forms that are easier to compare, count, and plot. This chapter builds an age-group column with pd.cut, then covers related techniques and the errors that most often appear.
Prerequisites
This chapter assumes you have already:
- Loaded
train.csvinto a DataFrame nameddf. - Checked missing values and found that
Agehas many of them. - Used boolean masks and
locto select rows and columns.
You also need basic Python (lists, dictionaries, functions) and pandas with matplotlib installed.
Why derive columns instead of editing the originals
Raw Age has dozens of distinct values. Comparing survival at age 23 with survival at age 24 rests on a handful of passengers each, so the result is noisy. Grouping ages into a few ranges gives groups large enough to compare.
Follow one rule: add a new column and leave the raw one unchanged. If you overwrite Age with a category, you lose the original numbers. You cannot rebuild them, and you cannot try different bin edges later. A derived column can be dropped and recomputed at any time.
Binning with pd.cut
pd.cut assigns each numeric value to an interval that you define. You supply the bin edges and, optionally, 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))Several details matter here.
- Edges versus bins. Five bins need six edges. The edges
0, 12, 18, 40, 60, 120create the intervals (0, 12], (12, 18], (18, 40], (40, 60], and (60, 120]. - Right edges are inclusive by default. A passenger aged exactly 12 is a
child. A passenger aged 12.5 is ateen. Passright=Falseto make the left edge inclusive instead. - The lowest edge is exclusive. A value equal to the first edge, here 0, falls outside every bin. Titanic ages include fractional values below 1 (for example 0.42), which are greater than 0 and so are safely inside the first bin. If your data could contain an exact 0, add
include_lowest=Trueor start the edges below 0. - Values outside all bins become missing. Any age above 120 or below 0 would turn into
NaN. - Missing input gives missing output. Passengers with no
Ageget noAgeGroup. That is whydropna=Falseinvalue_countsis important: it shows aNaNrow so you can see how many passengers have no group.
The result has the category dtype, which stores each label once and refers to it by integer code. This saves memory and keeps the labels in the order you gave them.
print(df["AgeGroup"].dtype)
print(df["AgeGroup"].cat.categories.tolist())The first line prints category. The second prints the labels in your order, from child to senior. That order is why the groups sort and plot logically instead of alphabetically.
A diagram of the process
Equal-count bins with pd.qcut
pd.cut uses edges you choose, so bin sizes can be very uneven. pd.qcut instead chooses edges so each bin holds roughly the same number of rows. This suits skewed columns such as Fare, where most passengers paid little and a few paid a lot.
df["FareBand"] = pd.qcut(
df["Fare"],
q=4,
labels=["low", "mid_low", "mid_high", "high"],
)
print(df["FareBand"].value_counts())Each band holds about a quarter of the passengers. The trade-off is that the edges are data-dependent. A band called high is defined by this dataset's quartiles, not by a fixed price. Use cut when the ranges have meaning, such as "under 18". Use qcut when you want balanced groups.
If many values repeat, qcut can fail with a "Bin edges must be unique" error. Passing duplicates="drop" removes the repeated edges, but you then get fewer bins than q. Combine it with labels=False or omit custom labels, because the label count must match the final bin count.
Other ways to derive a column
Binning is one of several patterns. Each one creates a new column and leaves the source columns alone.
Arithmetic on columns
Combine columns with ordinary operators. Pandas applies them row by row.
df["FamilySize"] = df["SibSp"] + df["Parch"] + 1
df["IsAlone"] = df["FamilySize"] == 1SibSp counts siblings and spouses aboard, Parch counts parents and children aboard, and the + 1 adds the passenger. The second line produces a boolean column. Because True counts as 1 and False as 0, its mean is the share of passengers travelling alone.
Mapping values
Use map with a dictionary to recode a column.
df["Embarked_full"] = df["Embarked"].map(
{"C": "Cherbourg", "Q": "Queenstown", "S": "Southampton"}
)Any value not in the dictionary becomes NaN. This includes values that were already missing, so the new column has the same gaps as the old one.
Conditional values with numpy
For two or more cases, numpy.where and numpy.select are clearer than a loop.
import numpy as np
df["IsMinor"] = np.where(df["Age"] < 18, "minor", "adult")This example has a trap. A missing Age compares as False for < 18, so those passengers are labelled adult. The code runs without error and gives a wrong answer. A safer version keeps the gap.
df["IsMinor"] = np.where(
df["Age"].isna(), None,
np.where(df["Age"] < 18, "minor", "adult"),
)
print(df["IsMinor"].value_counts(dropna=False))Here missing ages stay missing, and the count shows them. Always ask what your rule does with NaN before trusting a derived column.
Checking a derived column
Never assume a derived column is right. Run three quick checks.
- Count the groups. Use
value_counts(dropna=False)and confirm that the total equalslen(df). - Check the missing count. The number of missing
AgeGroupvalues should equal the number of missingAgevalues. - Inspect the boundaries. Look at the minimum and maximum
Ageinside each group.
print(df["AgeGroup"].isna().sum() == df["Age"].isna().sum())
print(df.groupby("AgeGroup", observed=True)["Age"].agg(["min", "max", "count"]))The first line should print True. In the second, each group's min and max should fall within its bin edges. If a max sits above the upper edge, the bin definition is wrong.
Using the derived column in a comparison
A derived column pays off when you group by it. Because Survived is 0 or 1, its mean is the survival rate. Reporting count beside mean shows how many passengers each rate rests on.
print(df.groupby("AgeGroup", observed=True)["Survived"].agg(["count", "mean"]))The observed=True argument matters for categorical columns. Without it, older pandas versions list every category, including empty ones, and the behaviour of the default has changed across releases. Setting it explicitly keeps the output stable and silences warnings.
Notice that the count is smaller than 891. The passengers without an age are not in any group, so they do not appear in this table. A survival rate by age group describes only the passengers whose age is known. Whether those passengers differ from the others is a question to raise in your findings.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `ValueError: bins must increase monotonically` | Edges are not in ascending order | Sort the edges |
| `ValueError: Bin labels must be one fewer than the number of bin edges` | Label count does not match bin count | Use one fewer label than edges |
| `NaN` for a value that has an age | Value lies outside all bins or on the excluded lowest edge | Widen edges or use `include_lowest=True` |
| `SettingWithCopyWarning` | Assigning a column to a filtered slice | Call `.copy()` on the slice first |
| Group sizes look uneven | Edges chosen by hand | Check counts, or use `qcut` |
| Derived column has no gaps but `Age` does | Comparison rule treated `NaN` as `False` | Handle `isna()` explicitly |
Choosing bin edges
Edges are a modelling decision, not a fact about the data. Two analysts can pick different edges and see different survival rates for the "teen" group. Pick edges for a reason you can state, such as legal age or a natural life stage. Check that no group is tiny. Then try one or two alternative edge sets to see whether your conclusion survives. If the pattern disappears when you shift an edge by a few years, it is fragile. You can note that in your findings.
Exercise
You create df["IsMinor"] = np.where(df["Age"] < 18, "minor", "adult"). The column has 891 non-null values, but only 714 passengers have a known age. What went wrong, and how do you fix it?
Show answer
Comparing a missing Age with 18 gives False, so the 177 passengers with no age were labelled "adult". The column looks complete but is wrong for those rows. Fix it by checking df["Age"].isna() first and assigning a missing value for those rows (for example with a nested np.where), then confirm with value_counts(dropna=False) that the missing count equals the missing count of Age.
Exercise
You call pd.cut(df["Age"], bins=[0, 12, 18, 40, 60, 120], labels=["child", "teen", "adult", "middle_aged"]). What happens, and why?
Show answer
Pandas raises a ValueError because five bins need five labels, and only four were given. Add a fifth label such as "senior", or remove a bin edge so the counts match.