Lab 4: Relationships and a First Streamlit App¶
In this lab you look for relationships in Qahwa House’s orders, then turn your analysis into a small interactive app the manager can use.
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 = ...
countscheck("A1 one row per branch, one column per group", counts.shape == (4, 2))
check("A1 all orders counted", counts.values.sum() == len(orders))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 = ...
app_share.round(1)check("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)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 = ...
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")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 = ...
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"])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 = ...
within = ...
print(overall.round(2))
within.round(2)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())B4. In two sentences: how can both checks above be true? Use your answer to A2.
Your answer here (double-click to edit).
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 = ... # a multiselect of all_branches, all selected by default
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 = ... # the orders of the selected 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 with the mean revenue per order
# 3. Pivot table: revenue per order by branch and category
pivot = ... # mean of the selected categories by branch
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 with the correlation between x and y
st.caption("Correlation is not causation: a third variable, such as the branch, can drive both.")# 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)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.
Write your recommendation here (double-click to edit).
★ 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# E2# E3AI-use log (if you used an AI assistant)¶
What you asked, what you kept, what you changed.