Sub topic 10
Relationships between pairs of variables
This chapter assumes you have a cleaned df from the cleaning step, with amount (numeric), region (text category), and order_date (datetime) columns. You should also know groupby and basic matplotlib.
Pick the tool from the pair of types
Univariate work told you what each column looks like alone. Bivariate analysis asks whether two columns move together. The right summary and plot depend on the types of the two columns.
Numeric by category
This is the most common pair in the orders data: does order amount differ by region? Start with numbers, then plot.
summary = (
df.groupby("region")["amount"]
.agg(["count", "mean", "median", "std"])
.round(2)
.sort_values("median", ascending=False)
)
display(summary)Report count next to every mean. A region with 12 orders and a high mean is weak evidence. The box plot from the previous chapter shows the same comparison visually, so use it to check that the table's differences are not caused by one extreme order.
Numeric by numeric
To see a trend over time, convert the date into a number and plot it against amount. Then compute a rank correlation.
df_t = df.assign(
days_since_start=(df["order_date"] - df["order_date"].min()).dt.days
)
fig, ax = plt.subplots(figsize=(6, 4))
ax.scatter(df_t["days_since_start"], df_t["amount"], alpha=0.3, s=10)
ax.set_title("Order amount over time")
ax.set_xlabel("Days since first order")
ax.set_ylabel("Amount")
plt.show()
rho = df_t["days_since_start"].corr(df_t["amount"], method="spearman")
print(f"Spearman correlation: {rho:.2f}")Order amounts are right-skewed, so Spearman is safer than the default Pearson. A few large orders can dominate Pearson. The low alpha makes overlapping points visible, which matters once you have thousands of rows.
Category by category
A crosstab counts how often two categories occur together. Normalizing by row shows the mix within each group.
df_m = df.assign(month=df["order_date"].dt.to_period("M").astype(str))
counts = pd.crosstab(df_m["region"], df_m["month"])
display(counts)
display(pd.crosstab(df_m["region"], df_m["month"], normalize="index").round(2))Going beyond two variables
When a pair looks interesting, add a third variable by splitting or coloring. For example, repeat the scatter plot per region. Do this only for a pair you already have a reason to examine. Every extra split makes groups smaller and patterns easier to invent.
Record the result
End each pair with a short markdown cell in the format from the findings log: observation, evidence, hypothesis, next step. For example: "Median amount is highest in the west region (table above, n = 340). Hypothesis: a product mix difference. Next step: check product category by region."
Common errors
- Comparing means from groups with very different counts.
- Using Pearson correlation on skewed data without looking at the scatter plot.
- Testing dozens of pairs and reporting only the striking ones. Some will look striking by chance.
- Forgetting that a crosstab of raw counts reflects group size. Normalize when you compare mixes.
Exercise
A crosstab of region by month shows that the "north" region has twice as many orders in March as in February. Why might this not mean north became more popular, and what would you compute next?
Show answer
March may have more days, or the other regions may have grown too, so the raw count mixes total volume with north's share. Compute the row- or column-normalized crosstab (for example normalize="columns" to get each region's share of a month's orders), and compare orders per day. Then record the result as a hypothesis in the findings log.