Mathew K Analytics

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…

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 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)
(541909, 8)
InvoiceNo StockCode Description Quantity InvoiceDate UnitPrice CustomerID Country
0 536365 85123A WHITE HANGING HEART T-LIGHT HOLDER 6 12/1/2010 8:26 2.55 17850.0 United Kingdom
1 536365 71053 WHITE METAL LANTERN 6 12/1/2010 8:26 3.39 17850.0 United Kingdom
2 536365 84406B CREAM CUPID HEARTS COAT HANGER 8 12/1/2010 8:26 2.75 17850.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

Audit the raw file#

Problem: know exactly what is wrong before changing anything.

df.dtypes
InvoiceNo          str
StockCode          str
Description        str
Quantity         int64
InvoiceDate        str
UnitPrice      float64
CustomerID     float64
Country            str
dtype: object
df.isna().mean().round(3)
InvoiceNo      0.000
StockCode      0.000
Description    0.003
Quantity       0.000
InvoiceDate    0.000
UnitPrice      0.000
CustomerID     0.249
Country        0.000
dtype: float64
print(df.duplicated().sum())
print(df["InvoiceNo"].nunique())
5268
25900

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())
9288
True
codes = df["StockCode"]
odd = codes[~codes.str.match(r"\d{5}")]
odd.value_counts().head(8)
StockCode
POST            1256
DOT              710
M                571
C2               144
D                 77
S                 63
BANK CHARGES      37
AMAZONFEE         34
Name: count, dtype: int64

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)
---------------------------------------------------------------------------
IntCastingNaNError                        Traceback (most recent call last)
Cell In[9], line 1
----> 1 df["CustomerID"].astype(int)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\generic.py:6529, in NDFrame.astype(self, dtype, copy, errors)
   6525     results = [ser.astype(dtype, errors=errors) for _, ser in self.items()]
   6527 else:
   6528     # else, only a single dtype is given
-> 6529     new_data = self._mgr.astype(dtype=dtype, errors=errors)
   6530     res = self._constructor_from_mgr(new_data, axes=new_data.axes)
   6531     return res.__finalize__(self, method="astype")

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\internals\managers.py:627, in BaseBlockManager.astype(self, dtype, errors)
    626 def astype(self, dtype, errors: str = "raise") -> Self:
--> 627     return self.apply("astype", dtype=dtype, errors=errors)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\internals\managers.py:445, in BaseBlockManager.apply(self, f, align_keys, **kwargs)
    443         applied = b.apply(f, **kwargs)
    444     else:
--> 445         applied = getattr(b, f)(**kwargs)
    446     result_blocks = extend_blocks(applied, result_blocks)
    448 out = type(self).from_blocks(result_blocks, [ax.view() for ax in self.axes])

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\internals\blocks.py:607, in Block.astype(self, dtype, errors, squeeze)
    604         raise ValueError("Can not squeeze with more than one column.")
    605     values = values[0, :]  # type: ignore[call-overload]
--> 607 new_values = astype_array_safe(values, dtype, errors=errors)
    609 new_values = maybe_coerce_values(new_values)
    611 refs = None

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\dtypes\astype.py:240, in astype_array_safe(values, dtype, copy, errors)
    237     dtype = dtype.numpy_dtype
    239 try:
--> 240     new_values = astype_array(values, dtype, copy=copy)
    241 except (ValueError, TypeError):
    242     # e.g. _astype_nansafe can fail on object-dtype of strings
    243     #  trying to convert to float
    244     if errors == "ignore":

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\dtypes\astype.py:185, in astype_array(values, dtype, copy)
    182     values = values.astype(dtype, copy=copy)
    184 else:
--> 185     values = _astype_nansafe(values, dtype, copy=copy)
    187 # in pandas we don't store numpy str dtypes, so convert to object
    188 if isinstance(dtype, np.dtype) and issubclass(values.dtype.type, str):

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\dtypes\astype.py:102, in _astype_nansafe(arr, dtype, copy, skipna)
     97     return lib.ensure_string_array(
     98         arr, skipna=skipna, convert_na_value=False
     99     ).reshape(shape)
    101 elif np.issubdtype(arr.dtype, np.floating) and dtype.kind in "iu":
