Skip to main content

Section 13.7 Lifelines

A Python package called lifelines provides tools for survival analysis, including functions that compute Kaplan-Meier estimates.
We can use it to confirm that the result in the previous section is correct. First weโ€™ll compute the survival function using estimate_survival.
Listing 13.7.1. Python Code
try:
    import lifelines
except ImportError:
    %pip install lifelines
Listing 13.7.2. Python Code
surv = estimate_survival(resp60)
Next weโ€™ll compute it using lifelines. First weโ€™ll get the data into the format lifelines requires.
Listing 13.7.3. Python Code
complete = complete.dropna()
durations = np.concatenate([complete, ongoing])
event_observed = np.concatenate([np.ones(len(complete)), np.zeros(len(ongoing))])
Now we can make a KaplanMeierFitter object and fit the data.
Listing 13.7.4. Python Code
from lifelines import KaplanMeierFitter

kmf = KaplanMeierFitter()
kmf.fit(durations=durations, event_observed=event_observed)
<lifelines.KaplanMeierFitter:"KM_estimate", fitted with 15389 total observations, 5468 right-censored observations>
After fitting the data, we can call the plot function to display the results, which include the estimated survival function and a confidence intervalโ€”although the confidence interval is not correct in this case because it doesnโ€™t correct for stratified sampling.
Listing 13.7.5. Python Code
kmf.plot()

decorate(xlabel="Age", ylabel="Prob never married", ylim=ylim)
Figure 13.7.6.
Unlike the survival function we computed, the one from lifelines starts from 0. But the rest of the function is the same, within floating-point error.
Listing 13.7.7. Python Code
ps = kmf.survival_function_["KM_estimate"].drop(0)
np.allclose(ps, surv)
True
In the next section, weโ€™ll use weighted resampling to compute confidence intervals that take stratified sampling into account.