Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Relationships in Data

Open In Colab

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.

Loading...

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.

Loading...

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 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?

Loading...
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.

<Figure size 700x360 with 1 Axes>
Loading...

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?

<Figure size 600x360 with 1 Axes>
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:

r=cov(X,Y)sX sYr = \frac{\text{cov}(X, Y)}{s_X\, s_Y}
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 r=0r = 0. 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:

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 (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

  1. You want to know which branch app users favour. Row or column percentages of crosstab(branch, app_user)?

  2. Why is correlation preferred to covariance for comparing relationships?

  3. Ice-cream sales and drowning deaths are positively correlated across months. Name a confounder.

  4. Hospital A has a lower overall survival rate than hospital B, yet higher survival for both mild and severe cases. How can that be?

  5. 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.