Lab 3 Solutions: Exploratory Analysis with Plotly¶
These are the worked solutions, with outputs. Try the lab yourself first.
The question. In 2025 Qahwa House timed one order in five in its four branches. The manager wants to print “served within N minutes” on the menu boards of the whole chain. What should N be, and what must change first?
How this lab works
Run the cells from top to bottom with Shift + Enter.
Guided track: replace every
...with your code, then run the check cell under it. A ✅ means your answer is right.Extended track: after Part D, try the ★ challenges at the end.
Submit before the next lab session: File → Download → Download .ipynb, then upload the file to the course page.
You may use an AI assistant for code. If you do, add a short note at the end of the notebook: 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)Setup¶
Run the next two cells: the first loads Plotly, the charting library of this lab; the second downloads the data.
import plotly.express as px
import plotly.io as pio
import sys
# In Colab the charts are interactive. Outside Colab (and on the course website) they are saved as images.
if "google.colab" not in sys.modules:
try:
import kaleido # noqa: F401
pio.renderers.default = "png"
except ImportError:
passimport pandas as pd
DATA_URL = "https://chebil.github.io/BusinessDecision/data/qahwa_service_2025.csv"
try:
orders = pd.read_csv(DATA_URL, parse_dates=["date"])
except Exception: # offline, or working from a copy of the course repository
orders = pd.read_csv("../data/qahwa_service_2025.csv", parse_dates=["date"])
print(orders.shape)
orders.head()(32982, 10)
| Column | Meaning |
|---|---|
date, weekday, hour | when the order was paid |
branch, city | where |
channel | Counter, App or Drive-thru |
items, order_value | how many items, and the amount paid (SAR) |
wait_min | minutes from payment to the cup in the customer’s hand |
Part A: Categorical data¶
A1. How do customers order?¶
Use value_counts(normalize=True) on the channel column and multiply by 100 to get percentages. Store the result in channel_pct.
channel_pct = orders["channel"].value_counts(normalize=True) * 100
channel_pct.round(1)channel
Counter 57.9
App 29.2
Drive-thru 12.9
Name: proportion, dtype: float64check("A1 percentages add up to 100", abs(channel_pct.sum() - 100) < 1e-6)
check("A1 Counter is the most common channel (the mode)", channel_pct.idxmax() == "Counter")✅ A1 percentages add up to 100
✅ A1 Counter is the most common channel (the mode)
A2. Channels by branch¶
Percentages within each branch: group by branch, then take value_counts(normalize=True) of channel, and .unstack(fill_value=0) to get one row per branch. Store it in mix. Which branches have a drive-thru?
mix = orders.groupby("branch")["channel"].value_counts(normalize=True).unstack(fill_value=0)
(mix * 100).round(1)check("A2 one row per branch", len(mix) == 4)
check("A2 University has no drive-thru", mix.loc["University", "Drive-thru"] == 0)✅ A2 one row per branch
✅ A2 University has no drive-thru
Part B: Centre and spread of the wait¶
B1. Centre¶
Store the waiting times in w, then compute their mean and median. Which is larger, and why?
w = orders["wait_min"]
wait_mean = w.mean()
wait_median = w.median()
print(round(wait_mean, 2), wait_median)4.75 4.2
check("B1 mean", abs(wait_mean - orders["wait_min"].sum() / len(orders)) < 1e-9)
check("B1 the mean is above the median (right skew)", wait_mean > wait_median)✅ B1 mean
✅ B1 the mean is above the median (right skew)
B2. Spread¶
Compute the interquartile range (quantile(0.75) - quantile(0.25)) and the sample standard deviation (.std()).
wait_iqr = w.quantile(0.75) - w.quantile(0.25)
wait_std = w.std()
print(round(wait_iqr, 2), round(wait_std, 2))2.6 2.69
check("B2 IQR", abs(wait_iqr - (w.quantile(0.75) - w.quantile(0.25))) < 1e-9)
check("B2 sample standard deviation (n - 1)", abs(wait_std - w.std(ddof=1)) < 1e-9)✅ B2 IQR
✅ B2 sample standard deviation (n - 1)
B3. The 90th percentile¶
Compute the 90th percentile of the waits. Then compute the share of customers who wait longer than the mean. Is it half?
wait_p90 = w.quantile(0.9)
share_over_mean = (w > w.mean()).mean()
print(round(wait_p90, 2), round(share_over_mean, 3))7.7 0.394
check("B3 90% of orders are at or below the 90th percentile", abs((w <= wait_p90).mean() - 0.9) < 0.01)
check("B3 fewer than half wait longer than the mean", share_over_mean < 0.5)✅ B3 90% of orders are at or below the 90th percentile
✅ B3 fewer than half wait longer than the mean
Part C: Pictures with Plotly¶
plotly.express (imported as px) draws a whole chart in one line. In Colab you can hover over a bar for its value, zoom by dragging, and click a legend entry to hide a group.
C1. A histogram, and its bin width¶
Run the cell. Then change nbins to 8 and to 200 and run it again each time. Which bin width shows the shape best?
fig = px.histogram(orders, x="wait_min", nbins=60, range_x=[0, 25],
title="Wait times, all branches", labels={"wait_min": "wait (minutes)"})
fig.update_layout(width=800, height=380, bargap=0.02)
fig.show()
C2. Box plots by branch¶
Draw one box per branch with px.box(orders, x="wait_min", y="branch"). Store the figure in fig_box, then show it. Which branch has the longest tail?
fig_box = px.box(orders, x="wait_min", y="branch", points="outliers",
title="Wait time by branch", labels={"wait_min": "wait (minutes)", "branch": ""})
fig_box.update_layout(width=800, height=380)
fig_box.show()
check("C2 a Plotly box plot", type(fig_box).__name__ == "Figure" and fig_box.data[0].type == "box")✅ C2 a Plotly box plot
C3. Orders per week¶
Count orders per full week (Sunday to Saturday) and plot them against time. The first and last weeks of the year are partial, so drop them with .iloc[1:-1].
weekly = orders.set_index("date").resample("W-SAT").size().iloc[1:-1]
fig = px.line(x=weekly.index, y=weekly.values, labels={"x": "week ending", "y": "orders timed"},
title="Orders timed per week, 2025")
fig.update_layout(width=800, height=340)
fig.show()
check("C3 51 full weeks", len(weekly) == 51)✅ C3 51 full weeks
C4. When in the day?¶
Run the cell: it compares the share of orders per hour on normal days and in Ramadan (1 to 29 March 2025, approximately).
ramadan = orders["date"].between("2025-03-01", "2025-03-29")
by_hour = (orders.assign(period=ramadan.map({True: "Ramadan", False: "normal days"}))
.groupby("period")["hour"].value_counts(normalize=True).mul(100).rename("share").reset_index())
fig = px.line(by_hour.sort_values("hour"), x="hour", y="share", color="period", markers=True,
title="Share of the day's orders by hour", labels={"share": "% of orders"})
fig.update_layout(width=800, height=340)
fig.show()
Part D: The decision¶
D1. One row per branch¶
Build a table promise with one row per branch and four columns: the mean wait, the median, the 90th percentile p90, and over_8, the percentage of orders that wait more than 8 minutes. Sort it by p90.
g = orders.groupby("branch")["wait_min"]
promise = pd.DataFrame({
"mean": g.mean(),
"median": g.median(),
"p90": g.quantile(0.9),
"over_8": g.apply(lambda x: (x > 8).mean() * 100),
}).sort_values("p90")
promise.round(1)check("D1 four branches", len(promise) == 4)
check("D1 the right columns", {"mean", "median", "p90", "over_8"} <= set(promise.columns))
check("D1 sorted by p90, University last", promise.index[-1] == "University")✅ D1 four branches
✅ D1 the right columns
✅ D1 sorted by p90, University last
D2. What would a promise based on the mean cost?¶
For each branch, the percentage of orders that would break a promise of 5 minutes (about the chain’s mean wait). Store it in broken_at_5.
broken_at_5 = g.apply(lambda x: (x > 5).mean() * 100)
broken_at_5.round(1)branch
Al Faisaliyah 31.1
Corniche 38.6
Olaya 32.5
University 35.5
Name: wait_min, dtype: float64check("D2 a value per branch", len(broken_at_5) == 4)
check("D2 more than 30% broken everywhere", (broken_at_5 > 30).all())✅ D2 a value per branch
✅ D2 more than 30% broken everywhere
D3. Your recommendation¶
Write three sentences for the manager, who does not read code:
what the data shows, with one or two numbers;
the value of N you recommend, and for which branches;
what must change, or what the data cannot tell us, before the promise is safe everywhere.
Recommendation. A promise based on the average wait would fail: about 5 minutes is the mean, yet 31% to 39% of customers wait longer than that, depending on the branch. A chain-wide promise of 8 minutes is safe in Olaya, Al Faisaliyah and Corniche, where 5% to 9% of orders exceed it, but not at University, where one order in six (16.4%) does, even though its typical customer is served fastest (median 3.8 minutes). I recommend fixing University’s long tail first, with extra staff at its rush hours and in exam months, and launching the 8-minute promise there only once its 90th percentile, now 10.1 minutes, falls below 8; a follow-up timing study would show whether it has.
★ Extended challenges¶
E1. Rush hours. Compare the median and the 90th percentile of the wait in the rush hours (7, 8, 20 and 21) and at other times. Is the rush a reason to staff differently, or only to promise differently?
E2. Exam months at University. Compare University’s 90th percentile in its exam months (January, May, June, December) with the other months. Does the tail come from the whole year?
E3. The typical basket. Is order_value skewed? Which number would you report as the “typical basket”, and which one would you use to estimate the chain’s annual revenue from this sample?
# E1: rush hours
rush = orders["hour"].isin([7, 8, 20, 21])
orders.groupby(rush.map({True: "rush hours", False: "other hours"}))["wait_min"].describe(percentiles=[0.5, 0.9]).round(2)Both the median and the 90th percentile are higher in the rush hours, so the tail is largely made in the rushes. That argues for more staff at those hours rather than a longer promise.
# E2: University's exam months
uni = orders[orders["branch"] == "University"]
exam = uni["date"].dt.month.isin([1, 5, 6, 12])
uni.groupby(exam.map({True: "exam months", False: "other months"}))["wait_min"].quantile(0.9).round(1)date
exam months 11.5
other months 9.4
Name: wait_min, dtype: float64University’s 90th percentile is clearly higher in exam months, but it stays above the other branches’ even outside them: one barista off-peak makes a long tail all year, and the exam rushes make it worse. Both need fixing before an 8-minute promise.
# E3: the typical basket
v = orders["order_value"]
print(f"mean {v.mean():.2f} SAR, median {v.median():.2f} SAR, skewness {v.skew():.2f}")
fig = px.histogram(orders, x="order_value", nbins=60, title="Order value (SAR)")
fig.update_layout(width=800, height=340)
fig.show()mean 25.11 SAR, median 23.24 SAR, skewness 1.24

The order value is right-skewed too (skewness about 1.2), with two peaks: one-item and two-item baskets. The median (23.24 SAR) describes the typical basket. To estimate annual revenue, though, use the mean: revenue = mean order value × number of orders (here × 5, since one order in five was timed). Totals need the mean; “typical” needs the median.