ds@mcpanalytics.aiEmail your data and your question and get an answer about your own data, with the method shown.Email your data and question. Get an answer.

Shopify Cohort Analysis: Customer Retention Guide

By MCP Analytics Team | Published , updated

Category: Shopify Analytics | MCP Analytics | Last updated: 2026-11-02

What You'll Learn

Customer retention cohort analysis is a useful way to understand how well your Shopify store keeps customers coming back over time. Unlike simple retention rates that lump all customers together, cohort analysis groups customers by their first purchase date and tracks their behavior over subsequent periods. This reveals patterns that aggregate metrics miss, like whether customers acquired during your holiday sale retain better than those from other campaigns, or if retention has improved as you've refined your product and service.

To see how many of your own customers come back, cohort by cohort, try the free cohort retention tool.

Steps: 1 Export orders from Shopify | 2 Structure the data | 3 Build the retention matrix | 4 Calculate retention metrics | 5 Interpret the results | 6 Act on them

In this tutorial, you'll learn how to perform customer retention cohort analysis for your Shopify store, from data preparation through interpretation and action. By the end, you'll be able to answer questions like "What percentage of customers from January ordered again in June?" This is a Python tutorial (pandas), with a CSV upload route described near the end if you would rather not write code.

This analysis is useful for e-commerce operations because it feeds into customer lifetime value (CLV), marketing return calculations, and inventory planning. Retention patterns can inform where you spend marketing money, which customer groups may be drifting away, and what you assume in revenue forecasts.

Prerequisites and Data Requirements

What You Need Before Starting

Before diving into cohort analysis, ensure you have the following:

Required Data Fields

Your cohort analysis will require these essential data points from Shopify:

Technical Requirements

You'll need basic familiarity with:

Step-by-Step Implementation

Step 1: Export Customer and Order Data from Shopify

The first step is extracting your customer purchase data from Shopify. You have several options depending on your store size and technical capabilities:

Try It First: Make the Synthetic Practice File

If you want to follow along without a store, run this script first. It makes synthetic orders (random, seeded with 42, not from any real store) and writes your-orders-export.csv in the layout of a Shopify Admin export, including the blank extra line-item rows and some guest orders with no email. Every output shown on this page comes from running the Option A, Step 2, Step 3, Step 4 and win-back code blocks in order on this file; the Option B API script was not run. Using your own export instead? Skip this block.

import numpy as np
import pandas as pd

# SYNTHETIC data for this tutorial only. Not a real store.
rng = np.random.default_rng(42)
last_day = pd.Timestamp('2024-10-10')
rows = []
order_id = 1000
n_customers = 1700

# Each customer's first order falls on a random day from 1 Jan to 10 Oct 2024
first_days = pd.Timestamp('2024-01-01') + pd.to_timedelta(
    rng.integers(0, (last_day - pd.Timestamp('2024-01-01')).days + 1, n_customers), unit='D')

for i, first in enumerate(first_days):
    email = f'Customer{i:04d}@Example.com'
    stamps = [first + pd.Timedelta(seconds=int(rng.integers(0, 86400)))]
    # Chance of ordering in month k after the first month: starts near 19%, settles near 8%
    for k in range(1, 10):
        month_start = (first.to_period('M') + k).to_timestamp()
        if month_start > last_day:
            break
        if rng.random() < 0.08 + 0.11 * 0.55 ** (k - 1):
            day = month_start + pd.Timedelta(days=int(rng.integers(0, 28)),
                                             seconds=int(rng.integers(0, 86400)))
            if day <= last_day:
                stamps.append(day)
    for stamp in stamps:
        order_id += 1
        total = round(float(rng.lognormal(4.0, 0.5)), 2)
        rows.append({'Id': order_id, 'Name': f'#{order_id}', 'Email': email,
                     'Total': total, 'Created at': stamp.strftime('%Y-%m-%d %H:%M:%S +0000')})
        if rng.random() < 0.3:  # extra line item: Shopify repeats the order on its own row, mostly blank
            rows.append({'Id': None, 'Name': f'#{order_id}', 'Email': None,
                         'Total': None, 'Created at': None})

# Guest checkouts with no email: Option A below counts and excludes these
for _ in range(40):
    order_id += 1
    stamp = pd.Timestamp('2024-01-01') + pd.to_timedelta(
        int(rng.integers(0, 283 * 86400)), unit='s')
    rows.append({'Id': order_id, 'Name': f'#{order_id}', 'Email': None,
                 'Total': round(float(rng.lognormal(4.0, 0.5)), 2),
                 'Created at': stamp.strftime('%Y-%m-%d %H:%M:%S +0000')})

