lifelines
lifelines is a comprehensive Python library for survival analysis, offering implementations of various models including Kaplan-Meier, Nelson-Aalen, and Cox proportional hazards regression. It is actively maintained with regular releases, providing tools for handling right, left, and interval censored data, and includes internal plotting methods for easy visualization. The current version is 0.30.3.
Warnings
- breaking The `sklean_adaptor` module was removed in version 0.28.0. There is no direct replacement, simplifying the library's API.
- breaking Minimum Python version requirements have increased. Version 0.28.0 dropped support for Python < 3.9, and version 0.30.3 requires Python >= 3.11.
- deprecated The `initial_beta` parameter in `CoxPHFitter.fit()` was renamed to `initial_point` to align with a more general concept across models.
- deprecated The `plot_covariate_groups` method was renamed to `plot_partial_effects_on_outcome` and its behavior for transformed variables changed with the introduction of R-like formulas.
- gotcha When using `CoxPHFitter`, avoid including a column of all 1s (an explicit intercept) in your DataFrame or formula. The Cox model implicitly handles a baseline, and an explicit intercept can lead to warnings or convergence errors.
Install
-
pip install lifelines
Imports
- KaplanMeierFitter
from lifelines import KaplanMeierFitter
- CoxPHFitter
from lifelines import CoxPHFitter
- WeibullFitter
from lifelines import WeibullFitter
- NelsonAalenFitter
from lifelines import NelsonAalenFitter
Quickstart
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from lifelines import KaplanMeierFitter, CoxPHFitter
# --- Kaplan-Meier Fitter Example ---
np.random.seed(42)
num_samples = 100
T = np.random.exponential(scale=10, size=num_samples) # Durations
E = np.random.binomial(n=1, p=0.7, size=num_samples) # Events (0=censored, 1=event)
kmf = KaplanMeierFitter()
kmf.fit(T, event_observed=E, label="Sample Survival Function")
print("Kaplan-Meier Survival Function (first 5 rows):\n", kmf.survival_function_.head())
kmf.plot_survival_function()
plt.title("Kaplan-Meier Survival Estimate")
plt.xlabel("Time")
plt.ylabel("Survival Probability")
plt.grid(True)
plt.show()
# --- Cox Proportional Hazards Fitter Example ---
data = pd.DataFrame({
'T': T, # Duration
'E': E, # Event observed
'age': np.random.randint(20, 70, num_samples),
'sex': np.random.choice(, num_samples, p=[0.55, 0.45])
})
cph = CoxPHFitter()
cph.fit(data, duration_col='T', event_col='E', formula="age + sex")
print("\nCoxPHFitter Summary:\n")
cph.print_summary()