Cohort retention analysis in Python answers the question that a monthly revenue chart hides: are customers coming back, and is that getting better or worse? Total revenue can grow while retention falls, as long as you keep buying new customers. A cohort table groups customers by the month of their first order and shows what share of each group ordered again one, two, three and more months later. This guide builds that table from a plain orders CSV with pandas, adds cumulative revenue per customer, masks the months that have not happened yet so young cohorts do not look like failures, draws a heatmap with matplotlib and explains how to read it. The code works on an export from WooCommerce, Shopify or any system that can give you an order ID, a customer identifier, a date, a status and a total.

From my own work: When store owners ask me why growth feels harder each year, a cohort table is the first thing I build. It takes about fifteen minutes with the script below, and it usually changes the conversation from more ads to why second orders are rare, which is a cheaper problem to work on.
What a cohort retention table shows
A cohort is a group of customers who share a starting point, here the calendar month of their first paid order. Month 0 is that first month, so it is always 100 percent. Month 1 is the following calendar month, and so on. Reading across a row shows how one cohort behaves over time; reading down a column compares cohorts at the same age, which is how you spot whether a change to onboarding, pricing or email flows made later customers more loyal.
Several retention definitions are in common use, and mixing them up is the most frequent mistake in cohort reports:
| Definition | Cell value | Best for |
|---|---|---|
| N-month (classic) retention | Share of the cohort with at least one order in month N | Stores and apps with regular repeat purchases |
| Rolling (unbounded) retention | Share of the cohort with any order in month N or later | Infrequent purchases, such as furniture or annual plans |
| Revenue retention | Revenue in month N divided by month 0 revenue | Subscriptions with upgrades and downgrades |
| Cumulative revenue per customer | Total revenue to date divided by cohort size | Comparing customer value with acquisition cost |
The script below produces the first and the last, which together answer most ecommerce questions.
Export orders to a CSV
You need one row per order with five columns: order_id, customer_id, order_date, status and total. On WooCommerce with High-Performance Order Storage enabled, a read-only query against the orders table gives exactly that. Guest orders have a customer_id of 0, so fall back to the billing email:
-- WooCommerce with HPOS enabled (table prefix may differ from wp_)
SELECT
o.id AS order_id,
COALESCE(NULLIF(o.customer_id, 0), LOWER(o.billing_email)) AS customer_id,
o.date_created_gmt AS order_date,
REPLACE(o.status, 'wc-', '') AS status,
o.total_amount AS total
FROM wp_wc_orders o
WHERE o.type = 'shop_order'
ORDER BY o.date_created_gmt;
# run it on the server and save as CSV (MySQL or MariaDB client)
mysql --batch -e "SOURCE orders.sql" wordpress_db
| tr 't' ',' > orders.csv
The tab-to-comma conversion is safe here because none of these columns can contain commas. If you export other fields, use a CSV export plugin or the client’s proper CSV output instead. Treat the file as personal data: it contains customer emails, so keep it off shared drives and delete it when the analysis is done.
Cohort retention analysis in Python: build the table with pandas
The script loads and cleans the CSV, assigns each customer to the month of their first paid order, computes how many months after that each order happened, then counts distinct customers per cohort and month. read_csv with explicit dtypes keeps IDs as strings so leading zeros and long numbers survive (pandas: read_csv); groupby with transform attaches each customer’s first order date to every one of their rows (pandas: group by). It needs Python 3.9 or later and pandas 2.2 or later:
"""Monthly cohort retention from an orders CSV.
Usage: python cohort_retention.py orders.csv
"""
import sys
import pandas as pd
PAID_STATUSES = {"completed", "processing"}
def load_orders(path: str) -> pd.DataFrame:
df = pd.read_csv(
path,
usecols=["order_id", "customer_id", "order_date", "status", "total"],
dtype={"order_id": "string", "customer_id": "string", "status": "string"},
)
df["order_date"] = pd.to_datetime(df["order_date"], utc=True, errors="coerce")
df["total"] = pd.to_numeric(df["total"], errors="coerce").fillna(0)
df["customer_id"] = df["customer_id"].str.strip().str.lower()
df["status"] = df["status"].str.strip().str.lower()
df = df[df["status"].isin(PAID_STATUSES)]
df = df.dropna(subset=["customer_id", "order_date"])
df = df.drop_duplicates(subset="order_id")
return df
def month_number(dates: pd.Series) -> pd.Series:
return dates.dt.year * 12 + dates.dt.month
def add_cohort_columns(df: pd.DataFrame) -> pd.DataFrame:
df = df.copy()
first_order = df.groupby("customer_id")["order_date"].transform("min")
df["cohort"] = first_order.dt.tz_localize(None).dt.to_period("M")
df["period"] = month_number(df["order_date"]) - month_number(first_order)
return df
def mask_future(table: pd.DataFrame, last_month: pd.Period) -> pd.DataFrame:
# A March cohort cannot have a month-9 value yet: show it as blank, not 0%.
out = table.astype("float64")
for cohort in out.index:
max_period = (last_month.year - cohort.year) * 12 + (last_month.month - cohort.month)
out.loc[cohort, out.columns > max_period] = float("nan")
return out
def cohort_tables(df: pd.DataFrame):
active = (
df.groupby(["cohort", "period"])["customer_id"]
.nunique()
.unstack(fill_value=0)
.sort_index()
)
cohort_size = active[0]
retention = active.div(cohort_size, axis=0)
revenue = df.pivot_table(
index="cohort", columns="period", values="total", aggfunc="sum", fill_value=0
)
revenue_per_customer = revenue.cumsum(axis=1).div(cohort_size, axis=0)
last_month = df["order_date"].max().tz_localize(None).to_period("M")
return (
cohort_size,
mask_future(retention, last_month),
mask_future(revenue_per_customer, last_month),
)
if __name__ == "__main__":
orders = add_cohort_columns(load_orders(sys.argv[1]))
size, retention, ltv = cohort_tables(orders)
pd.set_option("display.width", 200)
print("Cohort sizes:n", size.to_string(), "n")
print("Retention (% of cohort ordering in month N):")
print((retention * 100).round(1).iloc[:, :7].to_string(na_rep=""), "n")
print("Cumulative revenue per customer:")
print(ltv.round(2).iloc[:, :7].to_string(na_rep=""))
retention.to_csv("cohort_retention.csv", float_format="%.4f")
ltv.to_csv("cohort_revenue_per_customer.csv", float_format="%.2f")
A few decisions in that code matter more than they look:
- Only paid statuses count. Refunded, cancelled and failed orders are dropped before the first order is found, so a customer whose first attempt failed joins the cohort of their first real purchase.
- Month offsets use calendar months.
year * 12 + monthgives an integer month number, so an order on 31 January and one on 1 February are one month apart. That matches how cohort charts are usually read. If you need 30-day windows instead, divide the day difference by 30. - Distinct customers, not orders.
nunique()counts a customer once per month even if they ordered three times, so retention cannot exceed 100 percent. - Future cells are blank. A cohort from last month has no month-6 data yet. Filling those cells with 0 would make recent cohorts look terrible;
mask_futuresets them to NaN instead.
The revenue table uses pivot_table with a sum, then a cumulative sum across columns, then divides by the cohort size, giving revenue per acquired customer to date (pandas: pivot_table). Monthly periods come from dt.to_period('M') (pandas: to_period); timezone information is dropped first because periods have no timezone.
Example output
Run against a synthetic test file of about 2,400 orders from 1,500 customers, generated for this article, the script prints:
$ python cohort_retention.py orders.csv
Retention (% of cohort ordering in month N):
period 0 1 2 3 4 5 6
cohort
2026-01 100.0 9.5 11.9 7.1 2.4 4.8 0.8
2026-02 100.0 21.7 16.7 12.5 5.8 5.0 5.8
2026-03 100.0 15.6 14.1 21.9 5.5 3.1 2.3
2026-04 100.0 11.3 12.9 12.9 6.5 7.3 4.0
2026-05 100.0 13.2 14.7 15.4 5.1 1.5 2.2
2026-06 100.0 17.1 22.9 12.1 8.6 6.4
2026-07 100.0 14.5 21.0 12.1 6.5
2026-08 100.0 9.0 22.9 8.3
2026-09 100.0 14.6 11.5
2026-10 100.0 8.7
2026-11 100.0
Cumulative revenue per customer:
period 0 1 2 3 4 5 6
cohort
2026-01 67.26 73.10 81.07 84.71 86.04 87.91 88.08
2026-02 61.70 73.32 85.32 94.63 98.11 100.36 103.95
...
The numbers are illustrative only; your own data will look different. The triangle shape is normal: older cohorts have more columns because they have had more time.
Draw a cohort retention heatmap
A heatmap makes patterns visible at a glance. imshow draws the matrix and leaves NaN cells empty (Matplotlib: imshow). Month 0 is skipped because it is always 100 percent and would flatten the color scale:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
retention = pd.read_csv("cohort_retention.csv", index_col="cohort")
retention.columns = retention.columns.astype(int)
data = retention.iloc[:, 1:13] # skip month 0 (always 100%)
fig, ax = plt.subplots(figsize=(12, 7))
im = ax.imshow(data.to_numpy(), cmap="Blues", aspect="auto", vmin=0, vmax=np.nanmax(data.to_numpy()))
ax.set_xticks(range(data.shape[1]), labels=data.columns)
ax.set_yticks(range(data.shape[0]), labels=data.index)
ax.set_xlabel("Months since first order")
ax.set_ylabel("Cohort (first order month)")
ax.set_title("Monthly customer retention by cohort")
for i in range(data.shape[0]):
for j in range(data.shape[1]):
value = data.iat[i, j]
if not np.isnan(value):
ax.text(j, i, f"{value:.0%}", ha="center", va="center", fontsize=8)
fig.colorbar(im, ax=ax, format=lambda x, _: f"{x:.0%}")
fig.tight_layout()
fig.savefig("cohort_retention_heatmap.png", dpi=150)
Install the dependencies in a virtual environment with python -m venv .venv && .venv/bin/pip install pandas matplotlib. For a dashboard, write the retention CSV to a location your BI tool reads and refresh it with a scheduled job.
How to read cohort retention results
- Compare columns, not rows. If month-1 retention rises from cohort to cohort, something you changed is working. A single row tells you little on its own.
- Watch cohort size. A cohort of 10 customers can swing from 0 to 30 percent with three people. Show the size next to the table and do not draw conclusions from small cohorts. The current, partial month is always small.
- Expect seasonality. Customers acquired in a holiday sale often retain worse than those who found you organically. Segment by acquisition channel or first product before blaming the store.
- Look for the flattening point. Retention usually drops sharply after month 0 and then levels off. The level where it flattens is your loyal core; raising it has the largest long-term effect.
- Pair retention with value. Cumulative revenue per customer by month 6 or 12, compared with what you paid to acquire that customer, tells you which cohorts were worth acquiring.
For segmentation, add a column such as first_channel or first_product_category and run the same functions on each group. The SQL equivalent, and how to turn cohorts into churn predictions for a subscription business, is covered in churn prediction with SQL cohort analysis. If retention is low because the first experience disappoints, the fixes in the conversion rate optimization guide and WooCommerce performance optimization are good starting points. Once event volumes outgrow a CSV, the same cohort logic runs well in a columnar database, as described in ClickHouse for SaaS analytics.
Common cohort analysis mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Counting orders instead of customers | Retention above 100 percent, inflated by heavy buyers | nunique() on the customer column |
| Including refunds and cancellations | Customers counted as retained who never paid | Filter statuses before finding the first order |
| Zero instead of blank for future months | Recent cohorts look like failures | Mask cells past the last data month |
| Guest checkouts under one ID | One huge fake customer, or every guest is new | Use a normalised email for guests |
| Mixed timezones | Orders near midnight land in the wrong month | Parse as UTC, convert once to the store timezone if needed |
Cohort retention analysis checklist
- Orders export with ID, customer, date, status and total; guests keyed by normalised email.
- Paid statuses only, duplicates removed, dates parsed as UTC.
- Cohort from the first paid order; calendar-month offsets.
- Distinct customers per cell; cohort sizes shown beside the table.
- Future cells masked; month 0 left out of the color scale.
- Cumulative revenue per customer alongside retention.
- Segments by channel or first product before drawing conclusions.
Want this done on your own server or site?
I am Saizul Amin, a web developer and technical SEO consultant. I set up and harden VPS servers, migrate WordPress sites, fix indexing problems and build automations. See my portfolio or get in touch.
FAQ
What is cohort retention analysis?
It groups customers by when they started, usually the month of their first purchase, and measures what share of each group is still active in later periods. It shows whether retention is improving for newer customers, which totals and averages hide.
How do I calculate retention rate for a cohort?
Count the distinct customers from the cohort who ordered in month N and divide by the number of customers in the cohort at month 0. Leave months that have not happened yet blank instead of zero.
Which Python libraries do I need for cohort analysis?
pandas is enough to build the tables. matplotlib or seaborn draw the heatmap. Everything in this guide uses pandas and matplotlib only.
Should I use calendar months or 30-day periods?
Calendar months are easier to read and match how businesses report. 30-day periods are more precise for products with short cycles. Pick one, document it and use it consistently.
How many customers does a cohort need to be meaningful?
There is no fixed number, but percentages from cohorts of a few dozen customers swing widely. Show cohort sizes, combine small months into quarters, and focus on trends across several cohorts.
Sources
- pandas documentation: read_csv
- pandas user guide: Group by (split-apply-combine)
- pandas documentation: DataFrame.pivot_table
- pandas documentation: Series.dt.to_period
- Matplotlib documentation: pyplot.imshow

Saizul Amin is an AI agent developer, AI automation engineer and full-stack software developer from Dhaka, Bangladesh. He builds any kind of AI agent, AI automation and custom software for any business. Portfolio: https://saizul.com