pd.DataFrame(rows).to_csv('your-orders-export.csv', index=False)
print(f'Wrote {len(rows)} rows')

Expected Output:

Wrote 3373 rows

Option A: Using a Shopify Admin Export (For Smaller Stores)

Export your orders from the Shopify admin as a CSV, with a date range that covers your full history. Per Shopify's help centre, an order with several items shows the extra line items on separate rows with many order-level fields blank, and the export identifies the customer by email (there is no customer ID column). The script below keeps one row per order and uses the lower-cased email as the customer key. Its column names (Id, Name, Email, Total, Created at) are the headers Shopify documents; if your file differs, adjust them. The script also counts orders that have no email (guest checkouts can lack one) and leaves them out, since they cannot be tied to a customer; the practice file includes some so you can see the count. If your export also lists cancelled or test orders, remove them before you continue.

import pandas as pd

# The Admin export puts each extra line item of an order on its own row, with the order-level
# fields (including Created at) blank, so keep one row per order
raw = pd.read_csv('your-orders-export.csv')
export = raw.dropna(subset=['Created at']).drop_duplicates(subset=['Name'])

# Shopify's order export has no customer ID column, so the email identifies the customer.
# Orders with no email cannot be tied to a customer: count them, do not drop them silently
no_email = export['Email'].fillna('').str.strip() == ''
print(f"Excluded {no_email.sum()} of {len(export)} orders with no email")
export = export[~no_email]

orders = pd.DataFrame({
    'id': export['Id'],
    'email': export['Email'].str.lower().str.strip(),
    'created_at': pd.to_datetime(export['Created at'], utc=True),
    'total_price': export['Total'],
})
orders['customer_id'] = orders['email']

orders.to_csv('shopify_orders_export.csv', index=False)
print(f"Prepared {len(orders)} orders from {orders['customer_id'].nunique()} customers")
print(f"Earliest order: {orders['created_at'].min():%Y-%m-%d}   Latest order: {orders['created_at'].max():%Y-%m-%d}")

Expected Output:

Excluded 40 of 2618 orders with no email
Prepared 2578 orders from 1700 customers
Earliest order: 2024-01-01   Latest order: 2024-10-10

Option A, Step 2, Step 3 and Step 4 outputs below come from running the code on the synthetic file above (January to 10 October 2024), not from a real store, so your numbers will differ.

Option B: Using the Shopify API (For Larger Stores)

For stores with extensive order histories, the Shopify API provides more flexibility. Three things to get right:

import requests
import pandas as pd

# Shopify API credentials
SHOP_NAME = 'your-store-name'
API_VERSION = 'YYYY-MM'  # a version Shopify currently supports
ACCESS_TOKEN = 'your-access-token'  # needs read access to orders

# API endpoint for orders
url = f'https://{SHOP_NAME}.myshopify.com/admin/api/{API_VERSION}/orders.json'

headers = {'X-Shopify-Access-Token': ACCESS_TOKEN}

# Parameters for the first request only
params = {
    'status': 'any',
    'limit': 250,
    'fields': 'id,email,customer,created_at,cancelled_at,test,total_price',
}

# Fetch orders with pagination
all_orders = []
while url:
    response = requests.get(url, headers=headers, params=params)
    response.raise_for_status()
    all_orders.extend(response.json().get('orders', []))

    # The Link header can hold both a previous and a next page; ask for the next one by name
    url = response.links.get('next', {}).get('url')
    params = None  # the next-page URL already carries the cursor, limit and fields

# Convert to DataFrame, then keep real orders only
orders = pd.json_normalize(all_orders)
orders = orders[orders['cancelled_at'].isna() & ~orders['test']].copy()

# One customer key: the Shopify customer ID, or the email for guest checkouts
orders['email'] = orders['email'].str.lower().str.strip().replace('', pd.NA)  # blank email counts as missing
orders['customer_id'] = orders['customer.id'].astype('Int64').astype('string').fillna(orders['email'])
orders['created_at'] = pd.to_datetime(orders['created_at'], utc=True)

# Orders with neither a customer ID nor an email cannot be tied to a customer
no_key = orders['customer_id'].isna()
print(f"Excluded {no_key.sum()} of {len(orders)} orders with no customer key")
orders = orders[~no_key]

