Relationships in Data¶
Last week we described one variable at a time. Decisions usually turn on relationships: does food sell differently in each branch, do bigger baskets come with more drinks, do loyalty-app users spend more? This reading shows the tools for each kind of pair of variables, and the two traps that catch even experienced analysts: confounding and Simpson’s paradox.
After this reading you can:
build a crosstab and choose between row and column percentages;
summarise data with a pivot table and with
groupby;compare a numerical variable across groups with side-by-side box plots;
read a scatterplot, and explain why correlation is preferred to covariance;
explain why correlation is not causation, and spot Simpson’s paradox.
Textbook: Albright & Winston, Chapter 3.
The data¶
Two Qahwa House datasets:
orders: a sample of 10,200 receipts from 2025, one row per order: branch, hour, whether the customer used the loyalty app, the drinks and food bought, and the amounts in SAR;sales: the daily sales by branch and product from Week 1.
import pandas as pd
BASE = "https://chebil.github.io/BusinessDecision/data/"
def load(name):
"""Read a course dataset from the website, or from a local copy of the repository."""
try:
return pd.read_csv(BASE + name)
except Exception: # offline, or working from a copy of the course repository
return pd.read_csv("../data/" + name)
orders = load("qahwa_orders_2025.csv")
sales = load("qahwa_sales_2025.csv")
orders.head()1. Two categorical variables: crosstabs¶
A crosstab (contingency table) counts the observations in each combination of two categories. pd.crosstab builds it; margins=True adds the totals.
pd.crosstab(orders["branch"], orders["app_user"], margins=True)Counts are hard to compare because the branches differ in size. Percentages fix that, but which percentages depends on the question:
Row percentages (
normalize="index") answer: within each branch, what share of orders come from app users?Column percentages (
normalize="columns") answer: of all app-user orders, what share come from each branch?
row_pct = pd.crosstab(orders["branch"], orders["app_user"], normalize="index") * 100
col_pct = pd.crosstab(orders["branch"], orders["app_user"], normalize="columns") * 100
print("Row percentages: share of each branch's orders\n", row_pct.round(1), "\n")
print("Column percentages: where each group orders\n", col_pct.round(1))Row percentages: share of each branch's orders
app_user 0 1
branch
Al Faisaliyah 79.0 21.0
Corniche 79.8 20.2
Olaya 84.5 15.5
University 24.8 75.2
Column percentages: where each group orders
app_user 0 1
branch
Al Faisaliyah 25.0 14.2
Corniche 29.9 16.1
Olaya 36.5 14.3
University 8.6 55.4
Three quarters of the University branch’s orders come from app users (it serves students who use the app’s offers), against 15 to 21% elsewhere; and more than half of all app-user orders are placed at the University branch. Remember this: it matters in section 5.
2. Pivot tables¶
A pivot table summarises a numerical variable by one or two categorical variables: rows, columns, and a summary (sum, mean, count). In pandas, pivot_table does it in one line; groupby followed by unstack gives the same result.
How does revenue per branch-day vary by weekday and category?
sales["revenue"] = sales["units"] * sales["price_paid"]
daily = sales.groupby(["date", "weekday", "branch", "category"], as_index=False)["revenue"].sum()
pivot = daily.pivot_table(index="weekday", columns="category", values="revenue", aggfunc="mean")
order = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
pivot = pivot.loc[order]
pivot.round(0)# the same table with groupby
same = daily.groupby(["weekday", "category"])["revenue"].mean().unstack().loc[order]
print("identical:", (same.round(6) == pivot.round(6)).all().all())identical: True
Friday is the best day for both drinks and food, and Monday and Tuesday the weakest, with Thursday to Saturday about 30% above them. A pivot table is the quickest way to see such a pattern; Week 4’s Streamlit app puts one behind a few filters.
3. A numerical variable across groups¶
To compare basket size across branches, a single average hides the spread. Side-by-side box plots show the median, the quartiles and the outliers of each group at once.
import matplotlib.pyplot as plt
branches = ["Olaya", "Corniche", "Al Faisaliyah", "University"]
fig, ax = plt.subplots(figsize=(7, 3.6))
ax.boxplot([orders.loc[orders["branch"] == b, "basket_sar"] for b in branches], showfliers=True)
ax.set_xticks(range(1, 5), branches)
ax.set_ylabel("Basket (SAR)")
ax.set_title("Baskets are smallest at the University branch")
ax.grid(axis="y", alpha=0.3)
plt.show()
orders["has_food"] = orders["food_items"] > 0
orders.groupby("branch")[["basket_sar", "food_sar"]].mean().join(orders.groupby("branch")["has_food"].mean().rename("share_with_food")).round(2)
The University branch stands out: its baskets are smaller, and only 17% of its orders include food, against 40% to 47% in the other branches, so food brings in 2.88 SAR per order there against 6.39 to 7.53 SAR elsewhere. That is a candidate for the manager’s attention, and the lab asks you what to do about it.
4. Two numerical variables: scatterplots, covariance and correlation¶
A scatterplot shows one point per observation. Does the basket grow with the number of food items?
fig, ax = plt.subplots(figsize=(6, 3.6))
jitter = (orders["food_items"] + (orders.index % 7 - 3) * 0.04)
ax.scatter(jitter, orders["basket_sar"], s=6, alpha=0.25)
ax.set_xlabel("Food items in the order")
ax.set_ylabel("Basket (SAR)")
ax.grid(alpha=0.3)
plt.show()
nums = orders[["drinks", "food_items", "basket_sar"]]
print("covariance\n", nums.cov().round(2), "\n")
print("correlation\n", nums.corr().round(2))
covariance
drinks food_items basket_sar
drinks 0.42 -0.01 4.58
food_items -0.01 0.45 5.93
basket_sar 4.58 5.93 145.41
correlation
drinks food_items basket_sar
drinks 1.00 -0.02 0.59
food_items -0.02 1.00 0.74
basket_sar 0.59 0.74 1.00
Covariance measures whether two variables move together, but its size depends on the units: measure the basket in halalas instead of riyals and the covariance with food items is 100 times larger, while nothing about the relationship changed. Correlation divides covariance by both standard deviations, so it has no units and always lies between −1 and +1:
halalas = orders["basket_sar"] * 100
print("covariance, SAR: ", round(orders["food_items"].cov(orders["basket_sar"]), 2))
print("covariance, halalas: ", round(orders["food_items"].cov(halalas), 2))
print("correlation, SAR: ", round(orders["food_items"].corr(orders["basket_sar"]), 2))
print("correlation, halalas:", round(orders["food_items"].corr(halalas), 2))covariance, SAR: 5.93
covariance, halalas: 593.2
correlation, SAR: 0.74
correlation, halalas: 0.74
Two cautions. Correlation measures only a linear relationship: a perfect U-shape can have . And it summarises a whole scatterplot in one number, so always look at the plot as well.
5. Correlation is not causation¶
At the Olaya branch, compare the daily sales of Iced Latte and Spanish Latte, then the monthly totals:
units = sales.pivot_table(index=["date", "branch"], columns="product", values="units", aggfunc="sum").reset_index()
olaya = units[units["branch"] == "Olaya"].copy()
olaya["month"] = pd.to_datetime(olaya["date"]).dt.month
monthly = olaya.groupby("month")[["Iced Latte", "Spanish Latte"]].sum()
print("daily r: ", round(olaya["Iced Latte"].corr(olaya["Spanish Latte"]), 2))
print("monthly r:", round(monthly["Iced Latte"].corr(monthly["Spanish Latte"]), 2))daily r: 0.25
monthly r: -0.46
Day by day the two move together (r = +0.25); month by month they move apart (r = −0.46). Neither product causes the other’s sales. Two third variables drive them: busy days and promotion days lift every product at once, and the summer heat pushes iced drinks up and hot drinks down. A variable that drives both of the variables we compare is a confounder (lurking variable).
You met one already in Lab 1: promotions fell more often on busy Thursdays, which flattered the promotion days. Only an experiment (promotion days chosen at random, and enough of them) or careful comparisons within groups (same weekday) separate the effect of a decision from its confounders.
6. Simpson’s paradox¶
Do loyalty-app users spend more per order?
overall = orders.groupby("app_user")["basket_sar"].mean().rename({0: "others", 1: "app users"})
within = orders.pivot_table(index="branch", columns="app_user", values="basket_sar", aggfunc="mean").rename(columns={0: "others", 1: "app users"})
within["difference"] = within["app users"] - within["others"]
print("Overall (SAR per order)\n", overall.round(2), "\n")
print("Within each branch (SAR per order)\n", within.round(2))Overall (SAR per order)
app_user
others 22.53
app users 21.03
Name: basket_sar, dtype: float64
Within each branch (SAR per order)
app_user others app users difference
branch
Al Faisaliyah 22.29 25.28 2.99
Corniche 23.98 26.32 2.35
Olaya 23.33 26.67 3.34
University 14.76 16.96 2.20
Overall, app users spend less (21.03 against 22.53 SAR). Within every branch, they spend more, by 2.20 to 3.34 SAR. Both statements are true. This reversal is Simpson’s paradox, and section 1 explains it: most app-user orders come from the University branch, where every basket is small. The overall comparison mixes “app or not” with “which branch”.
The decision at stake shows why it matters. Judged on the overall figure, the manager might cut the app’s budget; judged branch by branch, the app is associated with bigger baskets everywhere. Neither table proves the app causes bigger baskets (app users may simply be keener customers), but the branch-by-branch comparison is the fair one.
Rule of thumb: before comparing two groups overall, ask whether they are spread differently over a third variable that also affects the outcome. If they are, compare within its levels.
Check your understanding¶
You want to know which branch app users favour. Row or column percentages of
crosstab(branch, app_user)?Why is correlation preferred to covariance for comparing relationships?
Ice-cream sales and drowning deaths are positively correlated across months. Name a confounder.
Hospital A has a lower overall survival rate than hospital B, yet higher survival for both mild and severe cases. How can that be?
A dashboard shows that orders with food have bigger baskets. Can we conclude that pushing food raises spending?
Answers. 1. Column percentages: they spread each group (app users) over the branches. 2. It has no units and lies between −1 and +1, so relationships measured in different units can be compared. 3. Summer heat (temperature): it raises both. 4. Simpson’s paradox: hospital A treats far more severe cases, which have lower survival everywhere; the case mix is the confounder. 5. Not from this alone: the basket includes the food itself, and customers who buy food may differ (hungrier, in groups). A test, such as a meal-deal offer in some weeks, would measure the effect.