Customer Lifetime Value with Python: Beyond Simple Averages

Customer Lifetime Value Python Beyond Simple Averages
Image by Author
 

Customer lifetime value (CLV) represents the total revenue a business can expect from a single customer account throughout its relationship with the business. Basic CLV calculations use simple averages, but advanced modeling techniques provide more accurate, individualized predictions that account for varying customer behaviors and purchase patterns.

This tutorial shows you how to calculate CLV using Python’s lifetimes library, moving from basic averages to probabilistic models that predict both transaction frequency and monetary value for individual customers.

Prerequisites and Setup

This tutorial requires the lifetimes library, which implements probabilistic models for customer behavior analysis. Install it using pip if you haven’t already:

 
pip install lifetimes pandas numpy

The lifetimes library provides built-in datasets and implements two key models: the BG/NBD model for predicting purchase frequency and the Gamma-Gamma model for estimating monetary value. You will also use pandas for data manipulation and NumPy for numerical operations.

Loading and Exploring Customer Data

We’ll start by loading a customer dataset that contains the key metrics for CLV calculation:

 
import pandas as pd
import numpy as np
from lifetimes.datasets import load_cdnow_summary_data_with_monetary_value

# Customer-level summary: frequency, recency, T, monetary_value (AOV)
summary = load_cdnow_summary_data_with_monetary_value()
print(summary.head(3))
print("Shape:", summary.shape)
print("Columns:", list(summary.columns))
 
             frequency  recency      T  monetary_value
customer_id                                           
1                    2    30.43  38.86           22.35
2                    1     1.71  38.86           11.77
3                    0     0.00  38.86            0.00
Shape: (2357, 4)
Columns: ['frequency', 'recency', 'T', 'monetary_value']

The dataset contains customer-level summary data with four key columns that form the foundation for CLV modeling:

  • frequency – Number of repeat purchases made by each customer (excludes the initial purchase)
  • recency – Time elapsed since the customer’s most recent purchase, measured in weeks
  • T – Total observation period for each customer, representing how long we’ve been tracking each customer in weeks
  • monetary_value – Average order value (AOV) calculated from all of the customer’s purchases

All time measurements use weeks as the unit. Note that frequency counts only repeat purchases, so a customer with frequency = 0 made at most one purchase during the observation period.

Note on Data Quality: You’ll notice some customers show frequency = 0, recency = 0, and monetary_value = 0. These are one-time purchasers (since frequency counts only repeat purchases) or customers with data quality issues. The Gamma-Gamma model is fitted only on customers with frequency > 0, as shown in our mask. However, the CLV calculation still produces estimates for zero-frequency customers using fallback values.

Method 1: Simple Average CLV Calculation

Before implementing advanced models, let’s establish a baseline using simple averages across all customers:

 
# Simple Baseline CLV Calculation
# Cohort Average Order Value (exclude NaNs)
aov = summary['monetary_value'].dropna().mean()

# Average weekly transaction rate across customers
avg_weekly_rate = (summary['frequency'] / summary['T']).mean()

# Baseline projection for 26 weeks
horizon_weeks = 26
clv_simple = avg_weekly_rate * aov * horizon_weeks

print(f"Average Order Value: ${aov:.2f}")
print(f"Avg weekly transactions: {avg_weekly_rate:.4f}")
print(f"Simple-average CLV (26w): ${clv_simple:.2f}")
 
Average Order Value: $14.08
Avg weekly transactions: 0.0319
Simple-average CLV (26w): $11.67

This simple approach treats all customers identically, using cohort averages for both purchase frequency and monetary value. While easy to calculate, it doesn’t capture individual customer differences and behavioral patterns.

The calculation assumes every customer will behave like the average customer going forward by purchasing at the same weekly rate (0.0319 transactions) and spending the same amount per order ($14.08). In reality, some customers might be frequent buyers who purchase weekly, while others might buy once per quarter. Similarly, some customers consistently place large orders while others make small purchases. This averaging approach misses these variations entirely, potentially undervaluing high-frequency customers and overvaluing one-time buyers.

Additionally, this method doesn’t account for customer lifecycle stages. A customer who made their first purchase yesterday gets the same prediction as someone who hasn’t bought anything in six months, even though their likelihood of future purchases differs significantly.

Method 2: BG/NBD Model For Transaction Prediction

The BG/NBD (Beta-Geometric/Negative Binomial Distribution) model provides individualized predictions by modeling when customers become inactive and how frequently active customers make purchases:

 
from lifetimes import BetaGeoFitter

# Fit BG/NBD on frequency/recency/T (all in weeks)
bgf = BetaGeoFitter(penalizer_coef=0.001)
bgf.fit(summary['frequency'], summary['recency'], summary['T'])

# Predict expected purchases for the next 26 weeks
future_weeks = 26
summary['pred_txns_26w'] = bgf.conditional_expected_number_of_purchases_up_to_time(
    future_weeks, summary['frequency'], summary['recency'], summary['T']
)

print("\nPredicted transactions (26 weeks):")
print()
print(summary['pred_txns_26w'].describe()[['count','mean','50%','max']].round(3))
print()
print(summary[['pred_txns_26w']].head(5).round(3))
 
Predicted transactions (26 weeks):

count    2357.000
mean        0.525
50%         0.167
max        16.341
Name: pred_txns_26w, dtype: float64

             pred_txns_26w
customer_id               
1                    0.898
2                    0.128
3                    0.134
4                    0.134
5                    0.134

The BG/NBD model produces individualized transaction predictions ranging from 0.128 to over 16 transactions in 26 weeks. This wide range reflects the model’s ability to distinguish between different customer behaviors based on their purchase history.

Customer 1, with two repeat purchases and recent activity (recency = 30.43 weeks), gets a prediction of 0.898 transactions. This is much higher than customers 2–5, who all have minimal purchase history and receive predictions around 0.13 transactions. The model recognizes that Customer 1 has demonstrated repeat purchase behavior and remained active longer into the observation period, making them more likely to continue buying.

Notice how customers 3–5, with zero repeat purchases, still receive positive predictions (0.134 transactions). The BG/NBD model treats these as customers who made one initial purchase and might still be active. This probabilistic approach avoids writing off single-purchase customers entirely.

Complete CLV Calculation With Gamma-Gamma Model

The Gamma-Gamma model estimates individual customer monetary value, which we combine with BG/NBD transaction predictions for a complete CLV calculation:

 
from lifetimes import GammaGammaFitter

# Fit Gamma-Gamma on customers with repeat history and monetary values
mask = (summary['frequency'] > 0) & summary['monetary_value'].notna()
ggf = GammaGammaFitter(penalizer_coef=0.001).fit(
    summary.loc[mask, 'frequency'], summary.loc[mask, 'monetary_value']
)

# Calculate CLV for 26 weeks with reasonable discount rate
# Using 0.5% weekly discount (≈ 30% annual)
clv_26w = ggf.customer_lifetime_value(
    bgf,
    summary['frequency'], summary['recency'], summary['T'],
    summary['monetary_value'],
    time=26, freq='W', discount_rate=0.005  # 0.5% weekly discount
)
summary['clv_26w'] = clv_26w

print(f"\nCLV Summary (26 weeks, 0.5% weekly discount):")
print()
print(summary['clv_26w'].describe()[['mean','50%','75%','max']].round(2))
print()
print("\nSample predictions:")
print(summary[['pred_txns_26w','clv_26w']].head(5).round(2))
 
CLV Summary (26 weeks, 0.5% weekly discount):

mean      63.02
50%       21.32
75%       34.58
max     2484.31
Name: clv_26w, dtype: float64


Sample predictions:
             pred_txns_26w  clv_26w
customer_id                        
1                     0.90    69.92
2                     0.13     6.78
3                     0.13    17.89
4                     0.13    17.89
5                     0.13    17.89

The complete model produces CLV estimates with significant variation, from under \$7 to over \$2,400. The median CLV of \$21.32 is much higher than our simple average of \$11.67, showing how individualized modeling captures value concentration among high-value customers.

Interpreting the Results

The probabilistic approach reveals insights that simple averages miss. Customer 1, with two repeat purchases and recent activity, gets a CLV estimate of $69.92, reflecting both higher predicted transaction frequency (0.90) and above-average monetary value.

Customers 3–5, despite having zero repeat purchases, still get positive CLV estimates because the BG/NBD model accounts for the possibility that these customers remain active but haven’t yet made their next purchase. This probabilistic treatment avoids the zero-CLV trap that simpler methods create for single-purchase customers.

An interesting result: Customer 2, who made one repeat purchase worth \$11.77, gets a lower CLV estimate (\$6.78) than Customer 3, who made no repeat purchases (\$17.89). Here’s why:

Customer 2: With actual purchase data (frequency = 1, monetary_value = $11.77), both models can make personalized predictions. The BG/NBD predicts low future activity (0.128 transactions), and the Gamma-Gamma confirms below-average spending, resulting in low CLV.

Customer 3: With no repeat purchases (frequency = 0), the Gamma-Gamma model cannot estimate monetary value. The CLV function uses a population average monetary value as a fallback. Combined with the BG/NBD’s prediction (0.134 transactions), this yields a higher CLV than Customer 2.

This illustrates an important principle: having data showing low engagement can result in lower predictions than having no behavioral data at all, since the latter defaults to population averages.

Model Advantages and Considerations

The BG/NBD and Gamma-Gamma combination offers advantages over simple averaging approaches. It accounts for customer differences, predicts individual behavior patterns, and handles customers with limited purchase history better than rule-based methods.

These models assume purchase behavior follows specific probability distributions and require enough historical data for reliable parameter estimation. The models work best with at least 6–12 months of transaction history and perform well when customers have varying purchase frequencies.

Implementation Best Practices

When implementing probabilistic CLV models, start with model validation using holdout periods to test prediction accuracy. Monitor model performance across different customer segments, as some groups may not fit the underlying distributional assumptions well.

Consider recalibrating models quarterly or when significant business changes occur, such as new product launches or major marketing campaigns. The discount rate should reflect your organization’s cost of capital and strategic time horizon for customer investment decisions.

In production systems, consider whether to include CLV estimates for customers with no repeat purchases. Some practitioners exclude these customers from CLV calculations entirely, while others use the fallback values as shown here. Your choice depends on your business context and how you plan to use these predictions.

Conclusion

Probabilistic CLV modeling provides a different perspective on customer value estimates than simple averaging approaches. The combination of BG/NBD transaction prediction and Gamma-Gamma monetary modeling captures individual customer behavior patterns that drive effective segmentation and targeted marketing strategies.

This methodology enables data-driven customer acquisition costs, retention investment prioritization, and lifetime value strategies that simple averages can’t support. The individualized predictions help identify high-value customers early in their lifecycle and guide marketing spend allocation across customer segments.

Leave a Reply

Your email address will not be published. Required fields are marked *