Retailers collect more data than almost any other business: every sale, return, basket, price change, delivery and loyalty-card scan. Data science in retail is the work of turning that data into decisions: how much stock to order, which customers to win back, which products to recommend together and what to charge.
This article covers the main applications of data science in the retail industry, then works through a hands-on Python project on 541,909 real transactions from a UK online retailer. You’ll measure seasonality, split customers into RFM segments, find products that sell together and build a model that predicts which customers will buy again. All code runs as shown, and every number below is the output it produced.
How data science is used in retail
| Application | Question it answers | Typical data | Common methods |
|---|---|---|---|
| Demand forecasting | How many units will each store or channel sell next week? | Sales history, calendar, promotions, prices, weather | Seasonal baselines, gradient boosting, time-series models |
| Inventory and supply chain | How much to order, when, and where to hold it? | Forecasts, stock levels, lead times, supplier data | Safety-stock formulas, simulation, optimization |
| Customer segmentation and lifetime value | Who are our best customers, and what is each one worth? | Transactions, loyalty data | RFM, k-means clustering, BG/NBD lifetime value models |
| Churn and retention | Which customers are likely to stop buying? | Purchase history, engagement, complaints | Classification (logistic regression, gradient boosting) |
| Recommendations and basket analysis | What else will this customer want? | Baskets, browsing, ratings | Association rules, collaborative filtering |
| Pricing and markdowns | What price maximizes margin without losing volume? | Prices, sales, competitor prices, stock | Price-elasticity models, markdown optimization |
| Promotions and marketing | Did the campaign actually add sales? | Campaign exposure, sales, control groups | A/B tests, uplift modelling, marketing mix models |
| Fraud and returns | Which orders or returns are suspicious? | Orders, payments, return history | Anomaly detection, classification |
Most of these share the same raw material: a transaction table with one row per item sold. That is why a single sales dataset is enough to try several of them, as the project below does. Forecasting and inventory decide how much money is tied up in stock; segmentation, churn and recommendations decide how much each customer spends; pricing and promotions decide margin. A small improvement in any of them multiplies across thousands of products and customers.
The rest of the industry picture, and how other sectors use the same techniques, is in our guide to data science by industry. Data science in logistics covers the warehouse and delivery side in more depth.
Python project: analyse 500,000 real retail transactions
The data is the Online Retail dataset from the UCI Machine Learning Repository: every sale made by a UK-based online gift retailer between 1 December 2010 and 9 December 2011. Many of its customers are small businesses buying wholesale, which you’ll see in the order sizes. GitHub hosts a copy in the repository for the book Spark: The Definitive Guide, so pandas can load it straight from a URL (about 45 MB). You need pandas, Matplotlib and scikit-learn.
1. Load the data
import pandas as pd
URL = ("https://raw.githubusercontent.com/databricks/Spark-The-Definitive-Guide/"
"master/data/retail-data/all/online-retail-dataset.csv")
df = pd.read_csv(URL, dtype={"InvoiceNo": str, "StockCode": str, "CustomerID": str})
df["InvoiceDate"] = pd.to_datetime(df["InvoiceDate"], format="%m/%d/%Y %H:%M")
print(df.shape)
print(df.head(3).to_string())Output:
(541909, 8)
InvoiceNo StockCode Description Quantity InvoiceDate UnitPrice CustomerID Country
0 536365 85123A WHITE HANGING HEART T-LIGHT HOLDER 6 2010-12-01 08:26:00 2.55 17850 United Kingdom
1 536365 71053 WHITE METAL LANTERN 6 2010-12-01 08:26:00 3.39 17850 United Kingdom
2 536365 84406B CREAM CUPID HEARTS COAT HANGER 8 2010-12-01 08:26:00 2.75 17850 United KingdomEach row is one product on one invoice: Quantity units at UnitPrice (in pounds sterling). Reading the IDs as strings keeps codes like 85123A intact and stops pandas turning customer IDs into floats.
2. Clean it
Raw retail data always needs cleaning, and the decisions you make here change every number later. This dataset has three issues: cancelled invoices (numbers starting with C, with negative quantities), lines that aren’t products (postage, bank charges, Amazon fees and manual adjustments, whose stock codes don’t start with five digits) and lines with no customer ID.
cancelled = df["InvoiceNo"].str.startswith("C")
print(f"Cancelled lines: {cancelled.sum():,}")
print(f"Lines without a customer ID: {df['CustomerID'].isna().sum():,}")
sales = df[~cancelled & (df["Quantity"] > 0) & (df["UnitPrice"] > 0)]
sales = sales[sales["StockCode"].str.match(r"^\d{5}")].copy() # products only
sales["Revenue"] = sales["Quantity"] * sales["UnitPrice"]
print(f"{len(sales):,} lines, {sales['InvoiceNo'].nunique():,} orders, "
f"{sales['CustomerID'].nunique():,} customers, "
f"revenue £{sales['Revenue'].sum():,.0f}")Output:
Cancelled lines: 9,288
Lines without a customer ID: 135,080
527,725 lines, 19,773 orders, 4,334 customers, revenue £10,271,035A quarter of the lines (25%) have no customer ID, probably guest checkouts. They are real sales, so they stay in for revenue analysis, but customer-level analysis has to drop them. After cleaning, 85% of revenue can still be linked to a customer. Be explicit about choices like this in any retail analysis; “revenue” can differ by several percent depending on how returns and fees are treated.
3. Sales over time: find the seasonality
import matplotlib.pyplot as plt
monthly = sales.set_index("InvoiceDate")["Revenue"].resample("MS").sum()
monthly = monthly[:-1] # December 2011 stops on the 9th
print((monthly / 1000).round().astype(int).to_string())
fig, ax = plt.subplots(figsize=(8, 4))
colors = ["#c8242c" if m.month == 11 else "#1f4e79" for m in monthly.index]
ax.bar(monthly.index.strftime("%b %y"), monthly / 1000, color=colors)
ax.set_title("Monthly revenue, December 2010 to November 2011")
ax.set_ylabel("Revenue (£ thousands)")
ax.tick_params(axis="x", labelrotation=45)
ax.spines[["top", "right"]].set_visible(False)
fig.savefig("monthly.png", dpi=150, bbox_inches="tight")
plt.show()Output:
InvoiceDate
2010-12-01 778
2011-01-01 672
2011-02-01 509
2011-03-01 691
2011-04-01 516
2011-05-01 741
2011-06-01 739
2011-07-01 689
2011-08-01 725
2011-09-01 1030
2011-10-01 1107
2011-11-01 1458
Freq: MS
Revenue sits between £0.5 and £0.8 million a month until August, then climbs to £1.46 million in November, almost three times February. September to November bring in 37% of the year’s revenue: shops are stocking up on gifts for Christmas. This is the single most important fact for a forecaster or buyer at this company. A model that ignores the season will under-order in autumn and overstock in spring.
One year of data also has a limit: you can’t tell how much of the autumn rise is seasonal and how much is growth. Real forecasting projects use two or more years of history so the model can learn the seasonal pattern separately from the trend. Our time series analysis tutorial shows how.
4. The 80/20 rule and when people buy
def top_20_share(revenue):
revenue = revenue.sort_values(ascending=False)
return revenue.head(len(revenue) // 5).sum() / revenue.sum()
by_product = sales.groupby("StockCode")["Revenue"].sum()
by_customer = sales.groupby("CustomerID")["Revenue"].sum()
print(f"Top 20% of products: {top_20_share(by_product):.0%} of revenue")
print(f"Top 20% of customers: {top_20_share(by_customer):.0%} of revenue")
orders = sales.drop_duplicates("InvoiceNo")
print(orders["InvoiceDate"].dt.day_name().value_counts().to_string())Output:
Top 20% of products: 79% of revenue
Top 20% of customers: 75% of revenue
InvoiceDate
Thursday 4209
Wednesday 3667
Tuesday 3509
Friday 3109
Monday 3076
Sunday 2203Revenue is concentrated: the top 20% of products bring in 79% of revenue and the top 20% of customers 75%. For a buyer, that means stock-outs on a few hundred products matter far more than the long tail. For marketing, it means losing a handful of big customers can hurt more than losing hundreds of small ones.
The day counts show something that looks like a data error: there are no Saturday orders at all. It’s a real pattern in this dataset, consistent with a business that serves trade customers, and it’s exactly the kind of fact to check with the business before building anything on it. Thursday is the busiest day for orders, so maintenance and system changes belong on quieter days.
5. Segment customers with RFM
RFM scores each customer on three behaviours that predict future value: Recency (days since the last order), Frequency (number of orders) and Monetary value (total spend). Each is cut into five equal-sized groups and scored 1 to 5, then simple rules turn the scores into segments marketers can act on. Frequency is ranked first because many customers share the same order count, which would otherwise make the five groups unequal.
customers = sales.dropna(subset=["CustomerID"])
today = customers["InvoiceDate"].max() + pd.Timedelta(days=1)
rfm = customers.groupby("CustomerID").agg(
Recency=("InvoiceDate", lambda d: (today - d.max()).days),
Frequency=("InvoiceNo", "nunique"),
Monetary=("Revenue", "sum"),
)
# Score each from 1 (worst) to 5 (best) by quintile
rfm["R"] = pd.qcut(rfm["Recency"], 5, labels=[5, 4, 3, 2, 1]).astype(int)
rfm["F"] = pd.qcut(rfm["Frequency"].rank(method="first"), 5, labels=[1, 2, 3, 4, 5]).astype(int)
rfm["M"] = pd.qcut(rfm["Monetary"], 5, labels=[1, 2, 3, 4, 5]).astype(int)
def segment(row):
if row.R >= 4 and row.F >= 4: return "Champions"
if row.R >= 3 and row.F >= 3: return "Loyal"
if row.R >= 4: return "New or promising"
if row.R <= 2 and row.F >= 3: return "At risk"
if row.R <= 2: return "Lost"
return "Needs attention"
rfm["Segment"] = rfm.apply(segment, axis=1)
summary = rfm.groupby("Segment").agg(
Customers=("R", "size"),
Days_since_last=("Recency", "median"),
Orders=("Frequency", "median"),
Revenue=("Monetary", "sum"),
)
summary["Customer_%"] = (summary["Customers"] / summary["Customers"].sum() * 100).round(1)
summary["Revenue_%"] = (summary["Revenue"] / summary["Revenue"].sum() * 100).round(1)
summary = summary.sort_values("Revenue", ascending=False)
print(summary.drop(columns="Revenue").to_string())Output:
Customers Days_since_last Orders Customer_% Revenue_%
Segment
Champions 1136 11.0 7.0 26.2 66.7
Loyal 827 39.0 3.0 19.1 15.1
At risk 637 135.0 3.0 14.7 9.0
Lost 1068 220.5 1.0 24.6 5.8
Needs attention 347 53.0 1.0 8.0 1.8
New or promising 319 19.0 1.0 7.4 1.6import numpy as np
fig, ax = plt.subplots(figsize=(8, 4.5))
y = np.arange(len(summary))
ax.barh(y - 0.2, summary["Customer_%"], height=0.4, color="#9aa5b1", label="% of customers")
ax.barh(y + 0.2, summary["Revenue_%"], height=0.4, color="#c8242c", label="% of revenue")
ax.set_yticks(y, summary.index)
ax.invert_yaxis()
ax.set_xlabel("Percent")
ax.set_title("Champions are a quarter of customers and two-thirds of revenue")
ax.legend(frameon=False, loc="lower right")
ax.spines[["top", "right"]].set_visible(False)
fig.savefig("rfm.png", dpi=150, bbox_inches="tight")
plt.show()
The 1,136 Champions, a quarter of customers, account for two-thirds of revenue. They ordered a median of 7 times and last bought 11 days before the end of the data. Each segment calls for a different action:
- Champions: protect them. Early access to new ranges, account managers for the largest, and never a generic discount they didn’t need.
- Loyal: move them up with recommendations and volume offers.
- At risk (637 customers, 9% of revenue): they used to order regularly but haven’t bought for a median of 135 days. They are the best target for a win-back campaign, because they have shown they like the products.
- Lost: one order, more than six months ago. Cheap, automated reminders only.
- New or promising: recent first-time buyers. A good second-order experience decides whether they become loyal.
RFM is popular because anyone in the business can understand it, and it needs nothing but a transaction table. For segments found by the data instead of by rules, run k-means clustering on the scaled R, F and M values.
6. Market basket analysis: what sells together
Market basket analysis looks for products that appear in the same order more often than chance. Three numbers describe each pair: support (the share of orders containing both), confidence (of the orders with A, the share that also contain B) and lift (how many times more often they appear together than if they were bought independently). A lift of 1 means no relationship.
# One row per order, one column per product: True if the order contains it
n_orders = sales["InvoiceNo"].nunique()
share = sales.groupby("StockCode")["InvoiceNo"].nunique() / n_orders
common = share[share >= 0.02].index # products in 2%+ of orders
subset = sales[sales["StockCode"].isin(common)]
basket = pd.crosstab(subset["InvoiceNo"], subset["StockCode"]).gt(0).astype(int)
together = (basket.T @ basket) / n_orders # share of orders with both
support = basket.sum() / n_orders
names = sales.groupby("StockCode")["Description"].first()
rules = []
for i, a in enumerate(common):
for b in common[i + 1:]:
both = together.loc[a, b]
if both >= 0.01:
rules.append({
"Product A": names[a].capitalize(), "Product B": names[b].capitalize(),
"Both %": round(both * 100, 1),
"B given A %": round(both / support[a] * 100),
"Lift": round(both / (support[a] * support[b]), 1),
})
rules = pd.DataFrame(rules).sort_values("Lift", ascending=False)
print(len(common), "products,", len(rules), "pairs")
print(rules.head(8).to_string(index=False))Output:
298 products, 831 pairs
Product A Product B Both % B given A % Lift
Poppy's playhouse bedroom Poppy's playhouse kitchen 1.6 74 33.6
Set/6 red spotty paper cups Set/6 red spotty paper plates 1.8 82 30.7
Small dolly mix design orange bowl Small marshmallows pink bowl 1.8 67 30.4
Scandinavian paisley picnic bag Pink vintage paisley picnic bag 1.4 63 30.3
Wooden heart christmas scandinavian Wooden star christmas scandinavian 2.0 72 27.9
Feltcraft princess charlotte doll Feltcraft princess lola doll 1.3 57 27.2
Red stripe ceramic drawer knob Blue stripe ceramic drawer knob 1.3 57 26.6
Red stripe ceramic drawer knob White spot red ceramic drawer knob 1.2 53 25.8Keeping only products in at least 2% of orders makes the calculation fast (298 products instead of 3,900) and avoids rules based on a handful of orders. The matrix product basket.T @ basket counts, for every pair of products, how many orders contain both.
The strongest pairs are items from the same collection: 74% of orders with the Poppy’s Playhouse bedroom also include the kitchen, and the pair appears together 33.6 times more often than chance. Customers buy matching sets. That suggests concrete actions: “complete the set” recommendations on product pages, bundles, and keeping a whole range in stock together, because running out of one piece can lose the sale of the others. The same co-occurrence matrix is the starting point of item-based recommenders; see building a recommendation system with Python.
Two cautions. High lift on rare products can be noise, which is why the code requires a minimum support. And association isn’t causation: the pairs tell you what customers buy together, not that a recommendation will change what they buy. Test that with an A/B test.
7. Predict which customers will buy again
Churn prediction turns segmentation into a forecast. The trick is to pretend it’s an earlier date: build features from everything before 1 September 2011, then check who actually bought in the following 90 days. That gives a labelled dataset without leaking the future into the features.
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import roc_auc_score
cutoff = pd.Timestamp("2011-09-01")
before = customers[customers["InvoiceDate"] < cutoff]
after = customers[(customers["InvoiceDate"] >= cutoff)
& (customers["InvoiceDate"] < cutoff + pd.Timedelta(days=90))]
X = before.groupby("CustomerID").agg(
recency=("InvoiceDate", lambda d: (cutoff - d.max()).days),
tenure=("InvoiceDate", lambda d: (cutoff - d.min()).days),
orders=("InvoiceNo", "nunique"),
revenue=("Revenue", "sum"),
products=("StockCode", "nunique"),
)
X["avg_order"] = X["revenue"] / X["orders"]
y = X.index.isin(after["CustomerID"]).astype(int)
print(f"{len(X):,} customers, {y.mean():.0%} bought again in the next 90 days")
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42)
print(f"Recency alone: {roc_auc_score(y_test, -X_test['recency']):.3f}")
print(f"Number of orders: {roc_auc_score(y_test, X_test['orders']):.3f}")
logreg = make_pipeline(FunctionTransformer(np.log1p), StandardScaler(),
LogisticRegression(max_iter=1000)).fit(X_train, y_train)
print(f"Logistic regression: {roc_auc_score(y_test, logreg.predict_proba(X_test)[:, 1]):.3f}")
boost = HistGradientBoostingClassifier(random_state=42).fit(X_train, y_train)
print(f"Gradient boosting: {roc_auc_score(y_test, boost.predict_proba(X_test)[:, 1]):.3f}")Output:
3,314 customers, 56% bought again in the next 90 days
Recency alone: 0.687
Number of orders: 0.720
Logistic regression: 0.744
Gradient boosting: 0.715ROC AUC measures how well a score ranks buyers above non-buyers: 0.5 is random and 1.0 is perfect. Simple rules already work: the number of past orders alone scores 0.720. Logistic regression on six features, log-transformed because spend and order counts are very skewed, improves that to 0.744. Gradient boosting does worse here (0.715): with a few thousand customers and a handful of strong features, a simple model is enough. That’s common with customer data, so always compare against a simple baseline before reaching for a complex model. See logistic regression explained and XGBoost vs LightGBM vs CatBoost for more on both.
How useful is the ranking?
An AUC of 0.744 sounds modest, but what matters is whether the ranking is useful. Group the test customers into ten equal groups by predicted probability and compare with what actually happened:
proba = logreg.predict_proba(X_test)[:, 1]
decile = pd.qcut(proba, 10, labels=range(1, 11))
rate = pd.Series(y_test).groupby(decile, observed=True).mean() * 100
print(rate.round().astype(int).to_string())
fig, ax = plt.subplots(figsize=(8, 4))
ax.bar(rate.index.astype(str), rate, color=["#c8242c"] * 3 + ["#1f4e79"] * 7)
ax.set_title("24% of the lowest-ranked customers came back, 95% of the highest")
ax.set_xlabel("Predicted chance of buying again (1 = lowest 10% of customers)")
ax.set_ylabel("Actually bought again (%)")
ax.spines[["top", "right"]].set_visible(False)
fig.savefig("deciles.png", dpi=150, bbox_inches="tight")
plt.show()Output:
1 24
2 36
3 40
4 42
5 49
6 56
7 64
8 75
9 80
10 95
Only 24% of the lowest-ranked tenth came back, against 95% of the highest. A retention team with budget for a few hundred calls or vouchers should spend it on the red bars, where it can change something, rather than on customers who would have bought anyway.
Before using a model like this for real, split by time rather than randomly (train on one period, test on the next), and check more than one cutoff date: the share of customers who come back in the next 90 days is 56% from 1 September but 49% from 1 June in this data, so a model and its threshold need checking across the year.
More data science project ideas for retail
Once you have done the project above, these extend it or use other public retail datasets:
- Customer lifetime value: fit a BG/NBD and Gamma-Gamma model (the
lifetimesorpymc-marketingpackages) to the same Online Retail data to predict each customer’s spend over the next year. - Demand forecasting: the M5 competition dataset on Kaggle has daily unit sales of 3,049 Walmart products across 10 stores in three US states, with prices and events.
- Store sales forecasting: Kaggle’s Rossmann (European drugstores) and Corporación Favorita (Ecuadorian grocery) datasets add promotions, holidays and store details.
- Basket analysis at scale: the Instacart dataset has over 3 million grocery orders; try association rules and next-basket prediction.
- Price elasticity: estimate how quantity responds to price for the top products in the Online Retail data with a log-log regression, then check whether the results make business sense.
- Returns analysis: use the cancelled invoices dropped above to find which products and customers have the highest return rates.
A finished project is more convincing to an employer than a long list of started ones. Write up one of these the way this article does: the question, the cleaning decisions, the result and what the business should do. Our data science career guide covers how to present projects in a portfolio.
What does a retail data scientist do?
A retail data scientist spends less time on algorithms than the job title suggests. A typical week mixes SQL queries against sales and stock tables, cleaning data like the steps above, building or updating forecasting and customer models, designing and reading A/B tests, and explaining results to buyers, merchandisers and marketers. The skills that matter most:
- SQL and pandas for pulling and reshaping transaction data. See SQL for data analysis and data manipulation with pandas.
- Statistics and experiments: confidence intervals, A/B tests and knowing when a difference is noise.
- Forecasting and machine learning: time-series methods, gradient boosting and classification models, plus honest validation.
- Retail knowledge: margins, markdowns, lead times, seasonality and how stores and warehouses actually work.
- Communication: a chart and a recommendation a buyer can act on are worth more than a better AUC.
Common challenges
- Messy data: returns, missing customer IDs, fees mixed with products and price errors, all of which appeared in this small dataset.
- Short or changing history: new products have no sales history, and ranges change every season.
- Stock-outs hide demand: if a product sold zero units because it was out of stock, raw sales data understates demand.
- Privacy: laws like GDPR govern how you handle customer-level data. See the dark side of big data.
- Getting results used: a forecast only helps if it changes an order; build tools around existing decisions.
Related tutorials
- Exploratory data analysis in Python
- Clean and preprocess data with Python
- Data visualization with Matplotlib
- Random forests explained
- Data science by industry
Its UCI Machine Learning Repository page describes the dataset in full.
FAQ
What is data science in retail?
Using data from sales, customers, stock and prices to make better retail decisions: forecasting demand, managing inventory, personalizing marketing, setting prices and preventing fraud. It combines statistics, machine learning and knowledge of how retail works.
What are the main applications of data science in the retail industry?
Demand forecasting, inventory and supply chain planning, customer segmentation and lifetime value, churn prediction, recommendations and basket analysis, pricing and markdowns, promotion measurement, and fraud and returns detection.
What data do retailers use for data science?
Mainly transaction data (what was sold, when, where, at what price and to whom), plus stock levels, product attributes, loyalty and web data, promotions and external data such as holidays and weather.
What is RFM analysis?
A way to segment customers by Recency (how recently they bought), Frequency (how often) and Monetary value (how much). Each is scored, usually 1 to 5, and the combinations define segments such as Champions, At risk and Lost.
What is market basket analysis?
Finding products that are bought together more often than chance, measured with support, confidence and lift. Retailers use it for recommendations, bundles, store layout and keeping related products in stock together.
Can small retailers use data science?
Yes. The project in this article needs only a transaction export and free Python tools. Seasonality, RFM segments and basket pairs are useful even for a shop with a few thousand orders a year.