--> 102     return _astype_float_to_int_nansafe(arr, dtype, copy)
    104 elif arr.dtype == object:
    105     # if we have a datetime/timedelta array of objects
    106     # then coerce to datetime64[ns] and use DatetimeArray.astype
    108     if lib.is_np_dtype(dtype, "M"):

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\dtypes\astype.py:146, in _astype_float_to_int_nansafe(values, dtype, copy)
    142 """
    143 astype with a check preventing converting NaN to a meaningless integer value.
    144 """
    145 if not np.isfinite(values).all():
--> 146     raise IntCastingNaNError(
    147         "Cannot convert non-finite values (NA or inf) to integer."
    148         "Replace or remove non-finite values or cast to an integer type"
    149         "that supports these values (e.g. 'Int64')"
    150     )
    151 if dtype.kind == "u":
    152     # GH#45151
    153     if not (values >= 0).all():

IntCastingNaNError: Cannot convert non-finite values (NA or inf) to integer.Replace or remove non-finite values or cast to an integer typethat supports these values (e.g. 'Int64')
ids = df["CustomerID"].dropna().astype(int)
print(ids.head(3).tolist())
[17850, 17850, 17850]
fmt = "%m/%d/%Y %H:%M"
df["InvoiceDate"] = pd.to_datetime(df["InvoiceDate"], format=fmt)
print(df["InvoiceDate"].min(), df["InvoiceDate"].max())
2010-12-01 08:26:00 2011-12-09 12:50:00
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))
391153
cols = ["InvoiceNo", "Description", "Quantity", "Revenue"]
clean.nlargest(3, "Revenue")[cols]
InvoiceNo Description Quantity Revenue
540421 581483 PAPER CRAFT , LITTLE BIRDIE 80995 168469.6
61619 541431 MEDIUM CERAMIC TOP STORAGE JAR 74215 77183.6
222680 556444 PICNIC BASKET WICKER 60 PIECES 60 38970.0
big = df[df["Quantity"] == -80995]
big[["InvoiceNo", "Description", "Quantity", "CustomerID"]]
InvoiceNo Description Quantity CustomerID
540422 C581484 PAPER CRAFT , LITTLE BIRDIE -80995 16446.0
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")
_merge
left_only     385932
both            5221
right_only         0
Name: count, dtype: int64

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())
0.712
8199424
4321 18162

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)
InvoiceDate
2010-12     551592.0
2011-01     453016.0
2011-02     435946.0
2011-03     565995.0
2011-04     427055.0
2011-05     647181.0
2011-06     600076.0
2011-07     577445.0
2011-08     620151.0
2011-09     921786.0
2011-10     946162.0
2011-11    1112575.0
2011-12     340446.0
Freq: M, Name: Revenue, dtype: float64

Quick check: why does December 2011 look so weak?

print(clean["InvoiceDate"].max())
2011-12-09 12:50:00
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()
No description has been provided for this image
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)
InvoiceDate
Monday       1272954.0
Tuesday      1535748.0
Wednesday    1519074.0
Thursday     1892850.0
Friday       1212401.0
Saturday           NaN
Sunday        766396.0
Name: Revenue, dtype: float64

Common mistake: calling .dt on a column name

clean.groupby("InvoiceDate".dt.hour)["Revenue"].sum()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[21], line 1
----> 1 clean.groupby("InvoiceDate".dt.hour)["Revenue"].sum()

AttributeError: 'str' object has no attribute 'dt'
hour = clean["InvoiceDate"].dt.hour
by_hour = clean.groupby(hour)["Revenue"].sum()
print(by_hour.idxmax(), round(by_hour.max()))
12 1309630
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()
No description has been provided for this image

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)
Country
United Kingdom    0.822
Netherlands       0.034
EIRE              0.029
Germany           0.025
France            0.022
Name: Revenue, dtype: float64
abroad = clean.query("Country != 'United Kingdom'")
print(abroad["Country"].nunique())
print(abroad["CustomerID"].nunique())
36
415
product = clean.groupby("Description")
top = product.agg(revenue=("Revenue", "sum"),
                  buyers=("CustomerID", "nunique"))
top.nlargest(5, "revenue").round(0)
revenue buyers
Description
REGENCY CAKESTAND 3 TIER 134365.0 866
WHITE HANGING HEART T-LIGHT HOLDER 88741.0 852
JUMBO BAG RED RETROSPOT 79650.0 632
PARTY BUNTING 67293.0 706
ASSORTED COLOUR BIRD ORNAMENT 56301.0 676

Your turn#

Which 3 products were sold in the most countries?

