lifelines
Complete survival analysis library in Python. Handles right-censored data, Kaplan-Meier curves, and Cox regression. Standard for clinical trial analysis and epidemiology.
Best use case
lifelines is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Complete survival analysis library in Python. Handles right-censored data, Kaplan-Meier curves, and Cox regression. Standard for clinical trial analysis and epidemiology.
Teams using lifelines should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/lifelines/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How lifelines Compares
| Feature / Agent | lifelines | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Complete survival analysis library in Python. Handles right-censored data, Kaplan-Meier curves, and Cox regression. Standard for clinical trial analysis and epidemiology.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# Lifelines - Survival Analysis In medicine, we often care about "Time to Event" (death, recovery, relapse). Lifelines handles the complexity of "censored" data (patients who left the study). ## When to Use - Analyzing clinical trial data (time to death, disease progression). - Comparing survival between treatment groups. - Identifying risk factors using Cox Proportional Hazards regression. - Building survival models for prognosis. - Epidemiology studies (time to infection, recovery). ## Core Principles ### Censoring Patients who haven't experienced the event by the end of the study are "censored". Lifelines properly accounts for this. ### Hazard Ratios In Cox regression, a hazard ratio > 1 means increased risk; < 1 means decreased risk. ### Survival Curves Kaplan-Meier estimates the probability of survival over time without assuming a distribution. ## Quick Reference ### Standard Imports ```python from lifelines import KaplanMeierFitter, CoxPHFitter from lifelines.statistics import logrank_test import pandas as pd ``` ### Basic Patterns ```python # 1. Kaplan-Meier (Visualizing survival) kmf = KaplanMeierFitter() kmf.fit(durations=df['days'], event_observed=df['died']) kmf.plot_survival_function() kmf.median_survival_time_ # Time when 50% have died # 2. Cox Proportional Hazards (Risk factors) cph = CoxPHFitter() cph.fit(df, duration_col='days', event_col='died') cph.print_summary() # See hazard ratios for age, drug type, etc. cph.plot_partial_effects_on_outcome(covariates=['age'], values=[30, 50, 70]) ``` ## Critical Rules ### ✅ DO - **Use event_observed correctly** - 1 = event occurred, 0 = censored. - **Check proportional hazards assumption** - Use `cph.check_assumptions()` to validate Cox model. - **Compare groups with logrank test** - Statistical test for survival curve differences. - **Plot confidence intervals** - Survival estimates have uncertainty, especially with small samples. ### ❌ DON'T - **Don't ignore censoring** - Treating censored patients as "survived" biases results. - **Don't use regular regression** - Time-to-event data requires specialized methods. - **Don't assume proportional hazards** - If violated, use stratified Cox or parametric models. ## Advanced Patterns ### Comparing Multiple Groups ```python from lifelines.statistics import multivariate_logrank_test # Compare survival across treatment groups results = multivariate_logrank_test(df['days'], df['group'], df['died']) print(results.p_value) ``` ### Parametric Models ```python from lifelines import WeibullFitter, ExponentialFitter # When you need to extrapolate beyond observed data wf = WeibullFitter() wf.fit(df['days'], df['died']) wf.plot() ``` Lifelines transforms complex survival data into actionable medical insights, enabling evidence-based decisions in clinical research and practice.
Related Skills
xgboost-lightgbm
Industry-standard gradient boosting libraries for tabular data and structured datasets. XGBoost and LightGBM excel at classification and regression tasks on tables, CSVs, and databases. Use when working with tabular machine learning, gradient boosting trees, Kaggle competitions, feature importance analysis, hyperparameter tuning, or when you need state-of-the-art performance on structured data.
xarray
N-dimensional labeled arrays and datasets in Python. Built on top of NumPy and Dask. It introduces labels in the form of dimensions, coordinates, and attributes on top of raw NumPy-like arrays, making data analysis in physical sciences more intuitive and less error-prone. Use for working with multi-dimensional scientific data, NetCDF/GRIB/Zarr files, climate/weather/oceanographic datasets, remote sensing, geospatial imaging, large out-of-memory datasets with Dask, and labeled array operations.
transformers
State-of-the-art Machine Learning for PyTorch, TensorFlow, and JAX. Provides thousands of pretrained models to perform tasks on different modalities such as text, vision, and audio. The industry standard for Large Language Models (LLMs) and foundation models in science.
tqdm
A fast, extensible progress bar for Python and CLI. Instantly makes your loops show a smart progress meter with ETA, iterations per second, and customizable statistics. Minimal overhead. Use for monitoring long-running loops, simulations, data processing, ML training, file downloads, I/O operations, command-line tools, pandas operations, parallel tasks, and nested progress bars.
tensorflow
Comprehensive deep learning framework for building, training, and deploying neural networks. TensorFlow provides tf.keras high-level API for model construction, tf.data for efficient data pipelines, and tf.function for graph-mode optimization. Use when working with: neural network training and inference, image classification/detection/segmentation, NLP/text processing with embeddings or transformers, time series forecasting, generative models (VAE, GAN), transfer learning with pretrained models, custom training loops with GradientTape, GPU/TPU accelerated computation, or any deep learning task.
sympy
Comprehensive guide for SymPy - Python library for symbolic mathematics. Use for symbolic expressions, calculus (derivatives, integrals, limits, series), equation solving (algebraic, differential, systems), linear algebra, simplification, matrix operations, special functions, code generation, and mathematical proofs. Essential for analytical mathematics and computer algebra.
sunpy
The community-developed free and open-source software package for solar physics. Provides tools for data search and download, coordinate transformations specific to solar physics, and powerful image processing through the Map object. Use when working with solar data, solar images (EUV, magnetograms, white light), solar coordinates (Helioprojective, Heliographic), Fido data search, solar time series, differential rotation, limb fitting, or multi-instrument solar analysis (AIA, HMI, GOES).
statsmodels
Advanced statistical modeling and hypothesis testing. Complementary to SciPy's stats module, it provides classes and functions for the estimation of many different statistical models, as well as for conducting statistical tests and statistical data exploration. Use for linear regression, GLM, time series analysis, ANOVA, survival analysis, causal inference, and statistical hypothesis testing. Load when working with OLS, WLS, logistic regression, Poisson regression, ARIMA, SARIMAX, statistical diagnostics, p-values, confidence intervals, or R-style statistical analysis.
spacy-nltk
Natural Language Processing for text analysis, corpus linguistics, and production NLP pipelines. spaCy provides fast production-grade tokenization, POS tagging, NER, dependency parsing, and custom model training. NLTK provides classical corpus linguistics, linguistic analysis, VADER sentiment, collocation analysis, and access to standard linguistic corpora. Use when: processing and analyzing text data, extracting named entities (people, orgs, locations, dates), dependency parsing and syntactic analysis, building text classification pipelines, performing corpus-level linguistic analysis (frequency, collocations, readability), sentiment analysis, lemmatization and stemming, working with multilingual text, training custom NER or text classifiers, or any task requiring structured understanding of natural language beyond simple string operations.
sktime-tsfresh
Time series machine learning layer (Tier 1): integration of **sktime** and **tsfresh** for building production-grade pipelines that transform raw time series into tabular feature representations suitable for classical machine-learning models. *sktime* provides a unified, sklearn-compatible interface for time-series data types, transformations, and pipelines, while *tsfresh* enables large-scale automated extraction of statistical, spectral, and autocorrelation features, with optional statistically grounded feature relevance selection (FRESH).
sklearn-explainability
Advanced sub-skill for scikit-learn focused on model interpretability, feature importance, and diagnostic tools. Covers global and local explanations using built-in inspection tools and SHAP/LIME integrations.
sklearn-advanced
Professional sub-skill for scikit-learn focused on robust pipeline architecture, custom estimator development, advanced feature engineering, and rigorous model validation. Covers Target Encoding, Nested Cross-Validation, and Production Deployment.