🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Survival Analysis — Time-to-Event Data

Foundations of StatisticsAdvanced Topics🟢 Free Lesson

Survival Analysis

Foundations of Statistics

Analyzing Time-to-Event Data With Censoring

Survival analysis handles the unique challenge of censored observations — subjects who haven't experienced the event by study end. From Kaplan-Meier curves to Cox models, these methods extract maximum information from incomplete time-to-event data.

  • Clinical Trials — Estimate patient survival probabilities with censored follow-up
  • Reliability Engineering — Predict time-to-failure for mechanical components
  • Customer Analytics — Model time until churn with subscription cancellations

The event will happen — survival analysis tells us when, even when we don't wait long enough to see it.


What You'll Learn

  • 1Explain why censoring makes means and logistic regression the wrong tools for time-to-event data
  • 2Compute a Kaplan-Meier curve by hand from a table of event and censoring times
  • 3Fit a Cox model and interpret a hazard ratio as a multiplicative change in instantaneous risk
  • 4Choose between Kaplan-Meier, log-rank, Cox, and restricted mean survival for a given question

Survival analysis analyzes time until an event occurs (death, failure, relapse). It handles censored data — subjects who haven't experienced the event by the study end.

Key functions:

  • — survival function (probability of surviving past time t)
  • — hazard rate (instantaneous risk at time t)
  • — cumulative hazard

Why Censoring Breaks Ordinary Analysis

A patient still alive at the end of a trial has not failed — but their exact survival time is unknown; you only know it exceeds the follow-up period. Deleting such patients biases the estimate downward, since the ones who leave early are systematically the healthier ones. Coding them as survivors until the study ends and then computing a plain average treats an observation of "at least 24 months" as exactly 24 months, which also distorts the result. Logistic regression sidesteps the timing entirely and answers "did it happen by a fixed date", discarding when it happened and handling subjects followed for different lengths of time only awkwardly.

Censoring comes in several forms and the distinction matters. Right censoring is the common case: the event time lies somewhere beyond the observation window. Left censoring means the event was already present when observation began, such as a diagnosis made at the first visit. Interval censoring means the event is known to have occurred between two visits but the exact moment is unknown. The standard estimators handle right censoring directly; the others need dedicated methods, so identifying the type is the first step of any analysis.

The whole apparatus rests on one assumption: censoring must be non-informative, meaning a subject's chance of being censored cannot depend on their underlying risk given what you have modelled. If the sickest patients drop out because they are too unwell to attend, that assumption fails and every estimate is optimistic. If the study simply closed on a fixed date, censoring is independent by construction.

The Relationship Between the Three Functions

The hazard is the instantaneous event rate among those still at risk,

and it converts to the survival function through the cumulative hazard and . A constant hazard gives exponential survival with a memoryless property; an increasing hazard describes wear-out and ageing; a decreasing hazard describes the early-risk period of a surgery or a new customer onboarding. Reading the shape of therefore tells you which parametric family, if any, is plausible — Weibull for monotone hazards, log-normal for hazards that rise and then fall.

The Kaplan-Meier Estimator

Between consecutive event times the survival curve is a step function. At each distinct event time with events out of subjects still at risk,

Censored subjects leave the risk set at their censoring time without contributing a factor, so the curve never jumps at a censoring — it simply stops falling as steeply because fewer people remain.

Because the curve is a product of many small factors, its confidence intervals are asymmetric and are computed on the log-log scale to stay inside the unit interval. Software does this automatically; hand calculations on the raw scale are only trustworthy when the sample is large.

Comparing Curves: The Log-Rank Test

The log-rank test asks whether one group experiences more events than expected if both groups shared a single hazard. At every event time it pools the risk sets, computes the expected number of events in each group, and accumulates the observed-minus-expected differences. The squared total, suitably standardised, follows a chi-square distribution with one degree of freedom for a two-group comparison.

Its efficiency peaks exactly when hazards are proportional, and it loses power when curves cross — a treatment that helps early and harms late can produce a log-rank p-value near one despite a large and real difference. In that situation, pre-specify a restricted mean survival time comparison or a weighted log-rank variant rather than reaching for it after seeing the plot.

The Cox Proportional Hazards Model

Cox regression separates the baseline hazard, which is never specified, from the covariate effect:

