# Customer Lifetime Value in Python: Cumulative Revenue Curves and a BG/NBD Model

> Customer lifetime value in Python from an orders table. Build cumulative revenue per customer curves by cohort with pandas, find the CAC payback month, then fit BG/NBD and Gamma-Gamma models with lifetimes and PyMC-Marketing to predict 12-month LTV and validate it on a holdout period.

Source: https://www.pythoncharts.com/python/customer-lifetime-value-python/ | Published: 2026-12-05 | Author: Alex Scott | Category: Python | Tags: lifetimes, pymc-marketing, customer lifetime value, ltv, product analytics, pandas, matplotlib, cohort analysis

The simplest customer lifetime value (LTV) chart is **cumulative revenue per customer by signup cohort**: group orders by the quarter of each customer's first order, add up revenue by days since that first order, and divide by the cohort size. No model is needed, and it shows what customers have actually spent. To predict spend beyond what you have observed, fit a BG/NBD purchase model and a Gamma-Gamma spend model, covered further down with the `lifetimes` package and with PyMC-Marketing, the maintained replacement for it.

## Quick Example: Cumulative Revenue per Customer by Cohort

This builds a fake orders table (4,000 customers, 10,926 orders) and draws one curve per signup-quarter cohort, with an assumed cost of acquiring a customer as a dashed line. Swap the first block for your own `orders` with `customer_id`, `order_date` and `amount` columns.

```python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# --- Sample orders: one row per order ---
rng = np.random.default_rng(77)
n = 4000
end = pd.Timestamp("2026-11-30")  # the day the data was pulled
first = pd.Timestamp("2025-01-01") + pd.to_timedelta(rng.integers(0, 699, n), unit="D")  # first order
age = (end - first).days.to_numpy()
rate = rng.gamma(0.8, 1 / 60, n) * np.where(first >= "2026-01-01", 1.3, 1.0)  # orders per day while active; 2026 customers order more
p_leave = rng.beta(2, 3.5, n)                       # chance a customer leaves after each repeat order
repeats = np.minimum(rng.geometric(p_leave), 60)    # repeat orders a customer would place before leaving
cust = np.repeat(np.arange(n), repeats)
days = pd.Series(rng.exponential(1 / rate[cust])).groupby(cust).cumsum().to_numpy()  # days after the first order
cust = np.r_[np.arange(n), cust]                    # add every customer's first order
days = np.r_[np.zeros(n), days]
keep = days <= age[cust]                            # orders after the data pull don't exist yet
cust, days = cust[keep], days[keep]
avg_order = rng.lognormal(3.5, 0.45, n)
orders = pd.DataFrame({
    "customer_id": cust,
    "order_date": (first[cust] + pd.to_timedelta(days.astype(int), unit="D")).normalize(),
    "amount": (avg_order[cust] * rng.lognormal(0, 0.25, len(cust))).round(2),
})

# --- Cumulative revenue per customer, by signup quarter ---
orders["first_order"] = orders.groupby("customer_id")["order_date"].transform("min")
orders["cohort"] = orders["first_order"].dt.to_period("Q")
orders["month"] = (orders["order_date"] - orders["first_order"]).dt.days // 30 + 1  # 30-day periods since first order

complete = orders[orders["cohort"] < pd.Period("2026Q4")]  # the current quarter is still filling up
size = complete.groupby("cohort")["customer_id"].nunique()
ltv = (
    complete.groupby(["cohort", "month"])["amount"].sum()
    .unstack(fill_value=0).cumsum(axis=1)
    .div(size, axis=0)                                  # revenue per customer in the cohort
)
for c in ltv.index:                                      # blank out periods a cohort hasn't fully reached
    ltv.loc[c, ltv.columns > (end - c.end_time).days // 30] = np.nan

# --- Plot ---
cac = 75  # assumed cost to acquire one customer
fig, ax = plt.subplots(figsize=(9, 5.5))
colors = plt.cm.viridis(np.linspace(0.05, 0.85, len(ltv)))
for color, (cohort, row) in zip(colors, ltv.iterrows()):
    row = row.dropna()
    ax.plot(row.index, row, color=color, lw=2, label=str(cohort))
ax.axhline(cac, color="#999999", ls="--", lw=1)
ax.text(20, cac + 1.5, f"Cost to acquire (${cac})", ha="right", color="#666666", fontsize=9)
ax.set_xticks(range(0, 21, 2))
ax.legend(title="Signup quarter", frameon=False, loc="upper left")
ax.set_xlabel("Months since first order (30-day periods)")
ax.set_ylabel("Cumulative revenue per customer ($)")
ax.set_title("Revenue per customer by signup cohort")
ax.spines[["top", "right"]].set_visible(False)
plt.show()
```