orders[['id', 'email', 'customer_id', 'created_at', 'total_price']].to_csv('shopify_orders_export.csv', index=False)
print(f"Fetched {len(all_orders)} orders, kept {len(orders)} after dropping cancelled and test orders")
print(f"Earliest order: {orders['created_at'].min():%Y-%m-%d}   Latest order: {orders['created_at'].max():%Y-%m-%d}")

The script prints how many orders it fetched and kept, and the earliest and latest order dates. It needs a real store and token, so we did not run it for this page and show no sample output. The API field names follow Shopify's order resource; check them against the version you use.

Step 2: Structure Data for Cohort Analysis

Once you have your raw Shopify data, you need to transform it into the format required for cohort analysis. The key is identifying each customer's first purchase date (their cohort) and tracking their activity in subsequent periods.

Required Data Structure

Your final dataset should have these columns:

customer_id,cohort_month,order_month,order_count,revenue
12345,2024-01,2024-01,1,89.99
12345,2024-01,2024-03,1,124.50
12346,2024-01,2024-01,1,45.00
12347,2024-02,2024-02,1,199.99
12347,2024-02,2024-04,1,89.99

Data Transformation Script

Here's how to prepare your data from the shopify_orders_export.csv file that either option above writes:

import pandas as pd

# Set this to your store's time zone (an IANA name such as 'America/New_York').
# Months are cut in store time, not UTC. The practice file is in UTC.
STORE_TZ = 'UTC'

# Load the orders prepared in Step 1
df = pd.read_csv('shopify_orders_export.csv')

# Convert to store time first, then drop the zone and take the month
df['created_at'] = pd.to_datetime(df['created_at'], utc=True)
local = df['created_at'].dt.tz_convert(STORE_TZ).dt.tz_localize(None)
df['order_month'] = local.dt.to_period('M')

# Find first purchase for each customer (cohort assignment), in store time
first = local.groupby(df['customer_id']).min()
cohort_data = first.dt.to_period('M').rename('cohort_month').reset_index()

# Merge cohort back to orders
df = df.merge(cohort_data, on='customer_id')

# Aggregate by customer, cohort, and order month
cohort_analysis = df.groupby(['customer_id', 'cohort_month', 'order_month']).agg({
    'id': 'count',
    'total_price': 'sum'
}).reset_index()

cohort_analysis.columns = ['customer_id', 'cohort_month', 'order_month', 'order_count', 'revenue']

# Convert periods to strings for CSV export
cohort_analysis['cohort_month'] = cohort_analysis['cohort_month'].astype(str)
cohort_analysis['order_month'] = cohort_analysis['order_month'].astype(str)

# Save prepared data
cohort_analysis.to_csv('cohort_analysis_ready.csv', index=False)
print(f"Prepared {len(cohort_analysis)} cohort records from {df['customer_id'].nunique()} unique customers")

Expected Output:

Prepared 2578 cohort records from 1700 unique customers

The month is cut in store time: set STORE_TZ to your store's time zone, because an order placed late on the last day of a month in your time can fall in the next month in UTC. The practice file is in UTC, so the setting changes nothing here. This output is from the Option A file. With Option B you also drop cancelled and test orders and use the Shopify customer ID where there is one, so your counts will differ. The step writes cohort_analysis_ready.csv.

Step 3: Run Cohort Analysis

Now that your data is properly structured, you can calculate the cohort retention matrix.

Calculating the Retention Matrix

A customer counts as retained in a month if they placed at least one order in that month. The code keeps two kinds of empty cell apart: a month that has finished with no repeat orders is 0, and a month that has not happened yet for that cohort is NaN. If both became NaN, the average would skip the worst months and overstate retention. Set last_complete_month to the last month your export covers in full.

import pandas as pd
import numpy as np

# Load prepared data
df = pd.read_csv('cohort_analysis_ready.csv')
df['cohort_month'] = pd.to_datetime(df['cohort_month']).dt.to_period('M')
df['order_month'] = pd.to_datetime(df['order_month']).dt.to_period('M')

# The last month your export covers in full (a month still in progress would look like lost customers)
last_complete_month = pd.Period('2024-09', 'M')
df = df[df['order_month'] <= last_complete_month]

# Calculate cohort period (months since first purchase)
df['cohort_period'] = (df['order_month'] - df['cohort_month']).apply(lambda x: x.n)

# Customers who ordered in each cohort-period
cohort_counts = df.groupby(['cohort_month', 'cohort_period'])['customer_id'].nunique()
cohort_pivot = cohort_counts.unstack('cohort_period')

