Sub topic 3
Comparing Groups with `groupby`
This chapter assumes you can load a CSV into pandas and understand basic variables, functions, and Boolean conditions. The examples use a Titanic DataFrame named df, with columns such as Survived, Pclass, Sex, Age, and Fare.
Comparing groups with `groupby`
groupby splits rows into groups, applies a calculation to each group, and returns the results. Since Survived contains 0 or 1, its mean is the proportion of passengers who survived.
import pandas as pd
df = pd.read_csv("train.csv")
by_class_sex = (
df.groupby(["Pclass", "Sex"])["Survived"]
.agg(count="count", survival_rate="mean")
)
print(by_class_sex)The count column gives context for each rate. A rate based on 10 passengers deserves less confidence than one based on 300 passengers.
Plotting distributions and group comparisons
A distribution plot shows how values are spread. A group comparison shows how a measure changes between categories.
import matplotlib.pyplot as plt
df["Age"].plot.hist(bins=30, title="Passenger age distribution")
plt.xlabel("Age")
plt.show()
df.groupby("Pclass")["Survived"].mean().plot.bar(
title="Survival rate by passenger class"
)
plt.ylabel("Survival rate")
plt.show()The histogram may reveal concentration or unusual values. The bar chart makes differences between classes easier to compare.
Checking correlations between numeric columns
Correlation measures how two numeric variables move together in a linear pattern. Its value ranges from -1 to 1. Values near 1 indicate a positive association, values near -1 indicate a negative association, and values near 0 indicate little linear association.
corr = df.corr(numeric_only=True)
print(corr["Survived"].sort_values(ascending=False))Correlation does not prove that one variable causes another. It also may miss curved relationships.
Reading results carefully
Missing values can change group sizes and bias comparisons. Confounding occurs when another variable helps explain an observed difference. For example, class and sex may both relate to survival, so comparing only one variable can hide important structure.
Check counts beside every rate. Investigate groups with very few rows. Avoid treating an association as a causal explanation.
| Finding | Caveat to record |
|---|---|
| First class has a higher survival rate | Class, sex, age, and missing values may affect the comparison |
Writing down findings and next questions
Record the pattern, its evidence, and its limits. Then write a question that the current analysis cannot answer. For example: “Survival rates differ by class, but class may be confounded with sex and age. Next, compare class and sex together.”
Exercise
Why should a survival rate be reported with a group count?
Show answer
The count shows how much evidence supports the rate and identifies small groups whose estimates may be unstable.