Sub topic 10
Relationships between pairs of variables
After the univariate pass, you know what each column looks like on its own. This chapter covers the next step: asking how two columns relate. It assumes you can use pandas groupby, have the df from the cleaning step, and know the difference between mean and median and between correlation and causation. The examples use the orders data from earlier chapters. Besides order_date, region, and amount, they assume a numeric quantity column. Substitute your own columns if they differ.
Pick the method from the types of the pair
The types of the two columns decide which summary and which plot fit. Choosing by type keeps the section systematic. Without that, you tend to plot whatever pair comes to mind first.
| Pair type | Summary | Plot |
|---|---|---|
| numeric, numeric | Pearson and Spearman correlation | Scatter plot |
| numeric, category | `groupby` with count, mean, median | Grouped box plot |
| category, category | `pd.crosstab` with row percentages | Stacked or grouped bar chart |
| numeric, time | Resampled median or sum | Line plot |
Choose pairs from the questions you wrote at the start of the notebook. Do not loop over every column pair and plot all of them. That approach produces a large grid of plots, and a few of them will look like patterns by chance. The pitfalls chapter returns to this problem.
Numeric against numeric
Start with a scatter plot, then compute the correlation. The plot shows the shape of the relationship, and the number is only a summary of it.
fig, ax = plt.subplots(figsize=(5, 4))
ax.scatter(df["quantity"], df["amount"], alpha=0.3, s=10)
ax.set_title("Order amount versus quantity")
ax.set_xlabel("Quantity")
ax.set_ylabel("Amount")
plt.tight_layout()
plt.show()
pair = df[["quantity", "amount"]]
print("Pearson: ", round(pair.corr(method="pearson").iloc[0, 1], 3))
print("Spearman:", round(pair.corr(method="spearman").iloc[0, 1], 3))The alpha=0.3 setting makes points semi-transparent, so dense regions look darker. With thousands of orders, opaque points merge into one blob and hide the density.
Compute both coefficients because they answer different questions:
- Pearson measures straight-line association. A few extreme values can move it a lot.
- Spearman works on ranks. It captures any consistently rising or falling relationship, and it resists outliers.
If the two differ a lot, look at the scatter plot for outliers or a curve before you trust either number. A correlation near zero does not mean the variables are unrelated. A U-shaped relationship can have a Pearson correlation near zero.
Numeric against category
This pair type is the most common in business data, and it is the one the chapter on plots introduced. The grouped box plot shows the spread. Pair it with a table, so the sample sizes and exact values are visible.
by_region = (
df.groupby("region")["amount"]
.agg(["count", "mean", "median", "std"])
.round(2)
.sort_values("median", ascending=False)
)
display(by_region)Read the count column first. A region with 12 orders and a high mean is weak evidence, however striking its box looks. Then compare mean and median within each group. A large gap in one group but not the others means that group's skew differs, and that is a finding to log.
If the groups overlap heavily in the box plot, the difference between the group means may be noise. At this stage, treat a visible difference as a hypothesis. Testing it formally belongs after the exploration, on data you did not use to find the pattern.
Category against category
For two categorical columns, count the combinations with a crosstab. To have a second category, this example bins amount into three equal-sized groups. Ranking first avoids errors when many values repeat.
band = pd.qcut(
df["amount"].rank(method="first"),
q=3,
labels=["low", "mid", "high"],
)
counts = pd.crosstab(df["region"], band)
shares = pd.crosstab(df["region"], band, normalize="index").round(3)
display(counts)
display(shares)Raw counts mostly reflect how big each region is. Row-normalized shares answer the more useful question: within each region, what fraction of orders is low, mid, or high? With normalize="index", each row sums to 1. Use normalize="columns" when the question runs the other way. State in your markdown which direction you normalized, because the two readings are easy to confuse.
Numeric against time
A date column is a special case because order matters. Aggregate into regular periods before plotting, since raw daily points are usually too noisy to read.
monthly = df.set_index("order_date")["amount"].resample("MS").agg(["count", "median"])
fig, ax = plt.subplots(figsize=(8, 3.5))
monthly["median"].plot(ax=ax, marker="o")
ax.set_title("Median order amount by month")
ax.set_xlabel("Month")
ax.set_ylabel("Median amount")
plt.tight_layout()
plt.show()
display(monthly["count"].describe())"MS" groups by month start. Check monthly["count"] as well. A partial first or last month, or a month with very few orders, produces a dip or spike that comes from the data collection and says nothing about customers.
Going beyond two variables
Often a pair relationship changes once you add a third variable. Add the third variable as a grouping and compare the pair within each group. This version checks whether the amount-quantity relationship is the same in every region.
within = (
df.groupby("region")[["quantity", "amount"]]
.apply(lambda g: g["quantity"].corr(g["amount"], method="spearman"))
.round(3)
.rename("spearman_quantity_amount")
)
display(within)If the overall correlation is positive but the per-region values are weak or mixed, the overall number mostly reflects differences between regions. This effect is often called Simpson's paradox. When the grouped result disagrees with the pooled one, report both.
A correlation matrix over all numeric columns gives a quick overview. Use df.select_dtypes("number").corr(method="spearman"). Treat it as a map for choosing which pairs to plot next, not as a result.
Common errors in bivariate work
- Reading the coefficient without the plot. Very different shapes can share the same Pearson value. Always look at the scatter plot.
- Ignoring group sizes. Group means with tiny counts are unstable. Show
countin every grouped table. - Using the wrong normalization. Raw counts, row shares, and column shares answer three different questions. Label which one you show.
- Silently dropping rows.
corrandboxplotskip missing values. Ifquantityis missing for many rows, the correlation describes a subset. Printpair.dropna().shapenext to the result. - Claiming cause. A relationship in observational data shows association. Word findings as "orders with higher quantity tend to have higher amounts", not "quantity raises amount".
Log each relationship as you find it
After each pair you explore, add a short markdown cell with the evidence, hypothesis, and next step, as in the findings log. For example:
### Finding: amount rises with quantity, but unevenly across regions
- **Evidence:** Spearman 0.62 overall; per-region values range from 0.35 to 0.71.
- **Hypothesis:** pricing or product mix differs by region.
- **Next step:** check product category once it is added to the data.Write the numbers into the cell from the output above it. If you rerun the notebook with different data, update the text too.
Exercise
A scatter plot of quantity against amount shows a clear curve that rises and then flattens. Pearson is 0.45 and Spearman is 0.78. Why do the two differ, and which should you report, and with what caveat?
Show answer
Pearson measures only straight-line association, so the flattening part of the curve lowers it. Spearman uses ranks, so it captures any consistently increasing relationship, curved or not. Report Spearman as the stronger summary of the monotonic trend, show the scatter plot, and state that the relationship is not linear so a straight-line summary would understate it.
Exercise
A crosstab of region by amount band shows that the North region has 400 high-band orders and the South region has 150. Why is this not enough to say North customers spend more, and what would you compute instead?
Show answer
North may simply have more orders in total. Compute row-normalized shares with pd.crosstab(df["region"], band, normalize="index") to see what fraction of each region's orders is in the high band, and check the group counts before drawing a conclusion.