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 that you have already created the AgeGroup column with pd.cut. It covers groupby, aggregation with agg, and the checks that keep group comparisons honest.
Why compare groups
A single overall number hides differences. In the Titanic data, about 38% of passengers in the training file survived. That figure says nothing about whether survival differed by sex, ticket class, or age. Comparing groups answers that kind of question: split the rows into groups, compute a summary for each group, and put the results side by side.
pandas implements this with groupby, which follows a split, apply, combine pattern.
- Split: rows are divided into groups by the values of one or more key columns.
- Apply: a function (mean, count, sum, and so on) runs on each group.
- Combine: the per-group results are assembled into a Series or DataFrame indexed by the group keys.
One key, one column
The simplest comparison groups by one column and summarizes another.
import pandas as pd
df = pd.read_csv("train.csv")
print(df.groupby("Sex")["Survived"].mean())df.groupby("Sex") creates a lazy GroupBy object. Nothing is computed until you select a column and call an aggregation. Selecting ["Survived"] gives a per-group Series, and .mean() reduces each group to one number.
Survived is coded 0 or 1, so its mean is the fraction of 1s, which is the survival rate. This trick works for any 0/1 column. The result shows that women survived at a much higher rate than men (roughly 74% versus 19%).
The output is a Series whose index is the group key (female, male). Keys are sorted by default. Pass sort=False if you want them in order of first appearance.
Several keys
Pass a list to group by combinations of columns.
print(df.groupby(["Pclass", "Sex"])["Survived"].mean())The result has a MultiIndex with one level per key. Each row is a combination such as (1, "female"). Six groups appear here: three classes times two sexes.
Use .unstack() to turn the inner level into columns, which is often easier to read.
rates = df.groupby(["Pclass", "Sex"])["Survived"].mean().unstack()
print(rates.round(2))Now the rows are classes and the columns are sexes. Reading across a row compares sexes within one class. Reading down a column compares classes within one sex.
Reporting the size of each group
A rate means little without the number of rows behind it. Use agg with a list of function names to compute several summaries at once.
by_class_sex = df.groupby(["Pclass", "Sex"])["Survived"].agg(["count", "mean"])
print(by_class_sex)Here count is the number of non-missing Survived values in each group, and mean is the survival rate. Reporting both lets you see that, for example, a group with 30 passengers gives a much less stable rate than a group with 300.
Count versus size
count excludes missing values in the column you aggregate. size counts all rows in the group, missing or not.
| Method | Counts | Missing values |
|---|---|---|
| `count()` | Non-missing values in each column | Excluded |
| `size()` | Rows in each group | Included |
Survived has no missing values, so the two agree here. They would differ for Age, which has missing entries. When you want "how many passengers are in this group", size() is the safer choice.
Named aggregation
When you summarize several columns, named aggregation gives you readable output column names.
summary = df.groupby("Pclass").agg(
passengers=("PassengerId", "size"),
survival_rate=("Survived", "mean"),
median_age=("Age", "median"),
mean_fare=("Fare", "mean"),
)
print(summary.round(2))Each keyword is the new column name. Each value is a tuple of the source column and the aggregation. The result is a flat DataFrame, with no MultiIndex in the columns.
Note that median_age ignores missing ages. Each group's median rests on fewer rows than passengers shows.
Grouping by a derived column
The AgeGroup column from the previous chapter is a categorical column created by pd.cut. You can group by it like any other.
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"]))Two details matter here.
- Passengers with a missing
Agehave a missingAgeGroup.groupbydrops rows whose key is missing by default, so these passengers do not appear in any group. Their absence is silent. Compare the total of thecountcolumn with the number of rows indfto see how many were left out. - For categorical keys,
observed=Truelimits the output to categories that actually occur. Withobserved=False, pandas also lists empty categories. Recent pandas versions are moving the default towardobserved=True, so setting it explicitly keeps your output stable across versions.
To keep the missing-key rows as their own group, pass dropna=False.
print(df.groupby("AgeGroup", observed=True, dropna=False)["Survived"].agg(["count", "mean"]))A group labeled NaN now appears. You can compare its survival rate with the others, which tells you whether passengers with unknown age differ from those with known age.
Looking at the groups themselves
When a result looks surprising, inspect the underlying rows rather than trusting the summary.
groups = df.groupby("Pclass")
print(groups.size())
print(groups.get_group(1).head())get_group returns the rows of one group as a DataFrame. This is useful for spot checks, for example confirming that the first-class group really contains what you expect.
Common errors
- Forgetting the column selection.
df.groupby("Sex").mean()tries to average every column and raises aTypeErroron text columns in current pandas. Select the column you need first, or passnumeric_only=True. - Writing
df.groupby("Sex", "Pclass"). The second positional argument is not a second key. Pass a list:df.groupby(["Sex", "Pclass"]). - Reading a rate without its count. A rate of 100% on 3 passengers is not evidence of anything.
- Assuming missing keys are included. They are dropped unless you set
dropna=False. - Treating a MultiIndex result like a flat table. Use
.reset_index()to turn the index levels back into ordinary columns when you need to filter, merge, or plot the result.
flat = by_class_sex.reset_index()
print(flat[flat["count"] >= 50])Reading the results with care
Group comparisons describe the data you have. They do not explain it.
- Confounding. Class and sex are tangled up with age, fare, and where a passenger boarded. A difference between two groups may reflect a third variable. Grouping by two keys, as above, is a first step toward separating them.
- Small groups. When a group has few rows, its mean moves a lot if a handful of passengers change. Report counts and be cautious with groups under a few dozen rows.
- Missing data. A comparison on
Ageonly covers passengers whose age is known. If missingness is related to class or survival, the comparison can mislead.
Exercises
Exercise
Write code that reports, for each combination of Embarked and Pclass, the number of passengers (including any with missing Age) and the mean Fare, as one flat DataFrame with columns Embarked, Pclass, passengers, and mean_fare. Which pandas argument decides whether passengers with a missing Embarked value appear?
Show answer
df.groupby(["Embarked", "Pclass"], dropna=False).agg(passengers=("PassengerId", "size"), meanfare=("Fare", "mean")).resetindex(). The dropna argument of groupby decides it: with the default dropna=True, rows with a missing Embarked are left out, and with dropna=False they form their own group. Using size rather than count makes the passenger total include rows with missing values in other columns.
Exercise
A groupby on AgeGroup shows a "child" survival rate of 0.58 with a count of 69, and a "senior" rate of 0.23 with a count of 22. Name two reasons to be careful before concluding that age alone drove these differences.
Show answer
First, the senior group is small (22 rows), so its rate could shift a lot with a few passengers. Second, age is confounded with other variables such as class and sex, and passengers with a missing Age are dropped from these groups by default, so the comparison covers only those with a known age. Grouping by AgeGroup together with Pclass or Sex, and checking the dropped rows with dropna=False, would test these concerns.