![Cumulative revenue per customer by signup quarter: curves for seven cohorts climb quickly in the first months and flatten, the 2026 Q1 curve sits above the 2025 curves, and a dashed line marks an assumed $75 cost to acquire a customer](https://www.pythoncharts.com/python/customer-lifetime-value-python/images/ltv-quick-example.png)

Each curve is that cohort's observed LTV so far, and the final point is its LTV to date. A curve stops where the cohort's newest customer stops being observed: the 2026 Q3 cohort has only two months of history, so its line is short. Curves flatten as customers drift away. The 2026 Q1 curve sits well above the 2025 curves from the first months, which is the kind of change you would want to trace back to something you shipped.

The code targets pandas 3.1 and Matplotlib 3.11.

## How many months until a cohort pays back its acquisition cost?

The payback month is the first month where cumulative revenue per customer reaches the cost of acquiring that customer. With the curves in a DataFrame, that is `idxmax` on a boolean comparison. Use revenue minus cost of goods if you have it, since margin pays back later than revenue:

```python
payback = (ltv >= cac).idxmax(axis=1).where((ltv >= cac).any(axis=1))
table = ltv[[3, 6, 12]].round(0).assign(payback_month=payback)
print(table.to_string())
```

```text
month      3      6     12  payback_month
cohort                                   
2025Q1  66.0   82.0  101.0            5.0
2025Q2  70.0   86.0  109.0            5.0
2025Q3  66.0   83.0  106.0            5.0
2025Q4  68.0   86.0    NaN            4.0
2026Q1  77.0   98.0    NaN            3.0
2026Q2  72.0    NaN    NaN            4.0
2026Q3   NaN    NaN    NaN            NaN
```

The 2025 cohorts pay back their $75 in month 4 or 5, and 2026 Q1 does it in month 3. 2026 Q3 has no payback month yet because it has only two months of data. `NaN` in the 12-month column just means the cohort hasn't been observed that long yet. It isn't a zero. Revenue in the first three months (77 dollars for 2026 Q1 against 66 to 70 for the 2025 cohorts) is the number most teams can act on, because it is the earliest signal for a new channel or campaign.

## Why not just multiply average order value by orders per year?

The curves above only describe the past. The textbook shortcut, average order value x purchase frequency x expected lifetime, needs a guess at the lifetime, and the lifetime of customers who haven't left yet is exactly what you don't know. That is the gap probabilistic models fill: given each customer's order history, they estimate how many more orders to expect and how likely the customer is to still be active.

## The hacky way: BG/NBD and Gamma-Gamma with lifetimes

The `lifetimes` package fits two models, and together they give a per-customer LTV forecast:

- **BG/NBD** (`BetaGeoFitter`) models how often each customer orders while active and the chance they have already left. It needs three numbers per customer: `frequency` (repeat orders), `recency` (days between their first and last order) and `T` (days since their first order).
- **Gamma-Gamma** (`GammaGammaFitter`) models the average value of an order, for customers with at least one repeat order.

"Hacky" because `lifetimes` hasn't had a release since July 2020 (0.11.3). It still installs and runs with NumPy 2, SciPy 1.18 and pandas 3.1 on Python 3.14, which is why this post pins it in its own environment, but two things are broken. `lifetimes.datasets` imports `pkg_resources`, which a plain environment no longer has, so the bundled example datasets don't load. And with pandas 3, `calibration_and_holdout_data` fails with `ValueError: No objects to concatenate` unless you pass `monetary_value_col` (see the holdout step). The same function also triggers a pandas 3 deprecation warning, because lifetimes sets `pd.options.mode.chained_assignment`, and the warning is harmless. Everything else used here works. The maintained replacement is PyMC-Marketing (`pymc-marketing`, last released 2026-11-18), which has the same models and is covered in its own section below. `lifetimes` is still the quick option: it fits in a fraction of a second, and the API is small.

### Build the summary table and fit BG/NBD

`summary_data_from_transaction_data` turns an orders table into one row per customer. Check the model against what really happened with `plot_period_transactions`, which compares the observed number of repeat orders per customer with what the model simulates:

```python
from lifetimes import BetaGeoFitter, GammaGammaFitter
from lifetimes.plotting import plot_period_transactions
from lifetimes.utils import summary_data_from_transaction_data

summary = summary_data_from_transaction_data(
    orders, "customer_id", "order_date",
    monetary_value_col="amount", observation_period_end=end,
)
print(summary.head(3).round(1))

bgf = BetaGeoFitter()  # penalizer_coef defaults to 0
bgf.fit(summary["frequency"], summary["recency"], summary["T"])
print(bgf.params_.round(3).to_dict())

fig, ax = plt.subplots(figsize=(8, 5))
plot_period_transactions(bgf, ax=ax, max_frequency=10)
ax.set_xlabel("Number of repeat orders")
plt.show()
```

```text
             frequency  recency      T  monetary_value
customer_id                                           
0                 11.0    275.0  657.0            39.9
1                  0.0      0.0  149.0             0.0
2                  0.0      0.0  255.0             0.0
{'r': 0.804, 'alpha': 57.996, 'a': 2.191, 'b': 3.837}
```

![Bar chart comparing the actual number of customers with 0 to 10 repeat orders against the BG/NBD model's prediction, with the model bars within a few percent of the actual bars at every count](https://www.pythoncharts.com/python/customer-lifetime-value-python/images/ltv-period-transactions.png)

Two details that trip people up:

- `frequency` counts *repeat* orders, so a customer with one order has `frequency = 0`, and `recency` is 0 for them as well.
- `monetary_value` is the average value of the *repeat* orders only, because the model assumes the first order isn't representative.

If the observed and model bars disagree badly, the model isn't a good fit for your data and its LTV numbers shouldn't be trusted. Here the bars are close: the model is within about 7% of the actual count at every number of repeat orders. That is the best case for BG/NBD, since the sample orders are generated by the same process the model assumes. Real order data usually fits worse. The model bars come from a simulation, so they move a little each time you run the plot.

### Who is still active, and who will order next?

`plot_frequency_recency_matrix` is the model's version of an RFM grid. For each pair of frequency and recency, it draws the expected number of orders over the next `T` days:

```python
from lifetimes.plotting import plot_frequency_recency_matrix

plt.figure(figsize=(8, 6))  # this function draws on the current axes and takes no ax argument
plot_frequency_recency_matrix(
    bgf, T=90, max_frequency=12, max_recency=360,
    title="Expected orders in the next 90 days",
)
plt.gca().invert_yaxis()  # put recency 0 at the bottom
plt.show()
```

![Heatmap of expected orders in the next 90 days by customer's repeat order count and recency; the highest values are for customers with many repeat orders who ordered recently, and customers with many orders but a long gap are predicted to be inactive](https://www.pythoncharts.com/python/customer-lifetime-value-python/images/ltv-frequency-recency.png)

Here `recency` is lifetimes' definition: days between a customer's first and last order, so a high value means they were still ordering lately. The hot corner is a customer with many repeat orders who ordered recently. The same customer with the same order count but a long gap since the last order (low recency) is predicted to have left, and the expected orders drop to almost zero. A plain RFM score for frequency alone would not see that.

### Check the forecast against a holdout period

Before trusting a prediction, hide the last six months, fit on the earlier data, and check the forecast against the orders you hid. `calibration_and_holdout_data` does the split:

```python
from lifetimes.plotting import plot_calibration_purchases_vs_holdout_purchases
from lifetimes.utils import calibration_and_holdout_data

cal = calibration_and_holdout_data(
    orders, "customer_id", "order_date", monetary_value_col="amount",  # required with pandas 3
    calibration_period_end="2026-05-31", observation_period_end=end,
)
bgf_cal = BetaGeoFitter()
bgf_cal.fit(cal["frequency_cal"], cal["recency_cal"], cal["T_cal"])

predicted = bgf_cal.predict(cal["duration_holdout"].iloc[0], cal["frequency_cal"], cal["recency_cal"], cal["T_cal"])
print(f"holdout orders: actual {cal['frequency_holdout'].sum():.0f}, predicted {predicted.sum():.0f}")

fig, ax = plt.subplots(figsize=(8, 5))
plot_calibration_purchases_vs_holdout_purchases(bgf_cal, cal, n=8, ax=ax)
plt.show()
```

```text
holdout orders: actual 1643, predicted 1562
```

![Line chart of average actual and model-predicted repeat orders in the last six months, grouped by the customer's repeat orders in the earlier calibration period; the two lines rise together and stay close, with the model below the actual line for customers with no calibration-period repeat orders and for the few with seven](https://www.pythoncharts.com/python/customer-lifetime-value-python/images/ltv-holdout.png)

Each point groups customers by how many repeat orders they had in the calibration period (the x-axis) and compares the average actual orders in the holdout period with the model's prediction. Lines that rise together mean the model ranks customers properly, not just in total. Overall the model predicts 1,562 holdout orders against 1,643 actual, about 5% too few. The lines stay close from zero to six orders. The largest gap is at seven orders, where the actual average is about 2.2 and the model says 1.45, but only 20 customers are in that group. Even so, a gap of a few percent is a reason to treat the LTV numbers as a ranking first and a dollar forecast second.

### Predict 12-month LTV for each customer

Gamma-Gamma assumes a customer's average order value isn't related to how often they order. Check that before fitting. Then `customer_lifetime_value` combines both models into expected revenue over the next `time` months, discounted at `discount_rate` per month:

```python
repeaters = summary[summary["frequency"] > 0]
print("corr(frequency, monetary_value):", round(repeaters["frequency"].corr(repeaters["monetary_value"]), 2))

ggf = GammaGammaFitter()
ggf.fit(repeaters["frequency"], repeaters["monetary_value"])

repeaters = repeaters.assign(
    ltv_12m=ggf.customer_lifetime_value(
        bgf, repeaters["frequency"], repeaters["recency"], repeaters["T"],
        repeaters["monetary_value"], time=12, freq="D", discount_rate=0.01,
    )
)
print(repeaters["ltv_12m"].describe().round(1))

# share of predicted value held by the top customers
value = repeaters["ltv_12m"].sort_values(ascending=False).to_numpy()
share = value.cumsum() / value.sum()
top = np.arange(1, len(value) + 1) / len(value)
print(f"top 10% of customers: {share[int(len(share) * 0.10) - 1]:.0%} of predicted value; top 20%: {share[int(len(share) * 0.20) - 1]:.0%}")

fig, ax = plt.subplots(figsize=(7, 5))
ax.plot(top * 100, share * 100, color="#7b3fa0", lw=2.5)
ax.plot([0, 100], [0, 100], color="#999999", ls="--", lw=1)
ax.set_xlabel("Customers, ranked by predicted 12-month value (%)")
ax.set_ylabel("Share of predicted value (%)")
ax.set_title("Where the predicted LTV sits")
ax.spines[["top", "right"]].set_visible(False)
plt.show()
```

```text
corr(frequency, monetary_value): 0.01
count    2932.0
mean       23.9
std        36.0
min         0.0
25%         3.3
50%        12.2
75%        30.9
max       543.5
Name: ltv_12m, dtype: float64
top 10% of customers: 44% of predicted value; top 20%: 63%
```

![Curve of cumulative share of predicted 12-month customer value against share of customers ranked from highest to lowest value, bowing well above the dashed diagonal because a small share of customers holds most of the value](https://www.pythoncharts.com/python/customer-lifetime-value-python/images/ltv-concentration.png)

The `freq="D"` argument tells lifetimes that your `recency` and `T` are in days, so that `time=12` is converted to 12 months. If your summary table is in weeks (`freq="W"`), pass that. A wrong `freq` quietly changes every number.

The mean forecast is $24 per customer over the next 12 months, but the median is $12, because the top 10% of customers hold 44% of the predicted value and the top 20% hold 63%. The result is one forecast per customer who has ordered more than once. Customers with a single order have no repeat spend for Gamma-Gamma to learn from, so they need a fallback, such as the overall average. The curve bowing far above the diagonal is what that concentration looks like, and it is usually what you want to know before you set retention budgets.

## The maintained way: BG/NBD and Gamma-Gamma with PyMC-Marketing

PyMC-Marketing is where this model family lives now. Its CLV module has `BetaGeoModel` and `GammaGammaModel`, the same two models as above, and its source calls `lifetimes` "the legacy library" its predictive methods were adapted from. It is under active development, works with current pandas, and fits the models with Bayesian sampling instead of a point estimate, so every number comes with a range. The cost is speed: fitting runs MCMC, about ten seconds for these 4,000 customers where `lifetimes` takes a fraction of a second.

The inputs are the same `frequency`, `recency` and `T` columns, but the data needs a `customer_id` column rather than an index, and you pass it to `fit()`:

```python
from pymc_marketing.clv import BetaGeoModel, GammaGammaModel

bgm = BetaGeoModel()
bgm.fit(summary.reset_index(), random_seed=42, progressbar=False)  # NUTS sampling, about 10 seconds
print(bgm.fit_summary().loc[["r", "alpha", "a", "b"], ["mean", "sd", "eti89_lb", "eti89_ub", "r_hat"]].round(2))
```

```text
        mean      sd eti89_lb eti89_ub r_hat
r      0.743  0.0242     0.71     0.78  1.00
alpha  50.86    2.36       47       55  1.00
a       2.22    0.29      1.8      2.7  1.00
b       3.88     0.6        3      4.9  1.00
```

The parameters are `r`, `alpha`, `a` and `b`, the same four as `BetaGeoFitter` and with the same meaning. Each row has a posterior mean, a standard deviation and an 89% interval (`eti89_lb`, `eti89_ub`). `r_hat` should be 1.00; a value above about 1.01 means the sampler didn't converge and the numbers aren't usable. `a` and `b` (2.22 and 3.88) agree with the `lifetimes` fit (2.19 and 3.84), and with the `a = 2` and `b = 3.5` the sample data was generated from. `r` and `alpha` come out lower than in `lifetimes` (0.74 and 51 against 0.80 and 58). Those two trade off against each other, and their ratio, the average order rate while active, is nearly the same: 0.0146 orders per day here against 0.0139. PyMC-Marketing also puts priors on the parameters where `lifetimes` fits by maximum likelihood, which is one reason they differ.

### Get a range for the holdout forecast

The same holdout check as before works here, and the posterior turns the single predicted total into a distribution. `expected_purchases()` returns one set of predictions per posterior draw, so summing over customers gives one forecast total per draw:

```python
cal_data = cal.reset_index().rename(
    columns={"frequency_cal": "frequency", "recency_cal": "recency", "T_cal": "T"}
)[["customer_id", "frequency", "recency", "T"]]

bgm_cal = BetaGeoModel()
bgm_cal.fit(cal_data, random_seed=42, progressbar=False)
holdout_days = int(cal["duration_holdout"].iloc[0])
total = bgm_cal.expected_purchases(cal_data, future_t=holdout_days).sum("customer_id").to_numpy().ravel()

actual = cal["frequency_holdout"].sum()
lo, hi = np.percentile(total, [5.5, 94.5])
print(f"holdout orders: actual {actual:.0f}, predicted {total.mean():.0f} (89% interval {lo:.0f} to {hi:.0f})")

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.hist(total, bins=40, color="#7b3fa0", alpha=0.8)
ax.axvline(actual, color="#222222", lw=2, label=f"Actual holdout orders ({actual:.0f})")
ax.set_xlabel("Expected orders in the six-month holdout period")
ax.set_ylabel("Posterior draws")
ax.set_title("PyMC-Marketing forecast of the hidden six months")
ax.margins(y=0.2)  # headroom for the legend
ax.legend(loc="upper left")
ax.spines[["top", "right"]].set_visible(False)
plt.show()
```

```text
holdout orders: actual 1643, predicted 1524 (89% interval 1457 to 1591)
```

![Histogram of PyMC-Marketing's posterior forecast of total orders in the six-month holdout period, with a vertical line at the actual count](https://www.pythoncharts.com/python/customer-lifetime-value-python/images/ltv-pymc-holdout.png)

The model forecasts 1,524 orders against 1,643 actual, about 7% low, and the actual total sits just outside the 89% interval. The interval only reflects uncertainty in the fitted parameters, not the luck of how many orders customers actually place, so it is narrower than the real spread of outcomes. Read it as "how sure is the model of its own average", not as a promise about next quarter. The `lifetimes` fit above misses by 5% in the other direction (1,562 predicted), so neither library is clearly more accurate here.

### Predict 12-month value per customer with a range

Gamma-Gamma works the same way: fit it on customers with repeat orders, ask for each customer's expected order value, and multiply by the expected number of orders from the BG/NBD model. Both calls return draws, so the product does too:

```python
rep = repeaters.reset_index()
ggm = GammaGammaModel()
ggm.fit(rep[["customer_id", "frequency", "monetary_value"]], random_seed=42, progressbar=False)

spend = ggm.expected_customer_spend(rep[["customer_id", "frequency", "monetary_value"]])
orders_12m = bgm.expected_purchases(rep[["customer_id", "frequency", "recency", "T"]], future_t=360)  # 12 x 30 days
ltv_draws = orders_12m * spend  # one LTV per customer per posterior draw
ltv_pm = ltv_draws.mean(("chain", "draw")).to_series()

print(ltv_pm.describe().round(1))
total_ltv = ltv_draws.sum("customer_id").to_numpy().ravel()
lo, hi = np.percentile(total_ltv, [5.5, 94.5])
print(f"predicted 12-month revenue from repeat customers: ${total_ltv.mean():,.0f} (89% interval ${lo:,.0f} to ${hi:,.0f})")
```

```text
count    2932.0
mean       25.2
std        37.8
min         0.0
25%         3.4
50%        13.0
75%        32.6
max       571.4
dtype: float64
predicted 12-month revenue from repeat customers: $73,809 (89% interval $69,482 to $78,217)
```

The mean is $25.2 per customer and the median $13.0, close to the $23.9 and $12.2 from `lifetimes`. The small gap is partly the discount: `lifetimes` was given `discount_rate=0.01` per month, and the code here doesn't discount. The new part is the total: about $73,800 of revenue from repeat customers over the next 12 months, with an 89% interval of $69,500 to $78,200. That interval has the same limit as the holdout one, since it covers the parameters and not the randomness of individual orders.

`GammaGammaModel` also has an `expected_customer_lifetime_value()` method that combines both models and handles discounting. On this table of 2,932 customers it was still running after 25 minutes, so this post multiplies the two outputs directly, which takes about two seconds.

## Cumulative curves or a BG/NBD model?

| | Cumulative revenue curves | BG/NBD + Gamma-Gamma |
|---|---|---|
| Needs | Orders and a cohort definition | Orders, a repeat-order history and a model check |
| Answers | What have customers spent so far, and how fast? | What will each customer spend next? |
| Strengths | Transparent, easy to explain, no modeling assumptions | Forecasts beyond the observed window and per customer |
| Weak spots | Can't see past the oldest cohort's age | Assumes steady ordering, and spend independent of frequency |
| Good for | CAC payback, comparing channels and campaigns | Prioritizing customers, forecasting revenue from existing customers |

Start with the curves. Use BG/NBD when you need numbers for each customer, or a forecast past the age of your oldest cohort, and run the holdout check before you use it.

Between the two BG/NBD libraries, `lifetimes` is quicker and its plotting helpers are handy, while PyMC-Marketing is the one that is still maintained and gives you intervals. For new work, use PyMC-Marketing unless you only need a fast point estimate.

## Practical Tips

- **Use margin if you can.** Revenue per customer overstates payback. Subtract product and fulfillment costs before comparing with acquisition cost.
- **Don't compare cohorts of different ages.** A 2025 Q1 cohort will always look better than 2026 Q3 at the end of its curve. Compare the same month on each curve.
- **Keep refunds out of `amount`.** A refund as a negative row will make early revenue look lower than it was and distort the average order value the Gamma-Gamma model learns from.
- **Decide what an order is.** Several line items on one day should be one order for frequency, so aggregate to one row per customer per day before the BG/NBD step. `summary_data_from_transaction_data` counts at most one order per customer per day.
- **Leave `penalizer_coef` at 0 unless you need it.** On this data, `BetaGeoFitter(penalizer_coef=0.01)` pulled `a` and `b` down to 0.66 and 0.87 on the calibration fit (true values 2 and 3.5) and over-predicted holdout orders by 9% (1,791 against 1,643). With 0.001 the forecast was 1,656, and with the default of 0 it was 1,562.
- **Fit the model on enough customers.** With a few hundred customers and few repeat orders, the fitted parameters swing a lot between runs. Check `plot_period_transactions` each time.

## Similar Topics

- [RFM Analysis in Python: Score and Segment Customers with pandas](https://www.pythoncharts.com/python/rfm-segmentation-python/)
- [Cohort Retention Heatmap in Python with pandas and Seaborn](https://www.pythoncharts.com/python/cohort-retention-heatmap-python/)
- [Kaplan-Meier Survival Curve in Python with lifelines](https://www.pythoncharts.com/python/kaplan-meier-survival-curve-python/)