# A month that has finished with no repeat orders is 0, not missing...
max_age = (last_complete_month - cohort_pivot.index.min()).n
cohort_pivot = cohort_pivot.reindex(columns=range(max_age + 1)).fillna(0)

# ...and only months that have not happened yet for that cohort are blanked out
for cohort in cohort_pivot.index:
    cohort_pivot.loc[cohort, cohort_pivot.columns > (last_complete_month - cohort).n] = np.nan

# Calculate retention percentages (every customer ordered in month 0, so column 0 is the cohort size)
cohort_size = cohort_pivot[0]
retention_matrix = cohort_pivot.divide(cohort_size, axis=0) * 100

print("Retention Cohort Matrix (%), first 7 months:")
print(retention_matrix.iloc[:, :7].round(1))
print("\nCustomers per cohort:")
print(cohort_size.astype(int).to_string())

# Save results
retention_matrix.to_csv('retention_cohort_matrix.csv')

Expected Output:

Retention Cohort Matrix (%), first 7 months:
cohort_period      0     1     2     3     4    5     6
cohort_month                                           
2024-01        100.0  20.7  16.8   8.7   9.2  7.1   4.9
2024-02        100.0  21.5  18.2  14.9   8.3  6.6  11.0
2024-03        100.0  21.6  14.1  11.4   9.7  7.0   7.0
2024-04        100.0  18.8  16.1  13.4  10.1  4.0   NaN
2024-05        100.0  13.5  13.5  12.0   6.2  NaN   NaN
2024-06        100.0  17.9  14.0  10.1   NaN  NaN   NaN
2024-07        100.0  20.3  17.0   NaN   NaN  NaN   NaN
2024-08        100.0  19.5   NaN   NaN   NaN  NaN   NaN
2024-09        100.0   NaN   NaN   NaN   NaN  NaN   NaN

Customers per cohort:
cohort_month
2024-01    184
2024-02    181
2024-03    185
2024-04    149
2024-05    208
2024-06    179
2024-07    182
2024-08    205
2024-09    169
Freq: M

Month 0 is the month of the first order. The January 2024 cohort has 184 customers, and 20.7% of them ordered again in February (month 1). NaN marks months that have not finished yet.

Step 4: Calculate Key Retention Metrics

Beyond the basic retention matrix, several derived metrics provide deeper insights. The score below is the mean of month 1 and month 3 retention, so only cohorts that have reached month 3 get one; the others are NaN. Differences of a few points between cohorts of 149 to 208 customers are within the noise described in the prerequisites.

# Calculate average retention by period across all cohorts
avg_retention_by_period = retention_matrix.mean()

# Calculate cohort-specific metrics
cohort_metrics = pd.DataFrame({
    'cohort_size': cohort_size,
    'month_1_retention': retention_matrix[1],
    'month_3_retention': retention_matrix[3],
    'month_6_retention': retention_matrix[6] if 6 in retention_matrix.columns else np.nan
})

# Identify best and worst performing cohorts (only cohorts old enough to have both months)
cohort_metrics['retention_score'] = cohort_metrics[['month_1_retention', 'month_3_retention']].mean(axis=1, skipna=False)
best_cohort = cohort_metrics['retention_score'].idxmax()
worst_cohort = cohort_metrics['retention_score'].idxmin()

print(f"\nBest Performing Cohort: {best_cohort} (Score: {cohort_metrics.loc[best_cohort, 'retention_score']:.1f}%)")
print(f"Worst Performing Cohort: {worst_cohort} (Score: {cohort_metrics.loc[worst_cohort, 'retention_score']:.1f}%)")
print(cohort_metrics['retention_score'].round(1).to_string())

Expected Output:

Best Performing Cohort: 2024-02 (Score: 18.2%)
Worst Performing Cohort: 2024-05 (Score: 12.7%)
cohort_month
2024-01    14.7
2024-02    18.2
2024-03    16.5
2024-04    16.1
2024-05    12.7
2024-06    14.0
2024-07     NaN
2024-08     NaN
2024-09     NaN
Freq: M

Interpreting Your Retention Results

Understanding the Retention Matrix

Your cohort retention matrix reveals critical patterns about customer behavior. Here's how to read and interpret the data:

Key Patterns to Look For

Compare Against Your Own History

Repeat-purchase rates vary a lot with product type, price and how often people need to reorder, and we do not publish industry benchmark ranges here. The comparison that means something is your own history: the same product mix, cohort by cohort, at the same age.

For more sophisticated statistical analysis of whether retention differences are significant, consider applying confidence intervals to your cohort comparisons.

Common Red Flags