Estimation uses the partial likelihood, which at each event time compares the covariate profile of the subject who failed against everyone still at risk:

The baseline hazard cancels from that ratio, which is why no distributional assumption about is needed. Exponentiating a coefficient gives the hazard ratio: a value of 0.65 means the treated group's instantaneous event rate is 35 percent lower at every moment, holding the other covariates fixed. Because the hazard ratio is a ratio of rates rather than of times, a hazard ratio of 0.5 does not mean patients live twice as long.

A Full Worked Pipeline

python
import numpy as np
import pandas as pd
from lifelines import KaplanMeierFitter, CoxPHFitter
from lifelines.statistics import logrank_test
import matplotlib.pyplot as plt

np.random.seed(42)
n = 200

# Simulate clinical trial: two treatment groups
# Group A (control): exponential survival, median = 12 months
# Group B (treatment): longer survival, median = 20 months
group = np.random.choice([0, 1], n)
true_median = np.where(group == 0, 12, 20)
duration = np.random.exponential(true_median/np.log(2))
censored_at = 24  # study ends at 24 months
observed = duration <= censored_at
duration_obs = np.minimum(duration, censored_at)

df = pd.DataFrame({
    'duration': duration_obs,
    'event': observed.astype(int),
    'group': np.where(group==0, 'Control', 'Treatment'),
    'age': np.random.uniform(40, 70, n),
    'stage': np.random.choice([1,2,3], n, p=[0.3,0.5,0.2])
})

# Kaplan-Meier estimator
fig, axes = plt.subplots(1, 2, figsize=(14, 5))

kmf = KaplanMeierFitter()
for grp, color in [('Control','red'), ('Treatment','blue')]:
    mask = df['group'] == grp
    kmf.fit(df[mask]['duration'], df[mask]['event'], label=grp)
    kmf.plot_survival_function(ax=axes[0], color=color)

axes[0].set_title('Kaplan-Meier Survival Curves')
axes[0].set_xlabel('Time (months)')
axes[0].set_ylabel('Survival Probability')

# Log-rank test
ctrl = df[df['group']=='Control']
trt  = df[df['group']=='Treatment']
result = logrank_test(ctrl['duration'], trt['duration'],
                       ctrl['event'], trt['event'])
axes[0].text(0.05, 0.1, f'Log-rank p = {result.p_value:.4f}',
             transform=axes[0].transAxes)

# Cox proportional hazards model
cph = CoxPHFitter()
cph.fit(df[['duration','event','group','age','stage']],
        duration_col='duration', event_col='event')
cph.print_summary()
cph.plot(ax=axes[1])
axes[1].set_title('Cox Model: Hazard Ratios')

plt.tight_layout()
plt.savefig('survival_analysis.png', dpi=150)
plt.show()

# Median survival times
for grp in ['Control','Treatment']:
    mask = df['group'] == grp
    kmf.fit(df[mask]['duration'], df[mask]['event'])
    median = kmf.median_survival_time_
    print(f"{grp}: median survival = {median:.1f} months")

Checking Proportional Hazards and Fallbacks

The Cox model's central claim is that every covariate multiplies the hazard by a constant over the whole follow-up period. The standard check regresses scaled Schoenfeld residuals against time: a non-zero slope means the effect drifts, and the associated test returns a p-value for that trend. Plotting the residuals against time with a smooth is more informative than the p-value alone, because with large samples the test flags drift too small to matter.

python
from lifelines.statistics import proportional_hazard_test
from lifelines import CoxPHFitter
import pandas as pd
import numpy as np

np.random.seed(0)
n = 400
treatment = np.random.binomial(1, 0.5, n)
# Effect that fades: hazard ratio starts near 0.4 and drifts to 1
time_effect = np.linspace(0, 1, n)
log_hazard = np.log(0.4) * (1 - time_effect) + np.log(1.0) * time_effect
true_time = np.random.exponential(np.exp(-log_hazard))
event = (true_time <= 24).astype(int)
frame = pd.DataFrame({
    'duration': np.minimum(true_time, 24),
    'event': event,
    'treatment': treatment,
})

cph = CoxPHFitter().fit(frame, duration_col='duration', event_col='event')
ph_test = proportional_hazard_test(cph, frame, time_transform='rank')
print(ph_test.summary)

