Lab 4 Solutions: Relationships and a First Streamlit App¶
These are the worked solutions, with outputs. Try the lab yourself first.
The question. The regional manager wants one dashboard to explore the orders, and one answer: which branch and category combination is underperforming, and what should we do about it?
How this lab works
Run the cells from top to bottom with Shift + Enter. Replace every
...with your code, then run the check cell under it.Extended track: after Part C, try the ★ challenges.
Submit before the next lab session: File → Download → Download .ipynb, plus your
qahwa_app.py.
You may use an AI assistant for code. If you do, add a short note at the end: what you asked, what you kept and what you changed.
# Run this cell once: it defines a small helper that checks your answers.
def check(label, condition):
print(("✅ " if condition else "❌ ") + label)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")
orders["has_food"] = orders["food_items"] > 0
orders.head()| Column | Meaning |
|---|---|
order_id, date, weekday, hour | the order and when it was placed |
branch, city | where |
app_user | 1 if the customer ordered through the loyalty app |
drinks, food_items | how many of each in the order |
drink_sar, food_sar, basket_sar | amounts paid in SAR (basket = drinks + food) |
Part A: Crosstabs and pivot tables¶
A1. A crosstab¶
Count the orders in each combination of branch and app_user with pd.crosstab. Store it in counts.
counts = pd.crosstab(orders["branch"], orders["app_user"])
countscheck("A1 one row per branch, one column per group", counts.shape == (4, 2))
check("A1 all orders counted", counts.values.sum() == len(orders))✅ A1 one row per branch, one column per group
✅ A1 all orders counted
A2. Row percentages¶
What share of each branch’s orders come from app users? Use normalize="index" and multiply by 100. Store the app-user column (the column 1) in app_share.
app_share = pd.crosstab(orders["branch"], orders["app_user"], normalize="index")[1] * 100
app_share.round(1)branch
Al Faisaliyah 21.0
Corniche 20.2
Olaya 15.5
University 75.2
Name: 1, dtype: float64check("A2 the University branch has the most app users", app_share.idxmax() == "University")
check("A2 percentages", 0 < app_share.min() and app_share.max() < 100)✅ A2 the University branch has the most app users
✅ A2 percentages
A3. A pivot table¶
Build a pivot table with one row per branch and the mean of drink_sar, food_sar and basket_sar, plus the share of orders that include food (has_food). Store it in by_branch.
by_branch = orders.pivot_table(index="branch", values=["drink_sar", "food_sar", "basket_sar", "has_food"], aggfunc="mean")
by_branch.round(2)check("A3 four branches", len(by_branch) == 4)
check("A3 food share is lowest at University", by_branch["has_food"].idxmin() == "University")✅ A3 four branches
✅ A3 food share is lowest at University
Part B: Relationships¶
B1. Box plots by branch¶
Run this cell. Which branch’s baskets are smallest, and which has the most outliers?
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])
ax.set_xticks(range(1, 5), branches)
ax.set_ylabel("Basket (SAR)")
ax.grid(axis="y", alpha=0.3)
plt.show()
B2. Correlation¶
Compute the correlation matrix of drinks, food_items and basket_sar. Store it in corr. Which of the two drives the basket more strongly?
corr = orders[["drinks", "food_items", "basket_sar"]].corr()
corr.round(2)check("B2 a 3 x 3 matrix", corr.shape == (3, 3))
check("B2 food items correlate more with the basket than drinks", corr.loc["food_items", "basket_sar"] > corr.loc["drinks", "basket_sar"])✅ B2 a 3 x 3 matrix
✅ B2 food items correlate more with the basket than drinks
B3. Do app users spend more?¶
First compare the mean basket_sar of app users and others overall (store in overall, indexed by app_user), then within each branch with a pivot table (store in within, branches as rows, app_user as columns).
overall = orders.groupby("app_user")["basket_sar"].mean()
within = orders.pivot_table(index="branch", columns="app_user", values="basket_sar", aggfunc="mean")
print(overall.round(2))
within.round(2)app_user
0 22.53
1 21.03
Name: basket_sar, dtype: float64
check("B3 overall, app users spend less", overall[1] < overall[0])
check("B3 within every branch, app users spend more", (within[1] > within[0]).all())✅ B3 overall, app users spend less
✅ B3 within every branch, app users spend more
B4. In two sentences: how can both checks above be true? Use your answer to A2.
Answer. Most app-user orders come from the University branch, where every basket is small, so the overall average of app users is pulled down by the branch they order at, not by being app users. Compared within the same branch, app users spend 2.20 to 3.34 SAR more per order: this is Simpson’s paradox, with the branch as the lurking variable.
Part C: A first Streamlit app¶
A Streamlit app is a Python script: each st. call adds an element to a web page (a title, a slider, a table, a chart), and the script runs again from the top every time the user changes a filter.
C1. Fill in the app¶
The next cell writes the app to a file, qahwa_app.py. Fill in the five gaps marked ..., run the cell, then run the test cell under it.
%%writefile qahwa_app.py
import pandas as pd
import streamlit as st
URL = "https://chebil.github.io/BusinessDecision/data/qahwa_orders_2025.csv"
@st.cache_data
def load():
try:
df = pd.read_csv(URL)
except Exception:
df = pd.read_csv("../data/qahwa_orders_2025.csv")
df["date"] = pd.to_datetime(df["date"])
df["has_food"] = df["food_items"] > 0
return df
orders = load()
st.title("Qahwa House · orders explorer")
# 1. Filters in the sidebar
all_branches = sorted(orders["branch"].unique())
branches = st.sidebar.multiselect("Branches", all_branches, default=all_branches)
categories = st.sidebar.multiselect("Categories", ["drink_sar", "food_sar"], default=["drink_sar", "food_sar"])
lo, hi = orders["date"].min().date(), orders["date"].max().date()
period = st.sidebar.date_input("Dates", value=(lo, hi), min_value=lo, max_value=hi)
view = orders[orders["branch"].isin(branches)]
if len(period) == 2:
view = view[(view["date"].dt.date >= period[0]) & (view["date"].dt.date <= period[1])]
if view.empty or not categories:
st.info("Choose at least one branch and one category.")
st.stop()
view = view.assign(revenue=view[categories].sum(axis=1))
# 2. Headline numbers
st.metric("Revenue per order (SAR)", f"{view['revenue'].mean():.2f}")
# 3. Pivot table: revenue per order by branch and category
pivot = view.groupby("branch")[categories].mean()
st.dataframe(pivot.round(2))
# 4. Chart: weekly revenue per order by branch
weekly = view.groupby([pd.Grouper(key="date", freq="W"), "branch"])["revenue"].mean().unstack()
st.line_chart(weekly)
# 5. Correlation view
numeric = ["drinks", "food_items", "drink_sar", "food_sar", "basket_sar"]
x = st.selectbox("x", numeric, index=1)
y = st.selectbox("y", numeric, index=4)
st.scatter_chart(view, x=x, y=y)
st.metric("Correlation r", f"{view[x].corr(view[y]):.2f}")
st.caption("Correlation is not causation: a third variable, such as the branch, can drive both.")Writing qahwa_app.py
# Run the app in the notebook without a browser: Streamlit's AppTest executes it like a visitor would.
import importlib.util, subprocess, sys
if importlib.util.find_spec("streamlit") is None: # Colab does not ship Streamlit
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "streamlit"], check=True)
import logging
from pathlib import Path
from streamlit.testing.v1 import AppTest
for name in ("streamlit", "streamlit.runtime.scriptrunner_utils.script_run_context"):
logging.getLogger(name).setLevel(logging.ERROR) # quiet "missing ScriptRunContext" notices
at = AppTest.from_file(str(Path("qahwa_app.py").resolve()), default_timeout=60).run()
check("C1 the app runs without an error", not at.exception)
check("C1 a revenue-per-order metric", any(m.label.startswith("Revenue per order") for m in at.metric))
check("C1 a correlation metric", any(m.label.startswith("Correlation") for m in at.metric))
check("C1 a pivot table", len(at.dataframe) >= 1)
if at.exception:
print(at.exception[0].message)✅ C1 the app runs without an error
✅ C1 a revenue-per-order metric
✅ C1 a correlation metric
✅ C1 a pivot table
C2. See it in a browser¶
Colab cannot show a Streamlit page, so open it in GitHub Codespaces (free with GitHub Education) or on your own computer:
Put
qahwa_app.pyin a folder, open a terminal there and runpip install streamlit pandas.Run
streamlit run qahwa_app.py; a browser tab opens athttp://localhost:8501.To share it, push the file to a GitHub repository and deploy it on Streamlit Community Cloud (share.streamlit.io): pick the repository and the file, and you get a public link.
The course’s finished version, with more views, is week04/app/app.py in the course repository.
C3. Your recommendation¶
Use your app: select one branch at a time, and only the food_sar category. Then write three sentences for the manager: which branch × category combination underperforms (with numbers), what you would try, and why the data alone cannot prove the cause.
Recommendation. Food is the weak spot at the University branch: only 17% of its orders include food, against 40% to 47% elsewhere, so food brings in 2.88 SAR per order there against 6.39 to 7.53 SAR in the other branches. I would test a student meal deal (a drink and a sandwich at a set price) on some weeks and not others, and compare food revenue per order. The data cannot tell us why food sells badly there: it may be prices, the menu, the opening hours, or simply customers with smaller budgets, so only such a test can show whether an offer changes their behaviour.
★ Extended challenges¶
E1. A weekday filter. Add a st.sidebar.multiselect for weekdays to your app and check it still runs with AppTest.
E2. Two correlations, one pair. With the Week 1 sales data, compute the correlation between Iced Latte and Spanish Latte daily units at the Olaya branch, then between their monthly totals. Explain why the sign changes.
E3. An alert. Make your app show st.warning when app users spend more than others in every selected branch but less overall.
# E1: a weekday filter (only the new lines; add them after the date filter in qahwa_app.py)
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
snippet = '''
chosen_days = st.sidebar.multiselect("Weekdays", days, default=days)
view = view[view["weekday"].isin(chosen_days)]
'''
print(snippet)
chosen_days = st.sidebar.multiselect("Weekdays", days, default=days)
view = view[view["weekday"].isin(chosen_days)]
# E2: daily and monthly correlation of two products at Olaya
sales = load("qahwa_sales_2025.csv")
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, busy days and promotion days lift both products together (r = +0.25). Month by month, the season dominates: summer pushes iced drinks up and hot drinks down (r = −0.46). Neither product causes the other’s sales; different confounders dominate at different time scales.
# E3: the alert, as it would sit in the app (tested here on the full data)
over = orders.groupby("app_user")["basket_sar"].mean()
inside = orders.pivot_table(index="branch", columns="app_user", values="basket_sar", aggfunc="mean")
if (inside[1] > inside[0]).all() and over[1] < over[0]:
print("st.warning: Simpson's paradox: app users spend more in every branch but less overall.")st.warning: Simpson's paradox: app users spend more in every branch but less overall.