Lesson 65 · Pandas Full Course
Pandas Capstone: Full Sales Analytics Project on 500K Real Rows | Pandas Course #65
In this lesson you'll be able to: Audit and clean half a million raw sales rows in one pipeline Track revenue by month, weekday and hour Rank countries and…
- CoursePandas Full Course
- Lesson65 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 65: Capstone Project - Sales Analytics with Pandas#
In this lesson you'll be able to:
- Audit and clean half a million raw sales rows in one pipeline
- Track revenue by month, weekday and hour
- Rank countries and products, and search product text
- Score customers with RFM and measure who comes back
- Deliver a capstone report built from every part of the series Dataset: a UK online gift retailer, 541,909 invoice lines (data/pandas/online_retail.csv.gz)
Warm-up: look at the numbers first#
Lesson 64 began by checking the target column. Same habit, new data.
import pandas as pd
df = pd.read_csv("data/pandas/online_retail.csv.gz")
print(df.shape)
df.head(3)
df[["Quantity", "UnitPrice"]].describe().round(2)
Audit the raw file#
Problem: know exactly what is wrong before changing anything.
df.dtypes
df.isna().mean().round(3)
print(df.duplicated().sum())
print(df["InvoiceNo"].nunique())
Quick check: invoice numbers starting with C are cancellations. How many lines are there?
cancel = df["InvoiceNo"].str.startswith("C")
print(cancel.sum())
print((df.loc[cancel, "Quantity"] < 0).all())
codes = df["StockCode"]
odd = codes[~codes.str.match(r"\d{5}")]
odd.value_counts().head(8)
Clean it in one readable pipeline#
Problem: many fixes, applied in a clear order you can re-run.
Common mistake: converting a column with gaps to whole numbers
df["CustomerID"].astype(int)
ids = df["CustomerID"].dropna().astype(int)
print(ids.head(3).tolist())
fmt = "%m/%d/%Y %H:%M"
df["InvoiceDate"] = pd.to_datetime(df["InvoiceDate"], format=fmt)
print(df["InvoiceDate"].min(), df["InvoiceDate"].max())
fees = ["POST", "DOT", "M", "C2", "D", "S", "BANK CHARGES",
"AMAZONFEE", "CRUK"]
clean = (
df.drop_duplicates()
.query("Quantity > 0 and UnitPrice > 0")
.dropna(subset=["CustomerID"])
.loc[lambda d: ~d["StockCode"].isin(fees)]
.assign(CustomerID=lambda d: d["CustomerID"].astype(int),
Revenue=lambda d: d["Quantity"] * d["UnitPrice"])
)
print(len(clean))
cols = ["InvoiceNo", "Description", "Quantity", "Revenue"]
clean.nlargest(3, "Revenue")[cols]
big = df[df["Quantity"] == -80995]
big[["InvoiceNo", "Description", "Quantity", "CustomerID"]]
keys = ["CustomerID", "StockCode", "Quantity"]
undo = df[cancel].assign(Quantity=lambda d: -d["Quantity"])
undo = undo[keys].drop_duplicates()
m = clean.merge(undo, on=keys, how="left", indicator=True)
print(m["_merge"].value_counts())
clean = m[m["_merge"] == "left_only"].drop(columns="_merge")
Your turn#
What share of the original lines and revenue survived cleaning?
print(round(len(clean) / len(df), 3))
print(round(clean["Revenue"].sum()))
print(clean["CustomerID"].nunique(), clean["InvoiceNo"].nunique())
Track revenue by month, weekday and hour#
Problem: when do customers buy, and is the business growing?
month = clean["InvoiceDate"].dt.to_period("M")
monthly = clean.groupby(month)["Revenue"].sum()
monthly.round(0)
Quick check: why does December 2011 look so weak?
print(clean["InvoiceDate"].max())
import matplotlib.pyplot as plt
full = monthly.iloc[:-1]
ax = full.plot(kind="bar", rot=45, figsize=(8, 4))
ax.set_title("Monthly revenue, Dec 2010 to Nov 2011")
ax.set_xlabel("Month")
ax.set_ylabel("Revenue (GBP)")
plt.show()
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday", "Sunday"]
day = clean["InvoiceDate"].dt.day_name()
by_day = clean.groupby(day)["Revenue"].sum().reindex(days)
by_day.round(0)
Common mistake: calling .dt on a column name
clean.groupby("InvoiceDate".dt.hour)["Revenue"].sum()
hour = clean["InvoiceDate"].dt.hour
by_hour = clean.groupby(hour)["Revenue"].sum()
print(by_hour.idxmax(), round(by_hour.max()))
import seaborn as sns
grid = clean.pivot_table(index=day, columns=hour,
values="Revenue", aggfunc="sum")
grid = grid.reindex([d for d in days if d in grid.index])
ax = sns.heatmap(grid / 1000, cmap="Blues")
ax.set_title("Revenue by weekday and hour (thousand GBP)")
ax.set_xlabel("Hour of day")
ax.set_ylabel("")
plt.show()
Rank countries and products#
Problem: which markets and products carry the business?
country = clean.groupby("Country")["Revenue"].sum()
share = (country / country.sum()).nlargest(5)
share.round(3)
abroad = clean.query("Country != 'United Kingdom'")
print(abroad["Country"].nunique())
print(abroad["CustomerID"].nunique())
product = clean.groupby("Description")
top = product.agg(revenue=("Revenue", "sum"),
buyers=("CustomerID", "nunique"))
top.nlargest(5, "revenue").round(0)
Your turn#
Which 3 products were sold in the most countries?
reach = product["Country"].nunique()
reach.nlargest(3)
xmas = clean["Description"].str.contains("CHRISTMAS", na=False)
xmas_rev = clean[xmas].groupby(month[xmas])["Revenue"].sum()
xmas_share = (xmas_rev / monthly).fillna(0)
xmas_share.round(3)
Score customers with RFM#
Recency, Frequency, Monetary: how recently, how often, how much.
snap = clean["InvoiceDate"].max() + pd.Timedelta(days=1)
rfm = clean.groupby("CustomerID").agg(
last=("InvoiceDate", "max"),
frequency=("InvoiceNo", "nunique"),
monetary=("Revenue", "sum"),
)
rfm["recency"] = (snap - rfm["last"]).dt.days
rfm[["recency", "frequency", "monetary"]].describe().round(1)
Quick check: what share of revenue comes from the top 20% of customers?
spend = rfm["monetary"].sort_values(ascending=False)
top_n = int(len(spend) * 0.2)
pareto = spend.iloc[:top_n].sum() / spend.sum()
print(top_n, round(pareto, 3))
Common mistake: quartiles on a column full of ties
pd.qcut(rfm["frequency"], 4, labels=[1, 2, 3, 4])
order = rfm["frequency"].rank(method="first")
rfm["F"] = pd.qcut(order, 4, labels=[1, 2, 3, 4]).astype(int)
rfm["R"] = pd.qcut(rfm["recency"], 4, labels=[4, 3, 2, 1])
rfm["R"] = rfm["R"].astype(int)
rfm[["recency", "R", "frequency", "F"]].head(3)
import numpy as np
recent, loyal = rfm["R"] >= 3, rfm["F"] >= 3
rules = [recent & loyal, recent, loyal]
names = ["Champions", "Promising", "At risk"]
rfm["segment"] = np.select(rules, names, default="Lapsed")
rfm["segment"].value_counts()
seg = rfm.groupby("segment").agg(customers=("monetary", "size"),
revenue=("monetary", "sum"))
seg["rev_share"] = seg["revenue"] / seg["revenue"].sum()
seg.sort_values("revenue", ascending=False).round(2)
Measure who comes back with cohorts#
Problem: group customers by first purchase month, then track them.
first = clean.groupby("CustomerID")["InvoiceDate"].transform("min")
clean["cohort"] = first.dt.to_period("M")
clean["month"] = clean["InvoiceDate"].dt.to_period("M")
y = clean["month"].dt.year - clean["cohort"].dt.year
m = clean["month"].dt.month - clean["cohort"].dt.month
clean["age"] = y * 12 + m
clean[["CustomerID", "cohort", "month", "age"]].head(3)
counts = clean.pivot_table(index="cohort", columns="age",
values="CustomerID", aggfunc="nunique")
print(counts[0].head(4))
retention = counts.div(counts[0], axis=0)
retention.iloc[:5, :6].round(2)
ax = sns.heatmap(retention.iloc[:, 1:], cmap="Greens",
vmin=0, vmax=0.5)
ax.set_title("Share of each cohort buying again")
ax.set_xlabel("Months since first purchase")
ax.set_ylabel("First purchase month")
plt.show()
Quick check: which cohort has the best month-1 retention?
month1 = retention[1].dropna()
print(month1.idxmax(), round(month1.max(), 3))
print(round(month1.drop(month1.idxmax()).mean(), 3))
Capstone report: the numbers for the board#
Question: how healthy is this business, in five numbers?
Plan: compute the KPIs, build a table, save it, read it back, conclude.
revenue = clean["Revenue"].sum()
orders = clean["InvoiceNo"].nunique()
aov = revenue / orders
growth = full.iloc[-1] / full.iloc[0] - 1
print(round(aov, 2), round(growth, 3))
report = pd.DataFrame({
"kpi": ["Revenue (GBP)", "Customers", "Avg order (GBP)",
"Top 20% share", "Month-1 return"],
"value": [f"{revenue:,.0f}", f"{len(rfm):,}", f"{aov:.2f}",
f"{pareto:.1%}", f"{month1.mean():.1%}"],
})
report
import os
os.makedirs("output/pandas", exist_ok=True)
path = "output/pandas/l65_board_report.csv"
report.to_csv(path, index=False)
pd.read_csv(path).equals(report)
n_champ = seg.loc["Champions", "customers"]
champ_share = seg.loc["Champions", "rev_share"]
print(f"Revenue grew {growth:.0%} from Dec 2010 to Nov 2011.")
print(f"{n_champ} champions bring {champ_share:.0%} of revenue.")
Recap: the whole series in one project#
- Foundations and cleaning: audit first, then one clear pipeline
- Selecting and transforming: query, isin, str methods, assign
- Grouping and combining: agg, pivot_table, merge with indicator
- Dates and visuals: periods, day names, bar charts, heatmaps
- Projects: RFM scores and cohorts turn rows into decisions
Challenges#
- Repeat the RFM segments for customers outside the UK only.
- Find each country's busiest month with groupby and idxmax.
- Add the at-risk customers' revenue to the board report.
What's next#
That's the Pandas series complete: 65 lessons, raw file to report. Next on the channel: the Python for Machine Learning series. Your cleaned DataFrames become the input to real models.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



