Sub topic 11
Comparing groups with groupby
This chapter assumes you can load train.csv into a DataFrame called df, filter rows with boolean masks, and have already created the AgeGroup column with pd.cut. Here you compare subgroups of passengers. You will use groupby to compute survival rates and check how many passengers each rate is based on.
The split-apply-combine model
groupby works in three steps. It splits the rows into groups by the values of one or more columns. It applies a function, such as a mean or a count, to each group. It combines the results into a new Series or DataFrame indexed by the group keys.
Survival rate by one column
Survived is 0 or 1, so its mean is the share of passengers who survived. That makes mean the natural summary here.
import pandas as pd
df = pd.read_csv("train.csv")
print(df.groupby("Sex")["Survived"].mean())The expression df.groupby("Sex") makes the groups. Selecting ["Survived"] picks the column to summarize. .mean() is the function applied to each group.
Two keys and several statistics
Pass a list to group by more than one column. Use agg to compute several statistics at once.
by_class_sex = df.groupby(["Pclass", "Sex"])["Survived"].agg(["count", "mean"])
print(by_class_sex)The result has a two-level index, one level for Pclass and one for Sex. Always report count next to mean. A rate of 100% means little if it comes from three passengers.
Grouping by a derived column
The AgeGroup column from the previous chapter is categorical. Grouping by a categorical column shows every category by default, including empty ones. Passing observed=True limits the output to categories that actually occur in the data.
df["AgeGroup"] = pd.cut(
df["Age"],
bins=[0, 12, 18, 40, 60, 120],
labels=["child", "teen", "adult", "middle_aged", "senior"],
)
print(df.groupby("AgeGroup", observed=True)["Survived"].agg(["count", "mean"]))Rows with a missing Age have a missing AgeGroup. By default, groupby drops rows whose key is missing, so those passengers vanish from this table. Add up the count column and compare it with len(df). The gap is the number of passengers with no age.
Common errors
- Forgetting the aggregation.
df.groupby("Sex")alone only creates a grouping object. Nothing is computed until you callmean,agg, or similar. - Averaging a column that is not numeric. Taking the mean of text columns raises an error in current pandas. Select the column you want first, as in
["Survived"]. - Reading a rate without its count. Small groups produce extreme and unstable rates.
- Losing missing keys silently. Use
dropna=Falseingroupbyif you want a group for missing values.
print(df.groupby("AgeGroup", observed=True, dropna=False)["Survived"].agg(["count", "mean"]))Exercise
Exercise
Write code that shows the number of passengers and the survival rate for each value of Embarked, including passengers whose port is missing. Why is the count column needed?
Show answer
Use df.groupby("Embarked", dropna=False)["Survived"].agg(["count", "mean"]). The dropna=False argument keeps the group for missing ports. The count column shows how many passengers each rate rests on. The missing-port group has only two passengers, so its rate is unreliable.