Lesson 61 · Pandas Full Course
Build a KPI Dashboard with Pandas (Revenue, Orders, Customers) | Pandas Course #61
In this lesson you'll be able to: Define KPIs clearly and clean the data behind them Calculate headline KPIs: revenue, orders, customers, order value Track…
- CoursePandas Full Course
- Lesson61 of 65
- FormatJupyter notebook · 42 code cells
- Data1 dataset
What you'll learn
Datasets used in this lesson
Save these next to the notebook. In Google Colab, upload them with the 📁 icon on the left first.
- online_retail.csv.gz preview7.1 MB
📓 Full notebook
Download .ipynbPandas 61: Building a KPI Dashboard with Pandas#
In this lesson you'll be able to:
- Define KPIs clearly and clean the data behind them
- Calculate headline KPIs: revenue, orders, customers, order value
- Track KPIs month by month and break them down by country
- Flag each KPI as up or down against last month
- Lay several KPI charts out as one dashboard Data: a UK online gift shop's sales lines (online_retail.csv.gz)
Warm-up: describe before you trust#
Lesson 60 summarised stock prices. Same first step, new data.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("data/pandas/online_retail.csv.gz")
print(df.shape)
df.sample(3, random_state=42)
df[["Quantity", "UnitPrice"]].describe().round(2)
Define the KPIs and clean the data#
Problem: a KPI is only trusted if everyone calculates it the same way.
- Revenue: quantity times unit price, summed
- Orders: distinct invoice numbers
- Customers: distinct customer IDs
- Average order value: revenue divided by orders
Common mistake: using .dt on a date column that is still text.
df["InvoiceDate"].dt.month.head()
df["InvoiceDate"] = pd.to_datetime(df["InvoiceDate"],
format="%m/%d/%Y %H:%M")
print(df["InvoiceDate"].min(), df["InvoiceDate"].max())
df["Revenue"] = df["Quantity"] * df["UnitPrice"]
df[["Quantity", "UnitPrice", "Revenue"]].head(3)
cancelled = df["InvoiceNo"].str.startswith("C")
print(cancelled.sum(), round(cancelled.mean() * 100, 2))
Quick check: are all the negative quantities cancellations?
neg = df["Quantity"] < 0
pd.crosstab(cancelled, neg)
odd = df[~cancelled & neg]
print(odd["UnitPrice"].max())
odd["Description"].value_counts().head(3)
real = ~cancelled & (df["UnitPrice"] > 0)
sales = df[real].copy()
print(len(sales), (sales["Quantity"] <= 0).sum())
Calculate the headline KPIs#
Problem: boil 530,000 rows down to the numbers a manager reads first.
revenue = sales["Revenue"].sum()
orders = sales["InvoiceNo"].nunique()
customers = sales["CustomerID"].nunique()
print(round(revenue, 2), orders, customers)
units = sales["Quantity"].sum()
print(units, round(units / orders, 1))
guest = sales["CustomerID"].isna()
print(round(guest.mean() * 100, 1))
print(round(sales.loc[guest, "Revenue"].sum() / revenue * 100, 1))
Quick check: is the average order value just the mean of Revenue?
print(round(sales["Revenue"].mean(), 2))
aov = revenue / orders
print(round(aov, 2))
per_order = sales.groupby("InvoiceNo")["Revenue"].sum()
print(round(per_order.mean(), 2), round(per_order.median(), 2))
lost = -df.loc[cancelled, "Revenue"].sum()
cancel_rate = lost / (revenue + lost) * 100
print(round(lost, 2), round(cancel_rate, 2))
kpis = pd.Series({
"Revenue": revenue, "Orders": orders,
"Customers": customers, "Avg order value": aov,
"Cancelled %": cancel_rate,
})
for name, value in kpis.items():
print(f"{name:<16}{value:>14,.2f}")
Track KPIs month by month#
Problem: one total can't tell us whether the business is growing.
monthly = sales.resample("ME", on="InvoiceDate").agg(
revenue=("Revenue", "sum"),
orders=("InvoiceNo", "nunique"),
customers=("CustomerID", "nunique"),
)
monthly.round(0).tail(4)
Quick check: did sales really collapse in December 2011?
print(sales["InvoiceDate"].max())
monthly = monthly.loc[:"2011-11"].copy()
monthly["aov"] = monthly["revenue"] / monthly["orders"]
monthly["growth_%"] = monthly["revenue"].pct_change() * 100
monthly.round(1).tail(4)
best = monthly["revenue"].idxmax()
worst = monthly["revenue"].idxmin()
print("Best:", best.strftime("%B %Y"))
print("Worst:", worst.strftime("%B %Y"))
labels = monthly.index.strftime("%b %Y")
ax = (monthly["revenue"] / 1000).plot.bar(figsize=(9, 4))
ax.set_xticklabels(labels, rotation=45)
ax.set_title("Monthly revenue")
ax.set_xlabel("Month")
ax.set_ylabel("Revenue (thousand GBP)")
peak = monthly.loc["2011-09":"2011-11", "revenue"].sum()
share = peak / monthly["revenue"].sum() * 100
print(round(share, 1))
Your turn: add a 3-month rolling average of revenue, as in lesson 60.
monthly["rev_3m"] = monthly["revenue"].rolling(3).mean()
monthly[["revenue", "rev_3m"]].round(0).tail(4)
Break KPIs down by country#
Problem: a single total hides which markets carry the business.
Common mistake: a wrong function name inside named aggregation.
sales.groupby("Country").agg(revenue=("Revenue", "total"))
by_country = sales.groupby("Country").agg(
revenue=("Revenue", "sum"),
orders=("InvoiceNo", "nunique"),
)
by_country["share_%"] = by_country["revenue"] / revenue * 100
by_country.nlargest(5, "revenue").round(1)
Your turn: which of the top 5 countries has the highest average order value?
top = by_country.nlargest(5, "revenue").copy()
top["aov"] = top["revenue"] / top["orders"]
top["aov"].round(2).sort_values(ascending=False)
Quick check: why is the Dutch average order so much higher?
nl = sales[sales["Country"] == "Netherlands"]
print(nl["CustomerID"].nunique())
nl.groupby("CustomerID")["Revenue"].sum().nlargest(3).round(0)
abroad = by_country.drop(index="United Kingdom")
top8 = abroad.nlargest(8, "revenue")["revenue"] / 1000
ax = top8.sort_values().plot.barh(figsize=(8, 4))
ax.set_title("Top export markets by revenue")
ax.set_xlabel("Revenue (thousand GBP)")
ax.set_ylabel("Country")
Compare this month with last month#
Problem: a dashboard must show at a glance whether each KPI is up or down.
cur = monthly.iloc[-1]
prev = monthly.iloc[-2]
print(cur.name.strftime("%B %Y"), "vs", prev.name.strftime("%B %Y"))
table = pd.DataFrame({"current": cur, "previous": prev})
table = table.drop(index=["growth_%", "rev_3m"])
table["change_%"] = (table["current"] / table["previous"] - 1) * 100
table.round(2)
import numpy as np
table["status"] = np.where(table["change_%"] > 0, "up", "down")
table[["change_%", "status"]].round(1)
arrows = {"up": "^", "down": "v"}
for kpi, row in table.iterrows():
mark = arrows[row["status"]]
print(f"{kpi:<10}{row['current']:>12,.0f} {mark} "
f"{row['change_%']:+.1f}%")
Quick check: revenue rose, so how can average order value fall?
table.loc[["revenue", "orders"], "change_%"].round(1)
base = monthly.iloc[-4:-1]
table["3m_avg"] = base[["revenue", "orders", "customers", "aov"]].mean()
table["vs_avg_%"] = (table["current"] / table["3m_avg"] - 1) * 100
table[["current", "3m_avg", "vs_avg_%"]].round(1)
Lay out the dashboard#
Problem: four separate charts are hard to read side by side.
fig, axes = plt.subplots(2, 2, figsize=(10, 7))
cols = ["revenue", "orders", "customers", "aov"]
for ax, col in zip(axes.flat, cols):
monthly[col].plot(ax=ax, marker="o")
ax.set_title(f"Monthly {col}")
ax.set_xlabel("Month")
ax.set_ylabel(col)
fig.suptitle("Online gift shop KPI dashboard")
fig.tight_layout()
import os
os.makedirs("output/pandas", exist_ok=True)
path = "output/pandas/l61_kpi_table.csv"
table.to_csv(path)
back = pd.read_csv(path, index_col=0)
back[["current", "previous", "status"]].round(2)
Mini-project: how much do repeat customers matter?#
Question: what share of revenue comes from customers who ordered again? Plan: one row per customer, flag repeaters, compare revenue shares.
known = sales.dropna(subset=["CustomerID"])
per_cust = known.groupby("CustomerID").agg(
orders=("InvoiceNo", "nunique"),
revenue=("Revenue", "sum"),
)
print(len(per_cust), per_cust["orders"].median())
repeat = per_cust["orders"] > 1
print(round(repeat.mean() * 100, 1))
rev_share = per_cust.groupby(repeat)["revenue"].sum()
(rev_share / rev_share.sum() * 100).round(1)
cut = per_cust["revenue"].quantile(0.9)
top10 = per_cust.loc[per_cust["revenue"] > cut, "revenue"].sum()
print(round(top10 / per_cust["revenue"].sum() * 100, 1))
first = known.groupby("CustomerID")["InvoiceDate"].min()
new = first.dt.to_period("M").value_counts().sort_index()
new.head(3)
rest = new.loc["2011-01":"2011-11"]
print(rest.idxmin(), rest.min())
print(rest.idxmax(), rest.max())
once = rev_share[False] / (~repeat).sum()
again = rev_share[True] / repeat.sum()
print(f"Repeat customers spend {again / once:.1f} times as much")
Recap#
- Write each KPI's definition down before calculating it
- Clean first: drop cancellations and zero-price lines
- nunique counts orders and customers; AOV is revenue / orders
- Resample by month, and drop any incomplete final month
- Compare with last month and a 3-month average, then flag status
Challenges#
- Build the monthly KPI table for Germany only.
- Add monthly units sold and items per order to the dashboard.
- Find the weekday with the highest revenue.
What's next#
Lesson 62: Hands-on Project - Sales and Profit Summary Dashboard Add profit and margins, and find which products lose money.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