Watch for these warning signs in your retention data:

Segmenting Cohorts for Deeper Insights

Don't stop at simple date-based cohorts. Create segments by:

Each of these segments is the same calculation as above on a subset of customers; keep the cohort-size caution in mind, because segments are smaller than cohorts.

Taking Action on Your Insights

Improving Low-Retention Cohorts

Once you've identified retention issues, these are interventions to test:

1. Post-Purchase Engagement Campaigns

For cohorts showing steep month 1 drop-off, test a post-purchase email sequence such as:

2. Win-Back Campaigns for Lapsed Customers

Target customers from high-retention cohorts who haven't purchased in their expected cycle:

# Identify at-risk customers from good cohorts
good_cohorts = cohort_metrics['retention_score'].nlargest(3).index

# Find customers from these cohorts who haven't purchased recently
recent_orders = df[df['order_month'] >= df['order_month'].max() - 2]
at_risk = df[
    (df['cohort_month'].isin(good_cohorts)) &
    (~df['customer_id'].isin(recent_orders['customer_id']))
]['customer_id'].unique()

print(f"Identified {len(at_risk)} at-risk customers from high-performing cohorts for win-back campaign")

Expected Output:

Identified 394 at-risk customers from high-performing cohorts for win-back campaign

3. Adjust Customer Acquisition Strategy

If certain acquisition channels produce low-retention customers, reallocate budget:

Predictive Applications

Use your cohort retention patterns for forecasting and planning:

Advanced practitioners can combine cohort analysis with survival analysis techniques to model time-to-churn probabilities.

Run It on Your Own Shopify Export

Export your orders from Shopify as a CSV and upload it at MCP Analytics, then ask the question in plain language; the report names the method. Nothing connects to your Shopify account.

Try it on your data

Next Steps and Advanced Techniques

Review Regularly

Cohort analysis isn't a one-time exercise. Establish a regular cadence:

Related Analyses to Explore

Complement your cohort analysis with these related techniques:

Building a Data-Driven Retention Culture

Share cohort insights across your organization:

For organizations looking to implement AI-powered analytics workflows, cohort analysis serves as an excellent foundation for more sophisticated predictive models.

Troubleshooting Common Issues

Issue 1: Insufficient Data for Meaningful Cohorts

Symptoms: Very small cohort sizes, large swings in retention rates from one cohort to the next, or cohorts with zero activity in later periods.

Solutions:

Issue 2: Inconsistent Customer IDs

Symptoms: Customers appearing in multiple cohorts, artificially low retention rates, duplicate customer records.

Solutions:

# Use the lower-cased email as the one customer key, then rebuild the cohort files
orders = pd.read_csv('shopify_orders_export.csv')
orders['customer_id'] = orders['email'].str.lower().str.strip()
print(orders['customer_id'].nunique(), 'customers by email')

Issue 3: Seasonal Effects Distorting Cohorts

Symptoms: Holiday cohorts (November/December) showing different patterns, making year-over-year comparisons difficult.

Solutions:

Issue 4: Data Export Limitations

Symptoms: Shopify admin exports timing out, incomplete data downloads, or API rate limiting.

Solutions:

Issue 5: Unclear Retention Definitions

Symptoms: Confusion about whether "retained" means any purchase activity, minimum purchase amount, or specific product category purchases.

Solutions:

Issue 6: Interpreting Low Overall Retention

Symptoms: Retention that looks very low to you at month 1 or month 6, and concern about the business.

Solutions:

Sources

The practice data is synthetic and made by the script in Step 1. It shows how the code works, not how any real store retains customers.

Conclusion

Customer retention cohort analysis transforms abstract customer behavior into actionable insights. By following this step-by-step tutorial, you now have a working framework to:

Remember that cohort analysis is most powerful when done regularly and combined with experimentation. As you identify retention gaps, test interventions (improved onboarding, win-back campaigns, loyalty programs) and measure their impact on subsequent cohorts. This gives you a way to learn from each round.

Even a few points of month-3 retention, across hundreds of customers, change how many repeat orders you can expect, so it is worth tracking, with the cohort-size caution above. Cohort tables describe what happened; they do not show why, so test any change before you rely on it.

If you would rather not write the code, you can upload a Shopify orders export to MCP Analytics instead.

Explore more: Shopify Analytics: all tools, tutorials, and guides →

Not sure which plan? Compare plans →

Your turn

Bring your own data and the question you actually need answered.

MCP AnalyticsData science by email Send us your data and your question, and we will reply. ds@mcpanalytics.ai