Describing Data for Decisions¶
This reading follows the Week 3 lecture. A table of thousands of rows answers nothing by itself: a manager needs a few well-chosen numbers and pictures. Here you learn which summary answers which question, and why the most familiar one, the mean, can mislead. Open the notebook in Colab with the button above and run the cells from top to bottom.
After this reading you can:
choose the summaries that make sense for a variable’s type;
compute and interpret the mean, median, mode, range, IQR, standard deviation and percentiles;
explain why a right-skewed variable has its mean above its median;
draw and read histograms, box plots and time-series plots;
set a service target from a percentile.
Textbook: Albright & Winston, Business Analytics: Data Analysis and Decision Making, Chapter 2.
1. The service study¶
In 2025, Qahwa House timed one order in five in its four branches, from payment to the cup in the customer’s hand. Each row of the file is one timed order.
import 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 | Type |
|---|---|---|
order_id | order number | an identifier, not a quantity |
date, weekday, hour | when the order was paid | date and time |
branch, city, channel | where and how (Counter, App, Drive-thru) | categorical |
items | items in the order | discrete |
order_value | amount paid, SAR | continuous |
wait_min | minutes from payment to the cup | continuous |
The manager has five questions: How do customers order? How long does a typical customer wait? How long do the unlucky ones wait? When are we busy? Can we promise “served within N minutes”? Each needs a different summary.
2. The type of a variable decides the summary¶
Categorical variables are names. We can count them and give percentages; the mode is the most common category.
Numerical variables are quantities. We describe their centre, their spread and their shape.
Dates and times are best summarised by counting per period and plotting against time.
Some columns hold digits without being quantities: the mean order_id means nothing. And hour is a number you could average, but for a manager it is more useful as a category: which hours are busy.
3. Categorical data: counts and percentages¶
counts = orders["channel"].value_counts()
shares = orders["channel"].value_counts(normalize=True) * 100
pd.DataFrame({"orders": counts, "share (%)": shares.round(1)})Most orders are placed at the counter. Percentages matter when groups differ in size. Drive-thru exists only in Riyadh and Dammam, so its chain-wide share understates how much it matters there:
by_branch = (orders.groupby("branch")["channel"]
.value_counts(normalize=True)
.unstack(fill_value=0) * 100)
by_branch.round(1)4. Centre: mean, median and mode¶
The mean is the sum of the values divided by their number (pandas
.mean(), ExcelAVERAGE).The median is the middle value once the values are sorted: half the customers wait less, half wait more (
.median(),MEDIAN).The mode is the most frequent value. For a continuous variable we round first, or it is just a lucky tie (
.mode(),MODE.SNGL).
w = orders["wait_min"]
print(f"mean {w.mean():.2f} min")
print(f"median {w.median():.1f} min")
print(f"mode {w.round().mode()[0]:.0f} min (waits rounded to the minute)")mean 4.75 min
median 4.2 min
mode 4 min (waits rounded to the minute)
Three different answers to “what is a typical wait?”. The reason is the shape of the distribution, which a histogram shows:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 3.6))
ax.hist(w.clip(upper=20), bins=range(0, 21), color="#86c9e8", edgecolor="#127291")
ax.axvline(w.median(), color="tab:green", lw=2.5, label=f"median {w.median():.1f}")
ax.axvline(w.mean(), color="tab:orange", lw=2.5, ls="--", label=f"mean {w.mean():.2f}")
ax.set_xlabel("wait (minutes; the last bar holds every wait of 19 minutes or more)")
ax.set_ylabel("orders")
ax.set_title("Most waits are short; a few are very long")
ax.legend()
plt.show()
print(f"skewness {w.skew():.2f}")
print(f"share of customers waiting longer than the mean: {(w > w.mean()).mean():.1%}")
skewness 3.50
share of customers waiting longer than the mean: 39.4%
The histogram is right-skewed: most waits are between 2 and 6 minutes, and a long tail reaches 45 minutes. The tail pulls the mean (4.75 minutes) above the median (4.2 minutes), and only 39.4% of customers wait longer than the “average” wait, not half. A positive skewness (here 3.5) says the same in one number.
Which one to report? For “how long does a typical customer wait?”, the median. The mean is still the right number for totals: total minutes waited = mean × number of orders, and that is what staffing costs depend on.
5. Spread: range, IQR and standard deviation¶
Two branches can have the same typical wait and very different consistency. Spread measures it.
q1, q3 = w.quantile([0.25, 0.75])
print(f"range {w.min():.1f} to {w.max():.1f} min")
print(f"quartiles Q1, Q3 {q1:.1f} and {q3:.1f} min, so IQR = {q3 - q1:.1f} min")
print(f"standard deviation {w.std():.2f} min (sample, divides by n - 1)")
print(f"variance {w.var():.2f} min²")range 0.2 to 45.0 min
quartiles Q1, Q3 3.1 and 5.7 min, so IQR = 2.6 min
standard deviation 2.69 min (sample, divides by n - 1)
variance 7.24 min²
The range depends on two orders only, and one freak order sets it.
The interquartile range (IQR) is the width of the middle half of the data: robust to the tail.
The standard deviation is a typical distance from the mean, in the data’s own units: .
One trap: pandas and NumPy disagree by default.
import numpy as np
print(f"pandas .std() {w.std():.6f} divides by n - 1 (a sample), like Excel STDEV.S")
print(f"numpy np.std() {np.std(w):.6f} divides by n (a population), like Excel STDEV.P")pandas .std() 2.689901 divides by n - 1 (a sample), like Excel STDEV.S
numpy np.std() 2.689860 divides by n (a population), like Excel STDEV.P
With 32,982 orders the difference is negligible; with ten values it is not. Use the sample version unless the data really are the whole population. Excel’s older names (STDEV, VAR, PERCENTILE, QUARTILE) still work but are kept only for compatibility: use STDEV.S, VAR.S, PERCENTILE.INC and QUARTILE.INC.
6. Percentiles answer “how many customers?”¶
The p-th percentile is the value below which p% of the data lie. The median is the 50th percentile; Q1 and Q3 are the 25th and 75th.
pcts = w.quantile([0.25, 0.5, 0.75, 0.9, 0.95]).rename("wait (min)")
pcts.index = ["25th", "50th (median)", "75th", "90th", "95th"]
pcts.round(1).to_frame()The 90th percentile reads: 90% of customers are served within 7.7 minutes; one in ten waits longer. A mean describes the average customer; a high percentile describes the unlucky ones. That is why service targets in call centres, delivery and IT are almost always percentiles.
7. Comparing the branches¶
def p90(x):
return x.quantile(0.9)
summary = orders.groupby("branch")["wait_min"].agg(["count", "mean", "median", p90, "std"])
summary["IQR"] = orders.groupby("branch")["wait_min"].quantile(0.75) - orders.groupby("branch")["wait_min"].quantile(0.25)
summary.round(2).sort_values("p90")The means differ by barely half a minute. But look at University (Al-Kharj): the lowest median of the four, so its typical customer is served fastest, and by far the highest 90th percentile and standard deviation. Its unlucky customers wait much longer than anywhere else. Comparing means alone would hide this.
A box plot shows the same comparison at a glance: the box holds the middle half of the data, the line inside is the median, the whiskers reach the furthest value within 1.5 × IQR of the box, and points beyond them are drawn one by one.
branches = ["Olaya", "Corniche", "Al Faisaliyah", "University"]
fig, ax = plt.subplots(figsize=(8, 3.6))
ax.boxplot([orders.loc[orders["branch"] == b, "wait_min"] for b in branches],
flierprops={"marker": ".", "markersize": 3, "alpha": 0.3})
ax.set_xticks(range(1, len(branches) + 1), branches)
ax.set_ylim(0, 25)
ax.set_ylabel("wait (minutes; a few above 25 are off the chart)")
ax.set_title("University: the fastest median, the longest tail")
plt.show()
Points beyond the whiskers are not errors: they are real customers who waited a long time. Week 2 taught you to check outliers; here they are the very thing the manager needs to see.
8. When are we busy? Time-series plots¶
Summaries over a whole year hide when things happen. Always plot a time series against time first.
weekly = orders.set_index("date").resample("W-SAT").size().iloc[1:-1] # full weeks, Sunday to Saturday
fig, ax = plt.subplots(figsize=(9, 3.4))
ax.plot(weekly.index, weekly.values, lw=2)
ax.axvspan(pd.Timestamp("2025-03-01"), pd.Timestamp("2025-03-29"), color="tab:orange", alpha=0.15, label="Ramadan (approx.)")
ax.axvspan(pd.Timestamp("2025-06-01"), pd.Timestamp("2025-08-31"), color="tab:blue", alpha=0.08, label="summer")
ax.set_ylabel("orders timed per week")
ax.set_title("Dips in Ramadan and in the summer heat; a rising trend in the autumn")
ax.legend(loc="lower right")
ax.grid(alpha=0.3)
plt.show()
The weekly series shows three things no single number could: fewer orders in Ramadan, a summer dip (the Riyadh and Dammam branches lose daytime customers in the heat, while Jeddah’s corniche stays busy), and a rising trend in the autumn. Week 8 models trend and seasonality to forecast demand.
The time of day matters as much as the week. Here hour works as a category: we count orders per hour.
ramadan = orders["date"].between("2025-03-01", "2025-03-29")
by_hour = pd.DataFrame({
"normal days": orders[~ramadan]["hour"].value_counts(normalize=True),
"Ramadan": orders[ramadan]["hour"].value_counts(normalize=True),
}).reindex(range(6, 24), fill_value=0) * 100
ax = by_hour.plot(figsize=(9, 3.4), marker="o", title="Ramadan moves the rush to the evening")
ax.set_xlabel("hour of the day")
ax.set_ylabel("% of the day's orders")
ax.grid(alpha=0.3)
plt.show()
print(f"orders from 19:00 on: {(orders[ramadan]['hour'] >= 19).mean():.0%} in Ramadan, {(orders[~ramadan]['hour'] >= 19).mean():.0%} on other days")
orders from 19:00 on: 85% in Ramadan, 32% on other days
Normal days have two rushes, around 8:00 and 20:00. In Ramadan, 85% of orders arrive from 19:00 on. Rushes also slow service down:
rush = orders["hour"].isin([7, 8, 20, 21])
orders.groupby(rush)["wait_min"].median().rename(index={False: "other hours", True: "rush hours"}).round(1)hour
other hours 3.9
rush hours 4.8
Name: wait_min, dtype: float649. From a summary to a decision¶
The manager wants to print “served within N minutes” on the menu boards. Which summary gives N?
The mean (about 5 minutes) would be broken for roughly a third of the customers or more.
A high percentile is built for this question: the 90th percentile is broken for at most one order in ten, by construction.
promise = pd.DataFrame({
"mean": orders.groupby("branch")["wait_min"].mean(),
"share over the mean": orders.groupby("branch")["wait_min"].apply(lambda x: (x > x.mean()).mean() * 100),
"90th percentile": orders.groupby("branch")["wait_min"].quantile(0.9),
"share over 8 min": orders.groupby("branch")["wait_min"].apply(lambda x: (x > 8).mean() * 100),
})
promise.round(1).sort_values("90th percentile")A single chain-wide promise of 8 minutes holds in three branches, where at most about one order in eleven misses it, and fails one University customer in six. The data does not choose for the manager, but it shows what each choice costs: promise 8 minutes and fix University’s tail first (staff at its rushes and in exam months), promise branch by branch, or do not promise yet. Lab 3 asks you to make that recommendation.
Which summary answers which question?¶
| The manager asks | Use |
|---|---|
| How do customers order? | counts and percentages; a bar chart |
| How long does a typical customer wait? | the median, for skewed data |
| How many staff-minutes do we spend in total? | the mean × the number of orders |
| How long do the unlucky customers wait? | a high percentile (90th, 95th) |
| How consistent is the service? | the IQR or the standard deviation; a box plot |
| Which branch is different? | side-by-side box plots |
| When are we busy? | a time-series plot; counts by hour |
Check your understanding¶
Which summaries make sense for
channel? Foritems? Fororder_id?A delivery company’s delivery times have a mean of 38 minutes and a median of 31 minutes. Which way is the distribution skewed, and why?
Two branches both have a mean wait of 5 minutes. Branch A has a standard deviation of 1 minute, branch B of 4 minutes. Which one would you rather promise “within 8 minutes” for, and why?
Why does the range describe the spread of the waits badly?
The manager says: “Our average wait is under 5 minutes, so let’s promise 5 minutes.” What do you answer, with one number from this reading?
Answers. 1. channel: counts, percentages and the mode. items: those, plus the mean, median and spread. order_id: only a count of distinct values; it is a label. 2. Right-skewed: a few very long deliveries pull the mean above the median. 3. Branch A: with a small spread almost every wait is close to 5 minutes, while branch B’s waits often run far above it. 4. It depends on the two most extreme orders only, here a single 45-minute wait. 5. A promise set at the mean is broken for many customers: 39.4% of customers wait longer than the mean wait.