reach = product["Country"].nunique()
reach.nlargest(3)
Description
REGENCY CAKESTAND 3 TIER    29
JAM MAKING SET PRINTED      25
JAM MAKING SET WITH JARS    25
Name: Country, dtype: int64
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)
InvoiceDate
2010-12    0.043
2011-01    0.001
2011-02    0.001
2011-03    0.001
2011-04    0.001
2011-05    0.002
2011-06    0.004
2011-07    0.017
2011-08    0.034
2011-09    0.083
2011-10    0.095
2011-11    0.096
2011-12    0.070
Freq: M, Name: Revenue, dtype: float64

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)
recency frequency monetary
count 4321.0 4321.0 4321.0
mean 93.1 4.2 1897.6
std 100.4 7.5 8190.5
min 1.0 1.0 2.9
25% 18.0 1.0 301.3
50% 51.0 2.0 653.8
75% 144.0 5.0 1608.1
max 374.0 202.0 277460.4

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))
864 0.734

Common mistake: quartiles on a column full of ties

pd.qcut(rfm["frequency"], 4, labels=[1, 2, 3, 4])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[31], line 1
----> 1 pd.qcut(rfm["frequency"], 4, labels=[1, 2, 3, 4])

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\reshape\tile.py:384, in qcut(x, q, labels, retbins, precision, duplicates)
    380     quantiles = q
    382 bins = x_idx.to_series().dropna().quantile(quantiles)
--> 384 fac, bins = _bins_to_cuts(
    385     x_idx,
    386     Index(bins),
    387     labels=labels,
    388     precision=precision,
    389     include_lowest=True,
    390     duplicates=duplicates,
    391 )
    393 return _postprocess_for_cut(fac, bins, retbins, original)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\reshape\tile.py:487, in _bins_to_cuts(x_idx, bins, right, labels, precision, include_lowest, duplicates, ordered)
    485 if len(unique_bins) < len(bins) and len(bins) != 2:
    486     if duplicates == "raise":
--> 487         raise ValueError(
    488             f"Bin edges must be unique: {bins!r}.\n"
    489             f"You can drop duplicate edges by setting the 'duplicates' kwarg"
    490         )
    491     bins = unique_bins
    493 side: Literal["left", "right"] = "left" if right else "right"

ValueError: Bin edges must be unique: Index([1.0, 1.0, 2.0, 5.0, 202.0], dtype='float64', name='frequency').
You can drop duplicate edges by setting the 'duplicates' kwarg
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)
recency R frequency F
CustomerID
12347 2 4 7 4
12348 75 2 4 3
12349 19 3 1 1
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()
segment
Champions    1522
Lapsed       1510
Promising     651
At risk       638
Name: count, dtype: int64
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)
customers revenue rev_share
segment
Champions 1522 6282882.38 0.77
At risk 638 901090.26 0.11
Lapsed 1510 698710.44 0.09
Promising 651 316740.82 0.04

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)
CustomerID cohort month age
0 17850 2010-12 2010-12 0
1 17850 2010-12 2010-12 0
2 17850 2010-12 2010-12 0
counts = clean.pivot_table(index="cohort", columns="age",
                           values="CustomerID", aggfunc="nunique")
print(counts[0].head(4))
cohort
2010-12    882.0
2011-01    413.0
2011-02    381.0
2011-03    450.0
Freq: M, Name: 0, dtype: float64
retention = counts.div(counts[0], axis=0)
retention.iloc[:5, :6].round(2)
age 0 1 2 3 4 5
cohort
2010-12 1.0 0.36 0.32 0.38 0.36 0.40
2011-01 1.0 0.21 0.27 0.23 0.32 0.29
2011-02 1.0 0.19 0.19 0.28 0.27 0.24
2011-03 1.0 0.14 0.25 0.19 0.22 0.17
2011-04 1.0 0.21 0.20 0.21 0.20 0.23
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()
No description has been provided for this image

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))
2010-12 0.363
0.189

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))
451.46 1.017
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
kpi value
0 Revenue (GBP) 8,199,424
1 Customers 4,321
2 Avg order (GBP) 451.46
3 Top 20% share 73.4%
4 Month-1 return 20.3%
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)
True
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.")
Revenue grew 102% from Dec 2010 to Nov 2011.
1522 champions bring 77% 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#

  1. Repeat the RFM segments for customers outside the UK only.
  2. Find each country's busiest month with groupby and idxmax.
  3. 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.