How do I analyse churn and customer lifetime value with survival analysis in Python?
TL;DR
Difficulty: Advanced
Survival analysis says when customers leave, not just whether, and lifelines does the modelling in a few lines. The hard part is the table.
- Decide when the clock starts, what stops it and one fixed cut off, then check that the censored share rises for young cohorts.
- Kaplan Meier curves and the monthly hazard show when to act: in the generated Vanlog data 70% of Team accounts survive a year against 54% of Starter.
- The Cox model finds the drivers (onboarding 0.56, paid search 1.22), and the proportional hazards check flags annual billing, which is fixed by stratifying.
- Survival curves per segment become a discounted lifetime value: the theory chapter's £1,903 reproduces exactly, and a paid search Starter account is worth £282.
- Pin pandas below 3.0: lifelines 0.30.3 requires it.
A churn rate tells you how many customers left. Survival analysis tells you when they leave, who leaves faster and what a new customer is worth. This chapter builds it in Python with lifelines on Vanlog, the invented SaaS from my Marketing Analytics chapter: from a raw export with dates to Kaplan Meier curves, a checked Cox model and a lifetime value per segment you can bid on.
What this chapter builds, and where the theory lives
The concepts are explained in Survival analysis, churn and customer lifetime value, chapter 8 of my Marketing Analytics series: why "when" beats "whether", what censoring is, how a Kaplan Meier curve and a Cox model work, and how survival turns into a lifetime value. This chapter builds all of it in Python, line by line, on data you can generate and run yourself.
The example is the same one. Vanlog is an invented Rails SaaS from Manchester for trades businesses, with about 2,400 paying accounts on two plans: Starter at £29 a month, mostly sole traders, and Team at £89 a month with several seats. The founder's question is the one every subscription business ends up asking: "How long do our customers really stay, what is a new one worth, and what can we afford to pay to win one?"
The data in this chapter is generated in code to resemble the example in the Marketing Analytics chapter. The generator builds in the same story (Team accounts last longer, onboarding nearly halves the risk, paid search accounts leave faster), so you will recognise the curves and the hazard ratios, but the numbers come out of a simulation and carry its noise. Where they differ from the theory chapter, I say so.
By the end you will have:
- one clean table with a duration and an event flag per account, built from a raw export with dates in it
- Kaplan Meier curves per plan, with a chart a board can read
- the monthly hazard, which tells you when to act
- a Cox model with hazard ratios, and a check of its central assumption that, in this data, fails for a good reason
- a discounted lifetime value per segment, and a scored list of the accounts you still have.
You should be comfortable with pandas and with the regression ideas in statistical models in Python with statsmodels and scikit learn. If yes or no outcomes and lift charts are fresh in your mind from logistic regression, lift charts and basket analysis in Python, even better: this chapter is what you do when the outcome is not yes or no but "how long until".
The table is the analysis: three clock decisions
Here is the idea I would put above everything else in this chapter. The modelling in survival analysis is a few lines of code. The part that decides whether the answer is right is the table you feed it: one row per customer, with how long you watched them and whether the watching ended in churn. Every number downstream inherits the choices you made building that table, and tutorials skip it because their datasets arrive already built.
Three decisions make or break that table. I call them the clock decisions, and I write them down in two sentences before I touch a model.
When does the clock start? At signup, at the end of the free trial, or at the first successful payment? If trials are included, everyone who never converts counts as a month one churner, and the first month's hazard explodes.
What stops the clock? The day someone clicks "cancel", the end of the period they have paid for, or the day a payment finally fails? A card that expires is churn too, but it has a different cause and a different fix (a payment reminder, not a retention call). If you mix voluntary and involuntary churn in one event, your model will try to explain card expiry dates with onboarding.
Where is the cut off? One fixed moment for every account: the time the export was taken, in Coordinated Universal Time (UTC). Never "today" computed inside a notebook, because then every rerun moves the censoring and the numbers drift without anyone changing anything.
The test I use: read your two sentences to whoever owns the finance numbers. If they would count it differently, fix the table, not the model.
Example: what the trial decision does to month one
Take 100 new Vanlog signups in one month. Thirty of them start a 14 day trial and never pay. Of the 70 that pay, three cancel within their first paid month, which is about the 3.5% first month hazard the Marketing Analytics chapter shows for the Team plan.
- Clock starts at signup, trial dropouts counted as churn: churn in month one.
- Clock starts at the first payment, trial dropouts excluded: churn in month one.
Both are arithmetic on the same customers. The first is a conversion problem dressed up as a retention problem, and if it goes into a survival model, every hazard ratio after it is about trial conversion. For Vanlog the decision is: the clock starts at the first payment, stops on the date the subscription ends, involuntary churn is a separate flag, and the cut off is 31 March 2026, 23:59 UTC, the moment of the export.
For the person who commissions this
If you only read one section, read this one. Survival analysis answers three questions a single churn rate cannot: when customers leave (so you know when to act), who leaves faster (so you know whom to act on), and what a new customer is worth over their life with you (so you know what you can pay to win one).
What to ask for:
- the two sentences: when does the clock start, and what stops it
- the Kaplan Meier curves per plan, with the number of accounts still at risk printed under the chart
- the monthly hazard for the first year, which shows where the risk peaks
- a table of hazard ratios, with a statement of whether the proportional hazards check passed and what was done if it did not
- lifetime value per segment, with the discount rate and the horizon written next to it.
What good looks like: one page of decisions, not a model report. "Phone Starter accounts that have not onboarded by day 14. Set the paid search bid limit for Starter at £94, not £250. Test the onboarding call on half the accounts first." If a lifetime value arrives as a single company wide number, ask for it per segment. If the hazard ratios arrive without the assumption check, ask for the check.
Setting up: lifelines, and the pandas 3 trap
The survival library for Python is lifelines, written by Cameron Davidson Pilon and maintained as open source since 2013.1 It does Kaplan Meier, the Cox model, the assumption checks and the predictions, and it plays well with pandas. statsmodels has survival tools too (SurvfuncRight and PHReg), and you met statsmodels in the statistical models chapter, but for this work I use lifelines because the checks and the prediction helpers save real time.2
One trap is new this spring. pandas 3.0 was released on 21 January 2026, with copy on write as the default behaviour and a new default string data type.3 The current lifelines release, 0.30.3 from 5 March 2026, declares that it needs pandas below 3.0 and Python 3.11 or newer.4 So if your environment already runs pandas 3, installing lifelines will either pull pandas back to 2.3 or fail, depending on your tool. Pin it on purpose, so the next person who rebuilds the environment gets the same versions. The habit comes from a reproducible Python analysis workflow, and the setup from why Python for data analysis, and how to set it up.
Example: a pinned environment that works in April 2026
With uv, in a project folder:5
uv add "lifelines==0.30.3" "pandas>=2.3,<3" "numpy>=2.4" "matplotlib>=3.10"
Or with pip in a virtual environment:
python -m pip install "lifelines==0.30.3" "pandas>=2.3,<3" "numpy>=2.4" "matplotlib>=3.10"
Then check what you actually got:
import sys
import numpy, pandas, lifelines
print(sys.version_info[:2], numpy.__version__, pandas.__version__, lifelines.__version__)
# (3, 14) 2.4.4 2.3.3 0.30.3
Every output in this chapter comes from exactly these versions. The code avoids anything that behaves differently under copy on write, so it will keep working when lifelines catches up with pandas 3.
Generating Vanlog's subscription export
Real subscription data is a table of dates: when each account signed up, when it cancelled (or nothing, if it is still active), and what you knew about it early on. So the generator produces exactly that, a raw export, and the next section turns it into the analysis table. The covariates are measured early on purpose: seats at day 30, onboarding finished by day 14, support tickets in the first 30 days. A variable measured at cancellation would be the future predicting the past.
import numpy as np
import pandas as pd
rng = np.random.default_rng(18)
n = 2400
cutoff = pd.Timestamp("2026-03-31 23:59", tz="UTC") # the moment the export was taken
# Five years of signups, slightly more of them recently
days_back = (1826 * rng.random(n) ** 1.15).astype(int)
signed_up_at = cutoff.normalize() - pd.to_timedelta(days_back, unit="D")
plan = np.where(rng.random(n) < 0.45, "Team", "Starter")
team = plan == "Team"
seats_day30 = np.where(team, 2 + rng.poisson(0.9, n), 1 + rng.binomial(1, 0.25, n))
onboarded_day14 = rng.random(n) < np.where(team, 0.62, 0.50)
billing = np.where(rng.random(n) < np.where(team, 0.30, 0.18), "annual", "monthly")
channel = np.where(rng.random(n) < 0.40, "paid_search", "referral")
tickets_30d = rng.poisson(0.9, n)
Now the churn itself. The generator walks through 60 months. In each month, every account still active leaves with a probability that depends on a baseline (high early, a bump at each anniversary, the shape of the Marketing Analytics chapter's chart) and on the account's characteristics. The reference account is the riskiest profile, a one seat Starter account that never onboarded, so its baseline is about twice the Team average. Annual accounts get a twist that matters later: they rarely leave mid year, because they have paid, and they leave more often at the renewal.
# Monthly churn risk of the reference account: high early, a bump at each renewal
first_year = np.array([3.5, 4.8, 5.1, 4.2, 3.3, 2.6, 2.2, 2.0, 1.8, 1.7, 1.9, 3.0]) / 100
months = np.arange(1, 61)
later = np.where(months % 12 == 0, 0.022, 0.012)
baseline = 2.1 * np.where(months <= 12, np.resize(first_year, 60), later)
# The hazard ratios the generator builds in (the model should find them again)
log_hr = (np.log(0.71) * team + np.log(0.88) * (seats_day30 - 1)
+ np.log(0.55) * onboarded_day14 + np.log(1.24) * (channel == "paid_search")
+ np.log(1.09) * tickets_30d)
annual = billing == "annual"
churn_month = np.full(n, np.nan)
still_here = np.ones(n, dtype=bool)
for m in months:
# Annual accounts rarely leave mid year and more often at the renewal
annual_effect = np.where(annual, 2.0 if m % 12 == 0 else 0.5, 1.0)
h = 1 - (1 - baseline[m - 1]) ** (np.exp(log_hr) * annual_effect)
leaves = still_here & (rng.random(n) < h)
churn_month[leaves] = m - 1 + rng.random(leaves.sum()) # somewhere inside month m
still_here &= ~leaves
cancelled_at = signed_up_at + pd.to_timedelta(churn_month * 30.4375, unit="D")
cancelled_at = cancelled_at.where(cancelled_at <= cutoff).floor("s") # no future in the export
The line 1 - (1 - baseline) ** hr is how a hazard ratio applies to a monthly probability without ever pushing it above one, the same exact form the Marketing Analytics chapter uses for paid search accounts. And the where(cancelled_at <= cutoff) line is censoring in one line of code: a cancellation that would happen after the export simply is not in the export.
Finally the export itself, with the trap every real export has: internal test accounts that the team created and cancelled on the same day.
accounts = pd.DataFrame({
"account_id": np.arange(10001, 10001 + n),
"signed_up_at": signed_up_at,
"cancelled_at": cancelled_at,
"plan": plan,
"seats_day30": seats_day30,
"onboarded_day14": onboarded_day14,
"billing": billing,
"channel": channel,
"tickets_30d": tickets_30d,
"email_domain": "customer.example",
})
# Fifteen internal test accounts, created and cancelled on the same day
tests = accounts.sample(15, random_state=1).index
accounts.loc[tests, "email_domain"] = "vanlog.example"
accounts.loc[tests, "cancelled_at"] = accounts.loc[tests, "signed_up_at"] + pd.Timedelta(hours=2)
print(accounts.shape)
# (2400, 10)
Example: three rows of the export
The first three rows, as the export shows them:
| account_id | signed_up_at | cancelled_at | plan | seats_day30 | onboarded_day14 | billing | channel |
|---|---|---|---|---|---|---|---|
| 10001 | 2024 07 04 | (empty) | Team | 4 | True | annual | paid_search |
| 10002 | 2022 11 01 | 2023 06 28 02:06 | Team | 4 | True | monthly | paid_search |
| 10003 | 2025 02 01 | (empty) | Starter | 2 | True | monthly | referral |
Account 10002 churned after about eight months. Accounts 10001 and 10003 are still customers on 31 March 2026, so they are censored: you know they lasted at least until the cut off and nothing after it.
Building the three column table
Survival models want one row per account with a duration and an event flag. Durations come from subtracting two timestamps, which pandas does in one step and returns as a timedelta, a length of time.6 The conversion to months uses the average month length, 365.25 divided by 12, which is 30.4375 days. Calendar months would make a February signup look like it churned faster than a March one.
DAYS_PER_MONTH = 365.25 / 12 # 30.4375
df = accounts[accounts["email_domain"] != "vanlog.example"].copy()
end = df["cancelled_at"].fillna(cutoff) # still active: watched until the cut off
df["months"] = (end - df["signed_up_at"]).dt.total_seconds() / 86400 / DAYS_PER_MONTH
df["churned"] = df["cancelled_at"].notna().astype(int)
print(len(df), df["churned"].sum(), (df["churned"] == 0).sum())
# 2385 1147 1238
assert (df["months"] > 0).all()
Three lines carry the whole method. fillna(cutoff) gives every active account the cut off as its end, which is what censoring means in data. notna() turns "has a cancellation date" into the event flag. And the filter on email_domain removes the 15 test accounts before they can add 15 churners at a duration of two hours. Cleaning rules like this one belong in code, not in someone's memory, as cleaning data in pandas argues, and the date arithmetic is covered in time series in pandas.
The result: 2,385 real accounts, 1,147 churned and 1,238 censored. The theory chapter has 2,400 accounts with 1,060 churned, so the generated data churns a little more, and I keep that in mind when comparing numbers.
Example: two durations by hand
Account 10002 signed up on 1 November 2022 and cancelled on 28 June 2023 at 02:06. That is 239.09 days, and months, with churned = 1.
Account 10003 signed up on 1 February 2025 and is still active. Its end is the cut off, 31 March 2026 at 23:59, which is 424.0 days later, so months, with churned = 0. The model will use those 13.93 months as "survived at least this long" and nothing more.
The censoring check: does the cut off make sense?
Before any curve, one check that catches most broken tables. Group the accounts by signup year and look at the share still censored. Young cohorts have had less time to churn, so the censored share must rise as the cohorts get younger. If it does not, the cut off is wrong, or cancellation dates are missing for a part of the history, which happens after a move between billing systems.
df["cohort"] = df["signed_up_at"].dt.year
check = df.groupby("cohort").agg(
accounts=("churned", "size"),
churned=("churned", "sum"),
censored_share=("churned", lambda s: 1 - s.mean()),
)
print(check.round(2))
| cohort | accounts | churned | censored_share |
|---|---|---|---|
| 2021 | 320 | 206 | 0.36 |
| 2022 | 478 | 303 | 0.37 |
| 2023 | 449 | 259 | 0.42 |
| 2024 | 406 | 184 | 0.55 |
| 2025 | 556 | 183 | 0.67 |
| 2026 | 176 | 12 | 0.93 |
The share climbs from 0.36 to 0.93, as it should. The 2021 cohort starts in April, which is why it is smaller. The group by chapter explains named aggregation, the accounts=("churned", "size") pattern used here.
Example: why a plain churn rate says more about age than about quality
The plain churn rate, churned accounts divided by all accounts, is 55.0% for Starter and 40.4% for Team. By cohort it is 64% for 2021 () and 33% for 2025 (). A board reading those two numbers would conclude that the 2025 customers are twice as loyal. They are not. They are younger. The 2025 accounts have had at most 15 months to leave, the 2021 accounts up to five years.
A plain churn rate in a growing business falls every month just because the customer base gets younger, and it rises when growth slows, with no change in how well you keep anyone. That is the strongest reason to move to survival curves: they compare like with like, month of life against month of life.
Kaplan Meier curves in lifelines
The Kaplan Meier estimator draws the survival curve without assuming any shape for it, and handles censoring correctly.7 It multiplies, month by month, the share of accounts that survived among those still at risk:
Here is the estimated share of accounts still active after months, the product runs over every time at which at least one account churned, up to , is the number of accounts that churned at , and is the number still at risk just before it, meaning active and not yet censored. A censored account counts in for as long as it was watched, then leaves the risk set without counting as a churn. Foundations: probability
Example: five accounts, by hand and in lifelines
The theory chapter works through five accounts on 30 June: two that churned after two months, three still active after three months. By hand, , and . lifelines agrees:
from lifelines import KaplanMeierFitter
tiny = KaplanMeierFitter().fit([2, 2, 3, 3, 3], event_observed=[1, 1, 0, 0, 0])
print(tiny.survival_function_)
# KM_estimate
# timeline
# 0.0 1.0
# 2.0 0.6
# 3.0 0.6
Testing a library against a case you can do on paper is a habit worth keeping. It takes a minute and it catches the day you pass the arguments in the wrong order.
Now the real thing, one curve per plan:
curves = {}
for name, grp in df.groupby("plan"):
kmf = KaplanMeierFitter().fit(grp["months"], event_observed=grp["churned"], label=name)
curves[name] = kmf
print(name, kmf.survival_function_at_times([2, 12, 24]).round(3).tolist(),
"median", round(kmf.median_survival_time_, 1))
# Starter [0.867, 0.539, 0.411] median 16.1
# Team [0.919, 0.702, 0.606] median 38.2
After 12 months 70.2% of Team accounts are still active against 53.9% of Starter accounts. After 24 months it is 60.6% against 41.1%. The theory chapter's figures are 69% and 54%, then 59% and 42%, so the generated data lands within two points everywhere. The median lifetime, the month at which the curve crosses one half, is 38.2 months for Team and 16.1 for Starter.
Example: a chart a board can read
lifelines draws the curves with matplotlib, including the confidence band. The one addition I always make is the table of accounts still at risk under the chart, because a curve that rests on 40 accounts at month 48 should not look as solid as one that rests on 1,100 at month one. The function that prints it, add_at_risk_counts, was fixed for NumPy 2.4 in lifelines 0.30.1, so this needs the pinned version.8
import matplotlib.pyplot as plt
from lifelines.plotting import add_at_risk_counts
fig, ax = plt.subplots(figsize=(8, 5))
for name in ["Team", "Starter"]:
curves[name].plot_survival_function(ax=ax, ci_show=True)
ax.set_xlim(0, 24)
ax.set_ylim(0, 1)
ax.set_xlabel("Months since signup")
ax.set_ylabel("Share of accounts still active")
ax.set_title("After a year, 70% of Team accounts are still here, 54% of Starter", loc="left")
add_at_risk_counts(curves["Team"], curves["Starter"], ax=ax, xticks=[0, 6, 12, 18, 24])
fig.tight_layout()
Under the chart, the table shows 1,124 Team accounts at risk at month zero and 405 at month 24, and 1,261 Starter accounts falling to 289. The title states the finding instead of naming the chart, the rule from words on charts, and the general matplotlib craft is in charts in Python. The confidence band around Team at month 12 runs from 67.2% to 72.9%, which you can read from curves["Team"].confidence_interval_survival_function_. Foundations: confidence intervals
Example: are the two curves really different?
The log rank test asks whether two survival curves differ by more than chance would explain, comparing the churns each group had with the churns it would have had if both shared one curve.9
from lifelines.statistics import logrank_test
team_df, starter_df = df[df["plan"] == "Team"], df[df["plan"] == "Starter"]
result = logrank_test(team_df["months"], starter_df["months"],
event_observed_A=team_df["churned"],
event_observed_B=starter_df["churned"])
print(round(result.test_statistic, 1), result.p_value < 0.001)
# 78.0 True
A test statistic of 78.0 on one degree of freedom, with a p value far below 0.001. The plans differ. What the test cannot say is why: whether it is the plan, or the seats and onboarding that come with it. That is the Cox model's job.
The monthly hazard: when to act
The survival curve says how many are left. The hazard says where the risk lives, and that is the curve for deciding when to intervene. With monthly data it is a plain rate:
Here is the hazard in month , is the number of accounts that churned during that month, and is the number still active at its start. Churns over the accounts that could have churned. Foundations: ratios and rates
def monthly_hazard(grp, last_month=12):
rows = []
for m in range(1, last_month + 1):
at_risk = (grp["months"] >= m - 1).sum()
left = ((grp["months"] >= m - 1) & (grp["months"] < m) & (grp["churned"] == 1)).sum()
rows.append({"month": m, "at_risk": at_risk, "churned": left, "hazard": left / at_risk})
return pd.DataFrame(rows).set_index("month")
print(monthly_hazard(team_df).round(3))
| Month | At risk | Churned | Hazard |
|---|---|---|---|
| 1 | 1,124 | 51 | 4.5% |
| 2 | 1,049 | 38 | 3.6% |
| 3 | 987 | 41 | 4.2% |
| 4 | 926 | 41 | 4.4% |
| 5 | 867 | 22 | 2.5% |
| 6 | 820 | 27 | 3.3% |
| 7 | 769 | 20 | 2.6% |
| 8 | 736 | 12 | 1.6% |
| 9 | 710 | 7 | 1.0% |
| 10 | 689 | 11 | 1.6% |
| 11 | 668 | 10 | 1.5% |
| 12 | 640 | 23 | 3.6% |
Example: reading the Team hazard
Month one: 51 of 1,124 Team accounts churn, . The first four months all sit around 4%, the risk then halves by month eight and drops to about 1.5%, and month 12 jumps back to 3.6%, the annual renewal. That is the shape from the theory chapter (3.5%, 4.8%, 5.1% and so on, with a renewal bump at 3.0%), with the noise you get from 1,100 accounts rather than a smooth textbook curve. Seven churns in month nine and 11 in month ten are not a trend, they are small numbers.
The decision this table supports does not need precision: the risk lives in months one to four and at the renewal. Retention effort belongs in weeks two to eight and in month 10 or 11, not spread evenly across the year.
The Cox model in lifelines
Kaplan Meier gives one curve per group, but it cannot separate causes that travel together. Team accounts have more seats and onboard more often. Is the plan itself worth anything? The Cox proportional hazards model answers that by regressing the hazard on several characteristics at once:10
Here is the hazard at month for an account with characteristics to , is the baseline hazard of a reference account with every at zero, whose shape the model never needs to know, and to are the coefficients the model estimates. Each hazard ratio multiplies the risk at every point in time: 0.56 means 56% of the reference risk, a 44% lower hazard. Foundations: ratios and rates
The columns need a little care first. lifelines wants numbers, so the categories become 0 and 1 flags, and seats become "extra seats beyond the first" so that zero means a one seat account and the reference is a real account that exists.
from lifelines import CoxPHFitter
X = pd.DataFrame({
"months": df["months"],
"churned": df["churned"],
"onboarded": df["onboarded_day14"].astype(int),
"seats": df["seats_day30"] - 1, # extra seats beyond the first
"team": (df["plan"] == "Team").astype(int),
"annual": (df["billing"] == "annual").astype(int),
"paid_search": (df["channel"] == "paid_search").astype(int),
"tickets_30d": df["tickets_30d"],
})
cph = CoxPHFitter()
cph.fit(X, duration_col="months", event_col="churned")
print(cph.summary[["coef", "exp(coef)", "exp(coef) lower 95%", "exp(coef) upper 95%", "p"]].round(2))
print(round(cph.concordance_index_, 2))
# 0.63
cph.print_summary() prints the same with standard errors and z values. Side by side with the theory chapter and with what the generator built in:
| Variable | Theory chapter | Fitted here | 95% interval | Built into the generator |
|---|---|---|---|---|
| Onboarded by day 14 | 0.55 | 0.56 | 0.50 to 0.63 | 0.55 |
| Per extra seat | 0.88 | 0.89 | 0.82 to 0.97 | 0.88 |
| Team versus Starter | 0.71 | 0.75 | 0.63 to 0.91 | 0.71 |
| Annual versus monthly billing | 0.62 | 0.64 | 0.55 to 0.74 | not one number |
| Paid search versus referral | 1.24 | 1.22 | 1.09 to 1.38 | 1.24 |
| Per support ticket, first 30 days | 1.09 | 1.09 | 1.03 to 1.16 | 1.09 |
The model finds what was built in, within its intervals, every time. That is the point of generating data with known answers: before you trust a method on your own data, you have watched it recover the truth on data where you know the truth. The annual row is the odd one out, and the next section shows why.
The concordance index is 0.63: for a random pair of accounts, the model ranks correctly which one lasts longer 63% of the time. The theory chapter reports 0.71 for its data. The lifelines documentation notes that fitted survival models typically land between 0.55 and 0.75, and that even a perfect model cannot score much higher, because churn has a lot of plain chance in it.11 I am suspicious of anything above 0.85: it usually means a column is leaking the outcome, such as logins in the last month.
Example: two accounts compared
The effects multiply. Take a Team account on annual billing that onboarded and has four seats (three extra), and compare it with a one seat monthly Starter account that never onboarded, both from referral with one support ticket:
- Plan: 0.75.
- Annual billing: 0.64.
- Onboarding: 0.56.
- Three extra seats: .
- Together: .
The first account carries about a fifth of the second one's churn risk in any month. The theory chapter gets a sixth with its rounder numbers. Same conclusion: nobody needs to phone the first account in month two.
Checking proportional hazards, and fixing what fails
The Cox model assumes each hazard ratio is the same in month two as in month 20. That is an assumption, not a fact, and lifelines tests it with scaled Schoenfeld residuals, the method of Grambsch and Therneau.12 In plain words, the test asks whether a variable's effect drifts with time.
from lifelines.statistics import proportional_hazard_test
ph = proportional_hazard_test(cph, X, time_transform="rank")
print(ph.summary[["test_statistic", "p"]].round(3))
| Variable | Test statistic | p |
|---|---|---|
| annual | 5.348 | 0.021 |
| onboarded | 0.776 | 0.378 |
| paid_search | 0.001 | 0.982 |
| seats | 2.399 | 0.121 |
| team | 0.630 | 0.427 |
| tickets_30d | 0.003 | 0.956 |
The friendlier version is cph.check_assumptions(X, p_value_threshold=0.05), which runs the test with two time transforms and prints advice. Here it flags exactly one variable, with the message Variable 'annual' failed the non-proportional test, and suggests stratifying on it, with a link to the lifelines guide.13 It also warns, fairly, that with many observations even small deviations get flagged, so the test is a prompt to look, not a verdict.
Example: what the annual accounts are really doing
So look. Split the monthly hazard by billing, using the monthly_hazard function from before:
by_billing = pd.concat(
{b: monthly_hazard(df[df["billing"] == b], 14)["hazard"] for b in ["monthly", "annual"]},
axis=1,
)
print((100 * by_billing).round(1).T)
In months one to eleven, annual accounts churn at roughly half the monthly rate. In month 12 they churn at 6.5% against 4.9%, more than monthly accounts, because the renewal is the one moment they can leave. Then they go almost silent again at 0.3%. A single hazard ratio of 0.64 averages a strong protection with a renewal cliff, and that average is right in no month at all. This is exactly the pitfall the theory chapter describes, and here you can see it in the data.
The fix the checker suggests is stratification: give annual and monthly accounts their own baseline hazard, and estimate the other effects across both.
cph_s = CoxPHFitter()
cph_s.fit(X, duration_col="months", event_col="churned", strata=["annual"])
print(cph_s.summary[["exp(coef)", "exp(coef) lower 95%", "exp(coef) upper 95%"]].round(2))
| Variable | Hazard ratio | 95% interval |
|---|---|---|
| onboarded | 0.56 | 0.50 to 0.63 |
| seats | 0.89 | 0.82 to 0.97 |
| team | 0.75 | 0.63 to 0.91 |
| paid_search | 1.23 | 1.09 to 1.38 |
| tickets_30d | 1.09 | 1.03 to 1.16 |
The other hazard ratios barely move, which is reassuring: they did not depend on how annual billing was modelled. Annual billing no longer has a hazard ratio at all. Its effect now lives in the shape of its own baseline curve, renewal cliff included, and that is what the lifetime value needs. Rerun proportional_hazard_test on cph_s and no variable falls below 0.05.
The concordance drops from 0.63 to 0.61, because annual billing no longer helps rank accounts against each other across the two strata. I accept that. The stratified model describes when annual accounts leave correctly, and timing is what the money depends on. Chasing a concordance figure at the cost of a correct curve is a poor trade.
From survival to lifetime value
Now the money. Predictive lifetime value adds up, month by month, the margin you earn if the customer is still there, weighted by the probability that they are, and discounted back to today:
Here is the predicted lifetime value of one new customer, runs over future months from 1 to the horizon , is the margin in month , is the probability the customer is still active, and discounts month at the monthly rate . Margin times survival is the expected margin of that month. Foundations: expected value
In code that is one line inside a function. I keep it separate from the model, because it should work the same whether the survival comes from a Kaplan Meier curve, a Cox prediction or a hazard table someone hands you.
def lifetime_value(survival, margin, monthly_rate=0.01):
"""Discounted margin over the months in `survival` (S(1), S(2), and so on)."""
t = np.arange(1, len(survival) + 1)
return float(np.sum(margin * np.asarray(survival) / (1 + monthly_rate) ** t))
Example: reproducing the theory chapter's £1,903
The theory chapter's worked example uses the Team hazards for the first year (3.5%, 4.8%, 5.1% and so on), then 1.2% a month with 2.2% at each anniversary, a margin of £71 a month, 1% a month as the discount rate (about 12.7% a year, because ) and a horizon of 60 months. Survival is the running product of one minus the hazard, which NumPy's cumprod does in one step:
first_year = np.array([3.5, 4.8, 5.1, 4.2, 3.3, 2.6, 2.2, 2.0, 1.8, 1.7, 1.9, 3.0]) / 100
months = np.arange(1, 61)
hazard = np.where(months <= 12, np.resize(first_year, 60),
np.where(months % 12 == 0, 0.022, 0.012))
survival = np.cumprod(1 - hazard)
print(survival[[0, 2, 11, 59]].round(3)) # [0.965 0.872 0.693 0.372]
print(round(lifetime_value(survival, 71), 2)) # 1903.02
Month one by hand: . Add up all 60 months and you get £1,903.02, exactly the theory chapter's figure. Two more of its numbers come out the same way. A paid search Team account, with every month's hazard raised by the hazard ratio of 1.24 in the exact form, is worth £1,696:
paid_survival = np.cumprod((1 - hazard) ** 1.24)
print(round(lifetime_value(paid_survival, 71), 2)) # 1696.14
And a Starter account from paid search, with a margin of £23 and the hazard raised by , is worth £436:
starter_paid = np.cumprod((1 - hazard) ** (1.24 / 0.71))
print(round(lifetime_value(starter_paid, 23), 2)) # 435.87
The (1 - hazard) ** hr form is the same as inside the product, and it keeps every monthly probability between zero and one however large the ratio.
Lifetime value per segment, straight from the model
The hand calculation applies one ratio to one hazard table. The model can do better: it predicts a full survival curve for any profile you describe, with its own baseline for annual and monthly billing. Describe the segments the bidding actually uses, predict, and feed the curves into the same function.
profiles = pd.DataFrame({
"onboarded": [1, 1, 0, 0],
"seats": [2, 2, 0, 0],
"team": [1, 1, 0, 0],
"annual": [0, 0, 0, 0],
"paid_search": [0, 1, 0, 1],
"tickets_30d": [1, 1, 1, 1],
}, index=["Team, referral", "Team, paid search", "Starter, referral", "Starter, paid search"])
margin = pd.Series([71, 71, 23, 23], index=profiles.index)
surv = cph_s.predict_survival_function(profiles, times=months) # rows are months 1 to 60
ltv = pd.Series({p: lifetime_value(surv[p].to_numpy(), margin[p]) for p in profiles.index})
print(pd.DataFrame({"S(12)": surv.loc[12].round(2), "S(60)": surv.loc[60].round(2),
"LTV": ltv.round(0), "max CPA": (ltv / 3).round(0)}))
| Segment | S(12) | S(60) | Lifetime value | Bid limit, a third |
|---|---|---|---|---|
| Team, referral (onboarded, 3 seats) | 0.75 | 0.50 | £2,136 | £712 |
| Team, paid search (onboarded, 3 seats) | 0.71 | 0.43 | £1,960 | £653 |
| Starter, referral (not onboarded, 1 seat) | 0.43 | 0.13 | £347 | £116 |
| Starter, paid search (not onboarded, 1 seat) | 0.35 | 0.08 | £282 | £94 |
Example: what this does to the bid
The founder bid on Google Ads to one cost per acquisition target of £250 for everything. Against these numbers, £250 is nearly everything a paid search Starter account will ever earn: the whole discounted five year value of such an account is £282, so a £250 acquisition cost leaves £32 of margin. For a paid search Team account the same £250 is far below what the account can carry. With the founder's rule of paying at most a third of lifetime value, the paid search bid limits become £653 for Team and £94 for Starter.
These profiles are specific accounts, so their values differ from the theory chapter's averages: an onboarded three seat Team account is worth more than the average Team account, and a Starter account that never onboarded is worth less than the average Starter account. That is the point. The bidding should use the segments it can target, and a Cox model gives you a value for each of them.
Expected lifetime: the area under the curve
Sometimes the question is simpler: how many months does a new account stay, on average? With censoring you cannot average the durations, because the active accounts' durations are not finished. The answer is the area under the survival curve up to a horizon, the restricted mean survival time:14
Here is the expected number of months an account stays within the first months, is the survival curve and the integral adds up the area beneath it from zero to . Undiscounted lifetime margin is that number times the monthly margin. Foundations: mean
from lifelines.utils import restricted_mean_survival_time
for name, kmf in curves.items():
print(name, round(restricted_mean_survival_time(kmf, t=60), 1))
# Starter 25.3
# Team 35.4
# Discounted value of an average Team account, straight from its curve
team_curve = curves["Team"].survival_function_at_times(months).to_numpy()
print(round(lifetime_value(team_curve, 71)))
# 1943
Example: from expected months to a sanity check
Within the first five years, a new Team account stays 35.4 months on average and a Starter account 25.3. Times £71, a Team account's undiscounted five year margin is about . The discounted value of an average Team account, from its Kaplan Meier curve and the same lifetime_value function, is £1,943, close to the theory chapter's £1,903 and lower than £2,513, because a pound in month 48 is worth less than a pound today. If your discounted figure ever comes out above the undiscounted one, something in the code is wrong. It is a one line check, and I run it every time.
Scoring the accounts you still have
The last step turns the model into a list someone can act on. For the 1,238 active accounts, the useful question is not the survival of a new account but: given that this account has already lasted this long, how likely is it to still be here in 12 months? lifelines answers that with conditional_after, which starts each account's curve at the point it has already reached.15
active = X[X["churned"] == 0]
cond = cph_s.predict_survival_function(
active.drop(columns=["months", "churned"]),
times=[12],
conditional_after=active["months"],
)
scores = pd.DataFrame({
"account_id": df.loc[active.index, "account_id"],
"months_so_far": active["months"].round(1),
"p_still_here_in_12_months": cond.loc[12].round(2),
})
print(scores.sort_values("p_still_here_in_12_months").head(3))
print((scores["p_still_here_in_12_months"] < 0.6).sum())
# 66
Example: the list for Monday morning
The lowest scores are all young accounts: account 11616, 1.2 months in, has a 32% chance of still being a customer in a year, and the next ones sit at 36%. Of the 1,238 active accounts, 66 are below 60%. That is a list a person can phone this week, which is better than a drip campaign to everyone. The scores say whom and when. They do not say that phoning works: only a test, with half the list phoned and half not, can show that, and that is the job of the A/B testing chapter later in this series.
A note on data protection, as general information and not legal advice. A scored list of customers is personal data about the people behind those accounts, and many of Vanlog's customers are sole traders. Under the UK GDPR, keep only the columns the purpose needs (Article 5(1)(c), data minimisation) and build the pipeline so that it works on pseudonymous account numbers, with names joined in only for the people who will make the calls (Article 25, data protection by design).16 The Information Commissioner's Office (ICO) publishes guidance on both.17
Traps from real exports that tutorials skip
Generated data is clean by design. Real subscription exports are not, and these are the traps that change the answer. Each has a check that takes a line or two of pandas.
| Trap | What it does to the model | The check |
|---|---|---|
| Trials counted as customers | Month one hazard explodes, every ratio explains trial conversion | Start the clock at the first payment |
| Failed payments mixed with cancellations | The model tries to explain card expiry with onboarding | Separate event flag for involuntary churn |
| Reactivated accounts | One account becomes two spells, or one long false survival | Decide: new spell per reactivation, and count them |
| Move between billing systems | A spike of cancellations and signups on one date | Count events per day, look for one huge day |
| Covariates measured late | Logins last month predict churn perfectly, and uselessly | Measure every covariate at a fixed early day |
| A moving cut off | Numbers drift with every rerun | One fixed timestamp in UTC, stored with the data |
| Timestamps in UTC near midnight | Cancellations shift between months at month end | Convert to the business's time zone before grouping by month |
| Test and staff accounts | Dozens of zero day churners | Filter by email domain or a flag, in code |
Two of these deserve a sentence more. Involuntary churn is a separate event, and if you want both in one analysis, lifelines has an AalenJohansenFitter for competing risks, where each account can leave by one of several routes. And in a shop where nobody cancels, there is no end date at all, only silence. That is non contractual churn, a different problem with different models, and the theory chapter's section on it is the place to start.
My view
My view: draw the Kaplan Meier curves first, every time, and show them to the founder before any model. Most of the decisions (when to act, which plan bleeds, how far the plain churn rate misleads) are in the curves and the monthly hazard already. The Cox model earns its place when causes travel together and you need to separate them, and only together with the proportional hazards check. A table of hazard ratios without that check is a table I would not sign.
Lifetime value should always be a set of numbers per segment, never one figure for the company, and the discount rate and the horizon belong next to it in writing. One average lifetime value used for bidding overpays for the weak segment and underpays for the strong one, and the paid search Starter row above shows by how much.
And generate data with known answers before you trust a method on your own data. Watching lifelines find 0.56 where the generator put 0.55 is what lets you believe it on the day there is no answer key.
If you would rather have this built on your own subscription data than build it yourself, it is part of my Data Science work, and when the lifetime values go into bidding, I run the campaign side as well. It starts with the free workshop, and the first two weeks of work are on me. You own the code, the accounts and the data, and my prices are published on the transparency page.
Conclusion
Survival analysis in Python is a small amount of code on top of a carefully built table. Decide when the clock starts and what stops it, fix the cut off, and check that the censored share rises for young cohorts. Then lifelines gives you Kaplan Meier curves and monthly hazards for timing, a Cox model for the drivers, a test that tells you when one of those drivers behaves differently over time, and survival curves per segment that turn into a discounted lifetime value in one function.
On the generated Vanlog data, the method recovers what was built in: Team accounts at 70% after a year against 54% for Starter, onboarding at a hazard ratio of 0.56, paid search at 1.22, and annual billing flagged by the check and handled by stratification. The theory chapter's lifetime value of £1,903 reproduces to the penny, and the model's per segment values show a paid search Starter account worth £282, which no flat £250 bid target survives. In the next chapter of this series, panel regression in Python, the data becomes many units observed over many periods at once.
