Pulse Data Hub

Data Science in E-Commerce: Customer Retention, Tested

Data Science in E-Commerce: Customer Retention, Tested

Data science in e-commerce usually gets described through recommendation engines and dynamic pricing. This article starts with a plainer question that every online shop can answer from its own order table: how many customers come back, and can anything about the first order tell you who will? The analysis runs on real transactions, and every number below is the output of the code shown.

Bar chart: share of customers who ordered again within 90 days rises from 36.3% for the smallest first orders to 55.1% for the largest
Customers split into four equal groups by first-order value; the share who ordered again within 90 days rises with every step.

The data: one year of orders from an online shop

The data is the UCI Online Retail dataset: 541,909 invoice lines from a UK-based online retailer between December 2010 and December 2011. According to the dataset description, many customers are wholesalers, so order values are larger than in a typical consumer shop. The same file is used in our retail data science project and the PySpark tutorial; here the focus is customer behaviour. Code was run with pandas 3.0.5 and scikit-learn 1.9.1.

import pandas as pd

url = ("https://raw.githubusercontent.com/databricks/Spark-The-Definitive-Guide/"
       "master/data/retail-data/all/online-retail-dataset.csv")
raw = pd.read_csv(url, parse_dates=["InvoiceDate"])

# keep real sales to known customers: no cancellations ("C" invoices), positive qty/price
d = raw[raw.CustomerID.notna()
        & ~raw.InvoiceNo.astype(str).str.startswith("C")
        & (raw.Quantity > 0) & (raw.UnitPrice > 0)].copy()
d["revenue"] = d.Quantity * d.UnitPrice
print(len(raw), "lines ->", len(d), "clean lines,",
      d.CustomerID.nunique(), "customers,", d.InvoiceNo.nunique(), "orders,",
      round(d.revenue.sum()), "revenue")

orders = d.groupby(["CustomerID", "InvoiceNo"]).revenue.sum().reset_index()
n = orders.groupby("CustomerID").size()
spend = orders.groupby("CustomerID").revenue.sum()
print("one order only:", round((n == 1).mean(), 3),
      "| five or more:", round((n >= 5).mean(), 3))
print("revenue share, five-or-more group:", round(spend[n >= 5].sum() / spend.sum(), 3))
print("order value mean", round(orders.revenue.mean(), 1),
      "median", round(orders.revenue.median(), 1))
541909 lines -> 397884 clean lines, 4338 customers, 18532 orders, 8911408 revenue
one order only: 0.344 | five or more: 0.257
revenue share, five-or-more group: 0.712
order value mean 480.9 median 303.0

The cleaning keeps 397,884 of the 541,909 lines. The main loss is 135,080 lines with no customer ID, which cannot be tracked over time. Among the 4,338 customers who remain, 34.4% placed a single order, and the 25.7% who placed five or more produced 71.2% of the revenue. A shop in this position gets most of its income from a minority of repeat buyers, which is why retention is worth measuring before anything fancier.

Cohort retention: how many customers come back?

A cohort table groups customers by the month of their first purchase and counts how many order again in later months. Because the file starts in December 2010, the first cohort contains every customer active that month, including long-standing ones, so it is not a true set of new customers. The other cohorts start in January 2011 or later and are cleaner.

# cohort retention: share of each first-purchase month still ordering k months later
d["month"] = d.InvoiceDate.dt.to_period("M")
d["cohort"] = d.CustomerID.map(d.groupby("CustomerID").month.min())
d["k"] = (d.month - d.cohort).apply(lambda x: x.n)
active = d.groupby(["cohort", "k"]).CustomerID.nunique().unstack()
c = active.loc[:"2011-06"]                       # cohorts with 6 months of follow-up
print((c[[1, 3, 6]].div(c[0], axis=0)).round(3).head(7))
print("pooled:", {k: round(c[k].sum() / c[0].sum(), 3) for k in (1, 3, 6)})
k            1      3      6
cohort                      
2010-12  0.366  0.384  0.363
2011-01  0.221  0.230  0.247
2011-02  0.187  0.284  0.253
2011-03  0.150  0.199  0.268
2011-04  0.213  0.210  0.217
2011-05  0.190  0.173  0.264
2011-06  0.174  0.264  0.095
pooled: {1: 0.242, 3: 0.274, 6: 0.272}