# Fallback when hazards are not proportional: restricted mean survival
km = KaplanMeierFitter().fit(frame['duration'], frame['event'])
print("RMST to 24 months:", round(km.restricted_mean_survival_time_(24), 2))

When the test rejects, the honest response is to change the estimand rather than to keep adjusting. Restricted mean survival time — the area under the Kaplan-Meier curve up to a chosen horizon — averages the treatment effect over the whole period without assuming proportionality, and it has a direct interpretation as "expected months event-free within two years".

Choosing the Right Tool

QuestionMethodKey assumption
What does survival look like over time?Kaplan-MeierCensoring is independent of risk
Do two groups differ, unadjusted?Log-rank testProportional hazards for maximum power
Which covariates matter, adjusted?Cox proportional hazardsHazard ratios are constant over time
What is the absolute expected event-free time?Restricted mean survivalNone beyond independent censoring
Do hazards cross or drift?Weighted log-rank, time-varying coefficientsModelled drift form
Do you need extrapolation past the study?Weibull or log-normal AFTParametric distributional form

Common Mistakes

Deleting censored subjects or treating their time as the event time

Fix: Keep them with event = 0. The estimator uses their follow-up to build the risk set, which is exactly the information censoring preserves.

Reading a hazard ratio of 0.5 as doubling survival time

Fix: The hazard ratio scales the instantaneous rate, not the duration. Translate it into a survival curve or a restricted mean difference before making a claim about time gained.

Fitting a Cox model and never checking proportional hazards

Fix: Run a Schoenfeld residual test with a plot. If it rejects, move to restricted mean survival or time-varying coefficients instead of reporting a single summary ratio.

Best Practices

  • Plot Kaplan-Meier curves with numbers at risk before fitting any model
  • Report median survival with its confidence interval and the hazard ratio with its interval together
  • Pre-specify the horizon for restricted mean survival when curves may cross

Key Takeaways

  • Censored observations contribute their time at risk and are not missing data; dropping them biases survival upward
  • Kaplan-Meier multiplies the factors (1 − d/n) at each event time, and the median is where the curve first reaches 0.5
  • Cox regression estimates hazard ratios from a partial likelihood that cancels the baseline hazard entirely
  • Proportional hazards is a testable claim — verify it, and fall back to restricted mean survival when it fails

Frequently Asked Questions

What does the hazard function mean intuitively?

It is the instantaneous rate of the event among everyone still event-free at time , comparable to a speedometer reading rather than a distance. A hazard that rises with age describes wear-out; a constant hazard describes a memoryless process such as radioactive decay; a falling hazard describes the elevated early risk after surgery or enrolment.

Is censoring the same as missing data?

No. A censored subject contributes their full observed time to the risk set, and the estimator uses it. Missing data provides no information at all. Treating censored times as missing discards usable follow-up; treating them as events invents failures that never occurred.

Can survival analysis handle repeated events?

The standard models assume one event per subject. For recurrent events use a Andersen-Gill or Prentice-Williams-Peterson extension, a frailty model that adds a subject-level random effect, or a marginal rate model with robust standard errors clustered on the subject.

Interview Questions

Q1: What is censoring and why does it not bias the Kaplan-Meier estimate?

Censoring means the event time is known only to lie beyond the observation window. Kaplan-Meier handles it by removing censored subjects from the risk set at their censoring time without applying a factor, which is valid whenever censoring is independent of the event risk.

Q2: How do you interpret a hazard ratio of 0.7?

At any given moment, the treated group's instantaneous event rate is 70 percent of the control group's, holding covariates fixed. It is not a statement that survival time is 1/0.7 times longer.

Q3: How do you test the proportional hazards assumption?

Regress scaled Schoenfeld residuals on time (rank-transformed) and test the slope, as cox.zph or lifelines' proportional_hazard_test does, and inspect the residual plot. Rejection means the hazard ratio is not constant and a single summary is misleading.

Q4: What do you report when hazards are clearly non-proportional?

Restricted mean survival time difference at a pre-specified horizon, along with the Kaplan-Meier curves and numbers at risk. It has a direct interpretation in units of time and needs no proportionality assumption.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Statistics Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement