Mathew K Analytics

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…

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.

📓 Full notebook

Download .ipynb

Pandas 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)
(541909, 8)
InvoiceNo StockCode Description Quantity InvoiceDate UnitPrice CustomerID Country
209268 555200 71459 HANGING JAM JAR T-LIGHT HOLDER 24 6/1/2011 12:05 0.85 17315.0 United Kingdom
207108 554974 21128 GOLD FISHING GNOME 4 5/27/2011 17:14 6.95 14031.0 United Kingdom
167085 550972 21086 SET/6 RED SPOTTY PAPER CUPS 4 4/21/2011 17:05 0.65 14031.0 United Kingdom
df[["Quantity", "UnitPrice"]].describe().round(2)
Quantity UnitPrice
count 541909.00 541909.00
mean 9.55 4.61
std 218.08 96.76
min -80995.00 -11062.06
25% 1.00 1.25
50% 3.00 2.08
75% 10.00 4.13
max 80995.00 38970.00

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()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[4], line 1
----> 1 df["InvoiceDate"].dt.month.head()

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\generic.py:6194, in NDFrame.__getattr__(self, name)
   6187 if (
   6188     name not in self._internal_names_set
   6189     and name not in self._metadata
   6190     and name not in self._accessors
   6191     and self._info_axis._can_hold_identifiers_and_holds_name(name)
   6192 ):
   6193     return self[name]
-> 6194 return object.__getattribute__(self, name)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\accessor.py:230, in Accessor.__get__(self, obj, cls)
    227 if obj is None:
    228     # we're accessing the attribute of the class, i.e., Dataset.geo
    229     return self._accessor
--> 230 return self._accessor(obj)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\indexes\accessors.py:698, in CombinedDatetimelikeProperties.__new__(cls, data)
    695 elif isinstance(data.dtype, PeriodDtype):
    696     return PeriodProperties(data, orig)
--> 698 raise AttributeError("Can only use .dt accessor with datetimelike values")

AttributeError: Can only use .dt accessor with datetimelike values
df["InvoiceDate"] = pd.to_datetime(df["InvoiceDate"],
                                   format="%m/%d/%Y %H:%M")
print(df["InvoiceDate"].min(), df["InvoiceDate"].max())
2010-12-01 08:26:00 2011-12-09 12:50:00
df["Revenue"] = df["Quantity"] * df["UnitPrice"]
df[["Quantity", "UnitPrice", "Revenue"]].head(3)
Quantity UnitPrice Revenue
0 6 2.55 15.30
1 6 3.39 20.34
2 8 2.75 22.00
cancelled = df["InvoiceNo"].str.startswith("C")
print(cancelled.sum(), round(cancelled.mean() * 100, 2))
9288 1.71

Quick check: are all the negative quantities cancellations?

neg = df["Quantity"] < 0
pd.crosstab(cancelled, neg)
Quantity False True
InvoiceNo
False 531285 1336
True 0 9288
odd = df[~cancelled & neg]
print(odd["UnitPrice"].max())
odd["Description"].value_counts().head(3)
0.0
Description
check      120
damages     45
damaged     42
Name: count, dtype: int64
real = ~cancelled & (df["UnitPrice"] > 0)
sales = df[real].copy()
print(len(sales), (sales["Quantity"] <= 0).sum())
530104 0

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)
10666684.54 19960 4338
units = sales["Quantity"].sum()
print(units, round(units / orders, 1))
5588376 280.0
guest = sales["CustomerID"].isna()
print(round(guest.mean() * 100, 1))
print(round(sales.loc[guest, "Revenue"].sum() / revenue * 100, 1))
24.9
16.5

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))
20.12
534.4
per_order = sales.groupby("InvoiceNo")["Revenue"].sum()
print(round(per_order.mean(), 2), round(per_order.median(), 2))
534.4 303.84
lost = -df.loc[cancelled, "Revenue"].sum()
cancel_rate = lost / (revenue + lost) * 100
print(round(lost, 2), round(cancel_rate, 2))
896812.49 7.76
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}")
Revenue          10,666,684.54
Orders               19,960.00
Customers             4,338.00
Avg order value         534.40
Cancelled %               7.76

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)
revenue orders customers
InvoiceDate
2011-09-30 1058590.0 1837 1266
2011-10-31 1154979.0 2040 1364
2011-11-30 1509496.0 2769 1664
2011-12-31 638793.0 819 615

Quick check: did sales really collapse in December 2011?

print(sales["InvoiceDate"].max())
2011-12-09 12:50:00
monthly = monthly.loc[:"2011-11"].copy()
monthly["aov"] = monthly["revenue"] / monthly["orders"]
monthly["growth_%"] = monthly["revenue"].pct_change() * 100
monthly.round(1).tail(4)
revenue orders customers aov growth_%
InvoiceDate
2011-08-31 759138.4 1361 935 557.8 5.6
2011-09-30 1058590.2 1837 1266 576.3 39.4
2011-10-31 1154979.3 2040 1364 566.2 9.1
2011-11-30 1509496.3 2769 1664 545.1 30.7
best = monthly["revenue"].idxmax()
worst = monthly["revenue"].idxmin()
print("Best:", best.strftime("%B %Y"))
print("Worst:", worst.strftime("%B %Y"))
Best: November 2011
Worst: February 2011
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)")
No description has been provided for this image
peak = monthly.loc["2011-09":"2011-11", "revenue"].sum()
share = peak / monthly["revenue"].sum() * 100
print(round(share, 1))
37.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)
revenue rev_3m
InvoiceDate
2011-08-31 759138.0 746700.0
2011-09-30 1058590.0 845650.0
2011-10-31 1154979.0 990903.0
2011-11-30 1509496.0 1241022.0

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"))
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[25], line 1
----> 1 sales.groupby("Country").agg(revenue=("Revenue", "total"))

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\groupby\generic.py:2291, in DataFrameGroupBy.aggregate(self, func, engine, engine_kwargs, *args, **kwargs)
   2288     kwargs["engine_kwargs"] = engine_kwargs
   2290 op = GroupByApply(self, func, args=args, kwargs=kwargs)
-> 2291 result = op.agg()
   2292 if not is_dict_like(func) and result is not None:
   2293     # GH #52849
   2294     if not self.as_index and is_list_like(func):

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\apply.py:294, in Apply.agg(self)
    291     return self.apply_str()
    293 if is_dict_like(func):
--> 294     return self.agg_dict_like()
    295 elif is_list_like(func):
    296     # we require a list, but not a 'str'
    297     return self.agg_list_like()

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\apply.py:511, in Apply.agg_dict_like(self)
    503 def agg_dict_like(self) -> DataFrame | Series:
    504     """
    505     Compute aggregation in the case of a dict-like argument.
    506 
   (...)
    509     Result of aggregation.
    510     """
--> 511     return self.agg_or_apply_dict_like(op_name="agg")

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\apply.py:1677, in GroupByApply.agg_or_apply_dict_like(self, op_name)
   1672     kwargs.update({"engine": engine, "engine_kwargs": engine_kwargs})
   1674 with com.temp_setattr(
   1675     obj, "as_index", True, condition=hasattr(obj, "as_index")
   1676 ):
-> 1677     result_index, result_data = self.compute_dict_like(
   1678         op_name, selected_obj, selection, kwargs
   1679     )
   1680 result = self.wrap_results_dict_like(selected_obj, result_index, result_data)
   1681 return result

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\apply.py:592, in Apply.compute_dict_like(self, op_name, selected_obj, selection, kwargs)
    590 if cols.ndim == 1:
    591     series = obj._gotitem(key, ndim=1, subset=cols)
--> 592     results.append(getattr(series, op_name)(how, **kwargs))
    593     keys.append(key)
    594 else:

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\groupby\generic.py:464, in SeriesGroupBy.aggregate(self, func, engine, engine_kwargs, *args, **kwargs)
    462 kwargs["engine"] = engine
    463 kwargs["engine_kwargs"] = engine_kwargs
--> 464 ret = self._aggregate_multiple_funcs(func, *args, **kwargs)
    465 if relabeling:
    466     # columns is not narrowed by mypy from relabeling flag
    467     assert columns is not None  # for mypy

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\groupby\generic.py:522, in SeriesGroupBy._aggregate_multiple_funcs(self, arg, *args, **kwargs)
    520     for idx, (name, func) in enumerate(arg):
    521         key = base.OutputKey(label=name, position=idx)
--> 522         results[key] = self.aggregate(func, *args, **kwargs)
    524 if any(isinstance(x, DataFrame) for x in results.values()):
    525     from pandas import concat

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\groupby\generic.py:456, in SeriesGroupBy.aggregate(self, func, engine, engine_kwargs, *args, **kwargs)
    454     if engine_kwargs is not None:
    455         kwargs["engine_kwargs"] = engine_kwargs
--> 456     return getattr(self, func)(*args, **kwargs)
    458 elif isinstance(func, abc.Iterable):
    459     # Catch instances of lists / tuples
    460     # but not the class list / tuple itself.
    461     func = maybe_mangle_lambdas(func)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\groupby\groupby.py:1115, in GroupBy.__getattr__(self, attr)
   1112 if attr in self.obj:
   1113     return self[attr]
-> 1115 raise AttributeError(
   1116     f"'{type(self).__name__}' object has no attribute '{attr}'"
   1117 )

AttributeError: 'SeriesGroupBy' object has no attribute '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)
revenue orders share_%
Country
United Kingdom 9025222.1 18019 84.6
Netherlands 285446.3 94 2.7
EIRE 283454.0 288 2.7
Germany 228867.1 457 2.1
France 209715.1 392 2.0

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)
Country
Netherlands       3036.66
EIRE               984.22
France             534.99
United Kingdom     500.87
Germany            500.80
Name: aov, dtype: float64

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)
9
CustomerID
14646.0    280206.0
12759.0      1531.0
12775.0      1386.0
Name: Revenue, dtype: float64
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")
No description has been provided for this image

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"))
November 2011 vs October 2011
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)
current previous change_%
revenue 1509496.33 1154979.30 30.69
orders 2769.00 2040.00 35.74
customers 1664.00 1364.00 21.99
aov 545.14 566.17 -3.71
import numpy as np
table["status"] = np.where(table["change_%"] > 0, "up", "down")
table[["change_%", "status"]].round(1)
change_% status
revenue 30.7 up
orders 35.7 up
customers 22.0 up
aov -3.7 down
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}%")
revenue      1,509,496  ^ +30.7%
orders           2,769  ^ +35.7%
customers        1,664  ^ +22.0%
aov                545  v -3.7%

Quick check: revenue rose, so how can average order value fall?

table.loc[["revenue", "orders"], "change_%"].round(1)
revenue    30.7
orders     35.7
Name: change_%, dtype: float64
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)
current 3m_avg vs_avg_%
revenue 1509496.3 990902.6 52.3
orders 2769.0 1746.0 58.6
customers 1664.0 1188.3 40.0
aov 545.1 566.7 -3.8

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()
No description has been provided for this image
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)
current previous status
revenue 1509496.33 1154979.30 up
orders 2769.00 2040.00 up
customers 1664.00 1364.00 up
aov 545.14 566.17 down

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())
4338 2.0
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)
65.6
orders
False     6.9
True     93.1
Name: revenue, dtype: float64
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))
61.4
first = known.groupby("CustomerID")["InvoiceDate"].min()
new = first.dt.to_period("M").value_counts().sort_index()
new.head(3)
InvoiceDate
2010-12    885
2011-01    417
2011-02    380
Freq: M, Name: count, dtype: int64
rest = new.loc["2011-01":"2011-11"]
print(rest.idxmin(), rest.min())
print(rest.idxmax(), rest.max())
2011-08 169
2011-03 452
once = rev_share[False] / (~repeat).sum()
again = rev_share[True] / repeat.sum()
print(f"Repeat customers spend {again / once:.1f} times as much")
Repeat customers spend 7.1 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#

  1. Build the monthly KPI table for Germany only.
  2. Add monthly units sold and items per order to the dashboard.
  3. 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.