About a quarter of each cohort orders again in the month after the first purchase, and roughly the same share is still ordering three and six months later. Retention does not decay smoothly here because the shop is seasonal and many customers buy in bursts; a smooth churn curve from a textbook would be misleading for this business. The June 2011 cohort shows 9.5% at month six, but that month falls in the final weeks of the file, so it is the least reliable cell in the table.

Does the first order predict a return visit?

For each customer, the next block checks whether they ordered again within 90 days of their first order (on a different day), using only customers whose first order is early enough for 90 days of follow-up to exist. Customers are then split into four equal groups by the value of that first order.

import pandas as pd, numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
# d is the clean table from the first block
first = d.groupby("CustomerID").InvoiceDate.min()
d["first"] = d.CustomerID.map(first)

# did the customer order again within 90 days (and not on the same day)?
later = d[d.InvoiceDate > d["first"] + pd.Timedelta(days=1)]
back = set(later[later.InvoiceDate <= later["first"] + pd.Timedelta(days=90)].CustomerID)

f = d[d.InvoiceDate == d["first"]].groupby("CustomerID").agg(
    value=("revenue", "sum"), items=("Quantity", "sum"), lines=("StockCode", "nunique"))
f["back"] = f.index.isin(back)
f = f[first[f.index] <= pd.Timestamp("2011-09-09")]   # 90 days of follow-up exist
print(len(f), "customers; came back within 90 days:", round(f.back.mean(), 3))

f["quartile"] = pd.qcut(f.value, 4, labels=["Q1 smallest", "Q2", "Q3", "Q4 largest"])
print(f.groupby("quartile", observed=True).agg(
    customers=("back", "size"), came_back=("back", "mean"), median_value=("value", "median")).round(3))

X = np.log1p(f[["value", "items"]]).assign(lines=f.lines)
Xtr, Xte, ytr, yte = train_test_split(X, f.back, test_size=0.25, random_state=0, stratify=f.back)
m = LogisticRegression(max_iter=1000).fit(Xtr, ytr)
print("AUC", round(roc_auc_score(yte, m.predict_proba(Xte)[:, 1]), 3), "on", len(yte), "customers")
3362 customers; came back within 90 days: 0.452
             customers  came_back  median_value
quartile                                       
Q1 smallest        841      0.363        114.85
Q2                 841      0.405        222.99
Q3                 839      0.490        341.40
Q4 largest         841      0.551        683.64
AUC 0.593 on 841 customers

Of 3,362 eligible customers, 45.2% ordered again within 90 days. The return rate climbs from 36.3% for the smallest first orders (median 114.85) to 55.1% for the largest (median 683.64). That is a real gradient, but a weak predictor: a logistic regression on first-order value, quantity and number of distinct products reaches an AUC of 0.593 on 841 held-out customers, where 0.5 is a coin flip and 1.0 is perfect. First-order size is a useful signal for a segment report, not a reliable way to pick individual customers for a campaign.

What this means for an online shop

The honest conclusion from this one dataset is modest. Repeat buyers carry the revenue, about a quarter of each cohort comes back in any given month, and bigger first orders return more often, but a simple model cannot sort individuals well. That is typical of early-life customer data, and it is the reason mature shops add browsing behaviour, product categories and acquisition channel, none of which exist in this file. Two cautions apply. First, the data covers one year of a seasonal wholesale-heavy business, so the rates will not transfer to a consumer fashion shop. Second, a 90-day window is a choice; a different window changes every rate above. Before building a recommender or a pricing model, measure retention like this and check that the data supports the question. For related techniques see our SQL for data analysis guide and the broader data science by industry overview; scikit-learn behaviour is documented in the LogisticRegression reference.

Frequently asked questions

What is data science used for in e-commerce?

Common uses are customer segmentation, retention and churn analysis, demand forecasting, product recommendations, pricing and fraud detection. Most start with the same step shown here: a clean order table and a clear definition of what counts as a returning customer.

Which dataset can I practise e-commerce analysis on?

The UCI Online Retail dataset used in this article is free to download and contains 541,909 invoice lines. It has no browsing or marketing data, so it suits retention, basket and revenue analysis rather than conversion modelling.

Do I need machine learning to improve retention?

Not at first. The cohort table and quartile split above need only grouping and counting, and they already show where the revenue sits. Models become useful once you have richer features and a specific action, such as who receives a discount.

Newsletter Signup Form

Latest tutorials

Latest articles

On this page
Verified by MonsterInsights