Kaplan–Meier, one event at a time
Build a survival curve step by step, see why censored patients still count, and learn which interval each library draws by default.
What runs in CodeSplash
- Kaplan–Meier survival curves Verified in Python and R
You will be able to
- Compute a Kaplan–Meier step from the number at risk and the number of events
- Explain how censored subjects enter the calculation
- Fit the same curve in Python and R and match their intervals
The idea
ReadTo survive two years you must survive year one, and then year two given you survived year one. Kaplan–MeierKaplan–Meier estimatorEstimates survival by multiplying, at each event time, the share of those at risk who get past it. applies that logic at each event time:
is the number of events at time , and is the number at riskNumber at riskHow many people are still being followed, without the event, immediately before a given time.: everyone still under observation immediately before . Censored people count in until they leave, then drop out without causing a step.
Work one step
PredictPredict first
Ten patients are at risk. The curve stands at 1. One patient dies, and the curve steps down. Where does it land? Next, one patient is censored and one more dies.
Guess the curve's height after that second death.
Make your guess between 0 and 1 survival after this event, then reveal.
Reveal
The first death gives . The censored patient leaves, so 8 remain at risk, and the second death gives , about 79%. Censoring made that second step bigger: each death now counts for a larger share of those left.
Build a curve
ExploreStep through the events. Each row of the life table is one factor in the product above.
FExplorable · Kaplan–Meier, one step at a time
How do we estimate survival when some people leave the study before the event?
If censored patients were counted as having the event, survival would look…
Higher: follow-up ends sooner, so more patients are censored.
Solid: Kaplan–Meier so far — at t = 3.1: 11 at risk, 0 events, S = 0.851. Dashed: counting censored patients as deaths. Ticks: censoring times.
Commit your prediction above to see the result
Make your prediction to see the result.
Raise the censoring and look at the steps late in follow-up. Fewer people at risk means each event causes a larger drop, so the right-hand end of a curve is its least reliable part.
Read it on real patients
In the appIn the lung data, half the patients have died by day 310 (95% interval 284 to 361).
median survival = 310
- Events
- 165
- Median survival
- 310
- 95% CI
- [284, 361]
Plots
View data
| upper | lower | Censored | At risk | Survival probability | time |
|---|---|---|---|---|---|
| 1 | 1 | 0 | 228 | 1 | 0 |
| 0.9994 | 0.9693 | 0 | 228 | 0.9956 | 5 |
| 0.9934 | 0.9539 | 0 | 227 | 0.9825 | 11 |
| 0.9908 | 0.9481 | 0 | 224 | 0.9781 | 12 |
| 0.9852 | 0.9367 | 0 | 223 | 0.9693 | 13 |
| 0.9823 | 0.9311 | 0 | 221 | 0.9649 | 15 |
| 0.9793 | 0.9255 | 0 | 220 | 0.9605 | 26 |
| 0.9762 | 0.9200 | 0 | 219 | 0.9561 | 30 |
| 0.9730 | 0.9146 | 0 | 218 | 0.9518 | 31 |
| 0.9665 | 0.9038 | 0 | 217 | 0.9430 | 53 |
| 0.9632 | 0.8985 | 0 | 215 | 0.9386 | 54 |
| 0.9598 | 0.8932 | 0 | 214 | 0.9342 | 59 |
| 0.9530 | 0.8828 | 0 | 213 | 0.9254 | 60 |
| 0.9495 | 0.8776 | 0 | 211 | 0.9211 | 61 |
| 0.9460 | 0.8725 | 0 | 210 | 0.9167 | 62 |
| 0.9390 | 0.8622 | 0 | 209 | 0.9079 | 65 |
| 0.9354 | 0.8572 | 0 | 207 | 0.9035 | 71 |
| 0.9318 | 0.8521 | 0 | 206 | 0.8991 | 79 |
| 0.9245 | 0.8420 | 0 | 205 | 0.8904 | 81 |
| 0.9172 | 0.8321 | 0 | 203 | 0.8816 | 88 |
| 0.9135 | 0.8271 | 1 | 201 | 0.8772 | 92 |
| 0.9098 | 0.8221 | 0 | 199 | 0.8728 | 93 |
| 0.9023 | 0.8122 | 0 | 198 | 0.8640 | 95 |
| 0.8985 | 0.8073 | 1 | 196 | 0.8596 | 105 |
| 0.8909 | 0.7974 | 0 | 194 | 0.8507 | 107 |
| 0.8871 | 0.7925 | 0 | 192 | 0.8463 | 110 |
| 0.8833 | 0.7876 | 0 | 191 | 0.8418 | 116 |
| 0.8794 | 0.7827 | 0 | 190 | 0.8374 | 118 |
| 0.8755 | 0.7778 | 0 | 189 | 0.8330 | 122 |
| 0.8717 | 0.7729 | 0 | 188 | 0.8285 | 131 |
| 0.8639 | 0.7632 | 0 | 187 | 0.8197 | 132 |
| 0.8600 | 0.7584 | 0 | 185 | 0.8153 | 135 |
| 0.8560 | 0.7536 | 0 | 184 | 0.8108 | 142 |
| 0.8521 | 0.7488 | 0 | 183 | 0.8064 | 144 |
| 0.8442 | 0.7392 | 0 | 182 | 0.7975 | 145 |
| 0.8403 | 0.7344 | 0 | 180 | 0.7931 | 147 |
| 0.8363 | 0.7296 | 0 | 179 | 0.7887 | 153 |
| 0.8283 | 0.7201 | 0 | 178 | 0.7798 | 156 |
| 0.8163 | 0.7058 | 0 | 176 | 0.7665 | 163 |
| 0.8083 | 0.6964 | 0 | 173 | 0.7577 | 166 |
| 0.8042 | 0.6917 | 0 | 171 | 0.7532 | 167 |
| 0.8002 | 0.6870 | 0 | 170 | 0.7488 | 170 |
| 0.8002 | 0.6870 | 1 | 169 | 0.7488 | 173 |
| 0.8002 | 0.6870 | 1 | 168 | 0.7488 | 174 |
| 0.7961 | 0.6822 | 1 | 167 | 0.7443 | 175 |
| 0.7920 | 0.6775 | 0 | 165 | 0.7398 | 176 |
| 0.7878 | 0.6727 | 1 | 164 | 0.7353 | 177 |
| 0.7795 | 0.6631 | 0 | 162 | 0.7262 | 179 |
| 0.7753 | 0.6583 | 0 | 160 | 0.7217 | 180 |
| 0.7669 | 0.6488 | 0 | 159 | 0.7126 | 181 |
| 0.7627 | 0.6440 | 0 | 157 | 0.7081 | 182 |
| 0.7585 | 0.6392 | 0 | 156 | 0.7035 | 183 |
| 0.7585 | 0.6392 | 1 | 155 | 0.7035 | 185 |
| 0.7543 | 0.6345 | 0 | 154 | 0.6989 | 186 |
| 0.7543 | 0.6345 | 1 | 153 | 0.6989 | 188 |
| 0.7500 | 0.6296 | 0 | 152 | 0.6943 | 189 |
| 0.7500 | 0.6296 | 1 | 151 | 0.6943 | 191 |
| 0.7500 | 0.6296 | 1 | 150 | 0.6943 | 192 |
| 0.7457 | 0.6248 | 0 | 149 | 0.6897 | 194 |
| 0.7457 | 0.6248 | 1 | 148 | 0.6897 | 196 |
First 60 of 187 rows.
View data
| Survival probability | time |
|---|---|
| 1 | 0 |
| 0.9956 | 5 |
| 0.9825 | 11 |
| 0.9781 | 12 |
| 0.9693 | 13 |
| 0.9649 | 15 |
| 0.9605 | 26 |
| 0.9561 | 30 |
| 0.9518 | 31 |
| 0.9430 | 53 |
| 0.9386 | 54 |
| 0.9342 | 59 |
| 0.9254 | 60 |
| 0.9211 | 61 |
| 0.9167 | 62 |
| 0.9079 | 65 |
| 0.9035 | 71 |
| 0.8991 | 79 |
| 0.8904 | 81 |
| 0.8816 | 88 |
| 0.8772 | 92 |
| 0.8728 | 93 |
| 0.8640 | 95 |
| 0.8596 | 105 |
| 0.8507 | 107 |
| 0.8463 | 110 |
| 0.8418 | 116 |
| 0.8374 | 118 |
| 0.8330 | 122 |
| 0.8285 | 131 |
| 0.8197 | 132 |
| 0.8153 | 135 |
| 0.8108 | 142 |
| 0.8064 | 144 |
| 0.7975 | 145 |
| 0.7931 | 147 |
| 0.7887 | 153 |
| 0.7798 | 156 |
| 0.7665 | 163 |
| 0.7577 | 166 |
| 0.7532 | 167 |
| 0.7488 | 170 |
| 0.7488 | 173 |
| 0.7488 | 174 |
| 0.7443 | 175 |
| 0.7398 | 176 |
| 0.7353 | 177 |
| 0.7262 | 179 |
| 0.7217 | 180 |
| 0.7126 | 181 |
| 0.7081 | 182 |
| 0.7035 | 183 |
| 0.7035 | 185 |
| 0.6989 | 186 |
| 0.6989 | 188 |
| 0.6943 | 189 |
| 0.6943 | 191 |
| 0.6943 | 192 |
| 0.6897 | 194 |
| 0.6897 | 196 |
First 60 of 187 rows.
View data
| Survival probability | time |
|---|---|
| 1 | 0 |
| 0.9956 | 5 |
| 0.9825 | 11 |
| 0.9781 | 12 |
| 0.9693 | 13 |
| 0.9649 | 15 |
| 0.9605 | 26 |
| 0.9561 | 30 |
| 0.9518 | 31 |
| 0.9430 | 53 |
| 0.9386 | 54 |
| 0.9342 | 59 |
| 0.9254 | 60 |
| 0.9211 | 61 |
| 0.9167 | 62 |
| 0.9079 | 65 |
| 0.9035 | 71 |
| 0.8991 | 79 |
| 0.8904 | 81 |
| 0.8816 | 88 |
| 0.8772 | 92 |
| 0.8728 | 93 |
| 0.8640 | 95 |
| 0.8596 | 105 |
| 0.8507 | 107 |
| 0.8463 | 110 |
| 0.8418 | 116 |
| 0.8374 | 118 |
| 0.8330 | 122 |
| 0.8285 | 131 |
| 0.8197 | 132 |
| 0.8153 | 135 |
| 0.8108 | 142 |
| 0.8064 | 144 |
| 0.7975 | 145 |
| 0.7931 | 147 |
| 0.7887 | 153 |
| 0.7798 | 156 |
| 0.7665 | 163 |
| 0.7577 | 166 |
| 0.7532 | 167 |
| 0.7488 | 170 |
| 0.7488 | 173 |
| 0.7488 | 174 |
| 0.7443 | 175 |
| 0.7398 | 176 |
| 0.7353 | 177 |
| 0.7262 | 179 |
| 0.7217 | 180 |
| 0.7126 | 181 |
| 0.7081 | 182 |
| 0.7035 | 183 |
| 0.7035 | 185 |
| 0.6989 | 186 |
| 0.6989 | 188 |
| 0.6943 | 189 |
| 0.6943 | 191 |
| 0.6943 | 192 |
| 0.6897 | 194 |
| 0.6897 | 196 |
First 60 of 187 rows.
Assumptions
- Non-informative censoring — 63 of 228 observations are censored; censoring must be unrelated to prognosis.
- Number of events — At least 10 events per curve.
Survival summary
| Curve | n | Events | Median | 95% CI low | 95% CI high | RMST (τ = 365) | SE |
|---|---|---|---|---|---|---|---|
| All | 228 | 165 | 310 | 284 | 361 | 263.22 | 7.799 |
Survival at chosen times
| Curve | Time | At risk | Survival | 95% CI low | 95% CI high |
|---|---|---|---|---|---|
| All | 100 | 196 | 0.8640 | 0.8122 | 0.9023 |
| All | 365 | 65 | 0.4092 | 0.3387 | 0.4784 |
| All | 730 | 13 | 0.1157 | 0.0676 | 0.1778 |
log-log intervals; Greenwood standard errors.
- Event: dead = true. Intervals: log-log transformation (Greenwood SE); median limits from the interval curves (Brookmeyer–Crowley).
The exact R script · R R version 4.5.1 (2025-06-13)
# Kaplan–Meier survival curves
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.km 1.0.1 · spec 67e00adfab7af6ae
# Dataset: lung (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(survival)
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/lung.parquet", col_select = c("time", "dead")))
n_input <- nrow(df)
df[["dead"]] <- factor(df[["dead"]], levels = c("false", "true")) # stored level order
df <- df[stats::complete.cases(df[c("time", "dead")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("time", "dead")) # infinite values stop the run (registry/errors.yaml)
# %% Event coding
tcol <- "time"
ecol <- "dead"
tt <- as.numeric(df[[tcol]])
if (any(tt < 0)) cs_error("CS_E_INVALID_VALUES", column = tcol, requirement = "zero or positive (survival times)", count = sum(tt < 0))
event_level <- "true" # the event; other levels are censored
ev <- as.character(df[[ecol]]) == event_level
event_label <- sprintf("%s = %s", ecol, event_level)
if (!any(ev)) cs_error("CS_E_NO_EVENTS", event = event_label)
# %% Kaplan–Meier
conf <- 0.95
conf_type <- "log-log" # pinned: survfit's default is "log"
times <- c(100, 365, 730)
if (length(times) == 0) times <- cs_default_times(tt)
rmst_tau <- 365 # 0 = no restricted mean
levels_g <- character(0)
strata <- list(All = rep(TRUE, length(tt)))
fin <- function(x) if (length(x) == 0 || is.null(x) || !is.finite(x)) NA else unname(x)
values <- list(event_label = event_label, n_groups = if (length(levels_g)) length(levels_g) else NA)
summary_rows <- list()
time_rows <- list()
curve <- list(time = numeric(0), surv = numeric(0), low = numeric(0), high = numeric(0), strata = character(0),
nrisk = numeric(0), ncensor = numeric(0))
for (name in names(strata)) {
m <- strata[[name]]
fit <- survfit(Surv(tt[m], ev[m]) ~ 1, conf.type = conf_type, conf.int = conf)
tb <- summary(fit, rmean = if (rmst_tau > 0) rmst_tau else "none")$table
st <- list(n = sum(m), events = sum(ev[m]), median = fin(tb[["median"]]),
median_low = fin(tb[[grep("LCL$", names(tb))]]), median_high = fin(tb[[grep("UCL$", names(tb))]]),
rmst = if (rmst_tau > 0) fin(tb[["rmean"]]) else NA, rmst_se = if (rmst_tau > 0) fin(tb[["se(rmean)"]]) else NA)
for (k in names(st)) values[[if (name == "All") k else sprintf("%s[%s]", k, name)]] <- st[[k]]
summary_rows[[length(summary_rows) + 1]] <- c(list(group = name), st)
s_at <- cs_step_at(fit$time, fit$surv, times)
l_at <- cs_step_at(fit$time, fit$lower, times)
u_at <- cs_step_at(fit$time, fit$upper, times)
r_at <- cs_n_risk_at(tt[m], times)
for (i in seq_along(times)) {
key <- sprintf("%s@%s", name, cs_key_num(times[i]))
values[[sprintf("surv[%s]", key)]] <- fin(s_at[i])
values[[sprintf("surv_low[%s]", key)]] <- fin(l_at[i])
values[[sprintf("surv_high[%s]", key)]] <- fin(u_at[i])
values[[sprintf("n_risk[%s]", key)]] <- r_at[i]
time_rows[[length(time_rows) + 1]] <- list(group = name, time = times[i], n_risk = r_at[i], surv = fin(s_at[i]),
lower = fin(l_at[i]), upper = fin(u_at[i]))
}
if ((name == "All") == (length(levels_g) == 0)) {
curve$time <- c(curve$time, 0, fit$time)
curve$surv <- c(curve$surv, 1, fit$surv)
curve$low <- c(curve$low, 1, fit$lower)
curve$high <- c(curve$high, 1, fit$upper)
curve$strata <- c(curve$strata, rep(name, length(fit$time) + 1))
curve$nrisk <- c(curve$nrisk, sum(m), fit$n.risk)
curve$ncensor <- c(curve$ncensor, 0, fit$n.censor)
}
}
# %% Log-rank test
if (length(levels_g)) {
lr <- survdiff(Surv(tt, ev) ~ gv, rho = 0)
lr_df <- sum(lr$n > 0) - 1
values$logrank_chisq <- lr$chisq
values$logrank_df <- lr_df
values$logrank_p <- stats::pchisq(lr$chisq, lr_df, lower.tail = FALSE)
} else {
values$logrank_chisq <- NA
values$logrank_df <- NA
values$logrank_p <- NA
}
# %% Assumptions
assumptions <- list(list(key = "censoring", label = "Non-informative censoring", status = "info",
detail = sprintf("%d of %d observations are censored; censoring must be unrelated to prognosis.",
sum(!ev), length(ev))))
few <- character(0)
for (r in summary_rows) if (r$events < 10 && (r$group != "All" || length(levels_g) == 0)) few <- c(few, r$group)
assumptions[[2]] <- if (length(few)) {
list(key = "sample_size", label = "Number of events", status = "warn",
detail = sprintf("Fewer than 10 events in %s; medians and curves are imprecise.", paste(few, collapse = ", ")))
} else {
list(key = "sample_size", label = "Number of events", status = "pass", detail = "At least 10 events per curve.")
}
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
med_text <- if (is.na(values$median)) "not reached" else format(signif(values$median, 4))
summary_cols <- list(
list(key = "group", label = if (length(levels_g)) g else "Curve", type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "events", label = "Events", type = "integer"), list(key = "median", label = "Median", type = "number"),
list(key = "median_low", label = paste(pct, "CI low"), type = "number"), list(key = "median_high", label = paste(pct, "CI high"), type = "number")
)
if (rmst_tau > 0) summary_cols <- c(summary_cols, list(list(key = "rmst", label = sprintf("RMST (τ = %s)", format(rmst_tau)), type = "number"),
list(key = "rmst_se", label = "SE", type = "number")))
cs_publish(list(
method = "survival.km",
methodVersion = "1.0.1",
title = paste0("Kaplan–Meier survival", if (length(levels_g)) paste(" by", g) else ""),
engine = cs_engine_info("survival", "codesplashr"),
n = length(tt),
summary = paste0(sprintf("%d of %d subjects had the event (%s); median survival %s.", sum(ev), length(ev), event_label, med_text),
if (length(levels_g)) sprintf(" Log-rank %s.", cs_fmt_p(values$logrank_p)) else ""),
apa = paste0("median survival = ", med_text,
if (length(levels_g)) sprintf("; log-rank χ²(%d) = %s, %s", values$logrank_df, cs_fmt_num(values$logrank_chisq), cs_fmt_p(values$logrank_p)) else ""),
statistics = c(list(
list(key = "events", label = "Events", value = values$events, format = "integer"),
list(key = "median", label = "Median survival", value = values$median),
list(key = "median_ci", label = paste(pct, "CI"), value = c(values$median_low, values$median_high))
), if (length(levels_g)) list(list(key = "logrank_p", label = "Log-rank p", value = values$logrank_p, format = "p"))),
tables = list(
list(key = "summary", title = "Survival summary", columns = summary_cols, rows = summary_rows),
list(key = "survival_at", title = "Survival at chosen times", columns = list(
list(key = "group", label = if (length(levels_g)) g else "Curve", type = "string"), list(key = "time", label = "Time", type = "number"),
list(key = "n_risk", label = "At risk", type = "integer"), list(key = "surv", label = "Survival", type = "number"),
list(key = "lower", label = paste(pct, "CI low"), type = "number"), list(key = "upper", label = paste(pct, "CI high"), type = "number")
), rows = time_rows, note = paste(conf_type, "intervals; Greenwood standard errors."))
),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Event: %s. Intervals: %s transformation (Greenwood SE); median limits from the interval curves (Brookmeyer–Crowley).", event_label, conf_type)),
charts = list(cs_chart("km", "km-curve", paste0("Kaplan–Meier curve", if (length(levels_g)) paste(" by", g) else ""), list(
time = cs_col(tcol, curve$time, "numeric"), surv = cs_col("Survival probability", curve$surv, "numeric"),
low = cs_col("lower", curve$low, "numeric"), high = cs_col("upper", curve$high, "numeric"),
strata = if (length(levels_g)) cs_col(g, curve$strata, "categorical", levels = levels_g) else NULL,
nrisk = cs_col("At risk", curve$nrisk, "numeric"), ncensor = cs_col("Censored", curve$ncensor, "numeric")
)), cs_chart("cumhaz", "cumhaz", paste0("Cumulative hazard", if (length(levels_g)) paste(" by", g) else ""), list(
time = cs_col(tcol, curve$time, "numeric"), surv = cs_col("Survival probability", curve$surv, "numeric"),
strata = if (length(levels_g)) cs_col(g, curve$strata, "categorical", levels = levels_g) else NULL
)), cs_chart("loglog", "loglog-survival", paste0("Log–log survival", if (length(levels_g)) paste(" by", g) else ""), list(
time = cs_col(tcol, curve$time, "numeric"), surv = cs_col("Survival probability", curve$surv, "numeric"),
strata = if (length(levels_g)) cs_col(g, curve$strata, "categorical", levels = levels_g) else NULL
))),
values = values
))
median survival = 310
- Events
- 165
- Median survival
- 310
- 95% CI
- [284, 361]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Non-informative censoring — 63 of 228 observations are censored; censoring must be unrelated to prognosis.
- Number of events — At least 10 events per curve.
Survival summary
| Curve | n | Events | Median | 95% CI low | 95% CI high | RMST (τ = 365) | SE |
|---|---|---|---|---|---|---|---|
| All | 228 | 165 | 310 | 284 | 361 | 263.22 | 7.799 |
Survival at chosen times
| Curve | Time | At risk | Survival | 95% CI low | 95% CI high |
|---|---|---|---|---|---|
| All | 100 | 196 | 0.8640 | 0.8122 | 0.9023 |
| All | 365 | 65 | 0.4092 | 0.3387 | 0.4784 |
| All | 730 | 13 | 0.1157 | 0.0676 | 0.1778 |
log-log intervals; Greenwood standard errors.
- Event: dead = true. Intervals: log-log transformation (Greenwood SE); median limits from the interval curves (Brookmeyer–Crowley).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Kaplan–Meier survival curves
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.km 1.0.1 · spec 67e00adfab7af6ae
# Dataset: lung (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.stats import survival as sv # survfit/survdiff twins (see its docstring)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/lung.parquet", columns=["time", "dead"])
n_input = len(df)
df["dead"] = pd.Categorical(df["dead"], categories=["false", "true"]) # stored level order
df = df.dropna(subset=["time", "dead"]) # listwise deletion over the analysis columns
df["dead"] = df["dead"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["time", "dead"]) # infinite values stop the run (registry/errors.yaml)
# %% Event coding
tcol = "time"
ecol = "dead"
t = df[tcol].to_numpy(dtype=float)
if (t < 0).any():
cs.cs_error("CS_E_INVALID_VALUES", column=tcol, requirement="zero or positive (survival times)", count=int((t < 0).sum()))
event_level = "true" # the event; other levels are censored
ev = (df[ecol].astype(str) == event_level).to_numpy()
event_label = f"{ecol} = {event_level}"
if not ev.any():
cs.cs_error("CS_E_NO_EVENTS", event=event_label)
# %% Kaplan–Meier
conf = 0.95
conf_type = "log-log" # pinned: survfit's default is "log"
times = [100, 365, 730, ] or sv.default_times(t)
rmst_tau = 365 # 0 = no restricted mean
levels = []
strata = [("All", np.ones(len(t), dtype=bool))]
values = {"event_label": event_label, "n_groups": len(levels) if levels else None}
summary_rows, time_rows, curve = [], [], {"time": [], "surv": [], "low": [], "high": [], "strata": [], "nrisk": [], "ncensor": []}
for name, m in strata:
fit = sv.km(t[m], ev[m], conf=conf, conf_type=conf_type)
med, med_lo, med_hi = sv.km_median(fit)
rm, rm_se = sv.rmst(fit, rmst_tau) if rmst_tau > 0 else (None, None)
at = sv.km_at(fit, times)
nan = lambda x: None if x is None or not np.isfinite(x) else float(x) # noqa: E731
stats_ = {"n": float(m.sum()), "events": float(ev[m].sum()), "median": nan(med), "median_low": nan(med_lo),
"median_high": nan(med_hi), "rmst": nan(rm), "rmst_se": nan(rm_se)}
for k, v in stats_.items():
values[k if name == "All" else f"{k}[{name}]"] = v
summary_rows.append({"group": name, **stats_})
for i, x in enumerate(times):
key = f"{name}@{sv.key_num(x)}"
row = {"group": name, "time": x, "n_risk": float(at["n_risk"][i]), "surv": nan(at["surv"][i]),
"lower": nan(at["lower"][i]), "upper": nan(at["upper"][i])}
values[f"surv[{key}]"], values[f"surv_low[{key}]"], values[f"surv_high[{key}]"] = row["surv"], row["lower"], row["upper"]
values[f"n_risk[{key}]"] = row["n_risk"]
time_rows.append(row)
if (name == "All") == (not levels):
curve["time"] += [0.0] + fit["time"].tolist()
curve["surv"] += [1.0] + fit["surv"].tolist()
curve["low"] += [1.0] + [nan(x) for x in fit["lower"]]
curve["high"] += [1.0] + [nan(x) for x in fit["upper"]]
curve["strata"] += [name] * (len(fit["time"]) + 1)
curve["nrisk"] += [float(m.sum())] + fit["n_risk"].tolist()
curve["ncensor"] += [0.0] + fit["n_censor"].tolist()
# %% Log-rank test
if levels:
codes = np.array([levels.index(x) for x in gv])
lr = sv.logrank(t, ev, codes, rho=0.0) # survdiff(Surv(time, event) ~ group)
values.update({"logrank_chisq": lr["chisq"], "logrank_df": float(lr["df"]), "logrank_p": lr["p"]})
else:
values.update({"logrank_chisq": None, "logrank_df": None, "logrank_p": None})
# %% Assumptions
assumptions = [{"key": "censoring", "label": "Non-informative censoring", "status": "info",
"detail": f"{int((~ev).sum())} of {len(ev)} observations are censored; censoring must be unrelated to prognosis."}]
few = [r["group"] for r in summary_rows if r["events"] < 10 and (r["group"] != "All" or not levels)]
if few:
assumptions.append({"key": "sample_size", "label": "Number of events", "status": "warn",
"detail": f"Fewer than 10 events in {', '.join(few)}; medians and curves are imprecise."})
else:
assumptions.append({"key": "sample_size", "label": "Number of events", "status": "pass", "detail": "At least 10 events per curve."})
# %% Result
pct = f"{conf:.0%}"
med_text = "not reached" if values["median"] is None else f"{values['median']:.4g}"
cs.publish({
"method": "survival.km",
"methodVersion": "1.0.1",
"title": "Kaplan–Meier survival" + (f" by {g}" if levels else ""),
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(len(t)),
"summary": f"{int(ev.sum())} of {len(t)} subjects had the event ({event_label}); median survival {med_text}."
+ (f" Log-rank {cs.fmt_p(values['logrank_p'])}." if levels else ""),
"apa": f"median survival = {med_text}" + (f"; log-rank χ²({values['logrank_df']:.0f}) = {cs.fmt_num(values['logrank_chisq'])}, {cs.fmt_p(values['logrank_p'])}" if levels else ""),
"statistics": [
{"key": "events", "label": "Events", "value": values["events"], "format": "integer"},
{"key": "median", "label": "Median survival", "value": values["median"]},
{"key": "median_ci", "label": f"{pct} CI", "value": [values["median_low"], values["median_high"]]},
] + ([{"key": "logrank_p", "label": "Log-rank p", "value": values["logrank_p"], "format": "p"}] if levels else []),
"tables": [
{"key": "summary", "title": "Survival summary", "columns": [
{"key": "group", "label": g if levels else "Curve", "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "events", "label": "Events", "type": "integer"}, {"key": "median", "label": "Median", "type": "number"},
{"key": "median_low", "label": f"{pct} CI low", "type": "number"}, {"key": "median_high", "label": f"{pct} CI high", "type": "number"},
] + ([{"key": "rmst", "label": f"RMST (τ = {rmst_tau:g})", "type": "number"}, {"key": "rmst_se", "label": "SE", "type": "number"}]
if rmst_tau > 0 else []), "rows": summary_rows},
{"key": "survival_at", "title": "Survival at chosen times", "columns": [
{"key": "group", "label": g if levels else "Curve", "type": "string"}, {"key": "time", "label": "Time", "type": "number"},
{"key": "n_risk", "label": "At risk", "type": "integer"}, {"key": "surv", "label": "Survival", "type": "number"},
{"key": "lower", "label": f"{pct} CI low", "type": "number"}, {"key": "upper", "label": f"{pct} CI high", "type": "number"},
], "rows": time_rows, "note": f"{conf_type} intervals; Greenwood standard errors."},
],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Event: {event_label}. Intervals: {conf_type} transformation (Greenwood SE); median limits from the interval curves (Brookmeyer–Crowley)."],
"charts": [cs.chart("km", "km-curve", "Kaplan–Meier curve" + (f" by {g}" if levels else ""), {
"time": cs.col(tcol, curve["time"], "numeric"), "surv": cs.col("Survival probability", curve["surv"], "numeric"),
"low": cs.col("lower", curve["low"], "numeric"), "high": cs.col("upper", curve["high"], "numeric"),
"strata": cs.col(g, curve["strata"], "categorical", levels=levels) if levels else None,
"nrisk": cs.col("At risk", curve["nrisk"], "numeric"), "ncensor": cs.col("Censored", curve["ncensor"], "numeric"),
}), cs.chart("cumhaz", "cumhaz", "Cumulative hazard" + (f" by {g}" if levels else ""), {
"time": cs.col(tcol, curve["time"], "numeric"), "surv": cs.col("Survival probability", curve["surv"], "numeric"),
"strata": cs.col(g, curve["strata"], "categorical", levels=levels) if levels else None,
}), cs.chart("loglog", "loglog-survival", "Log–log survival" + (f" by {g}" if levels else ""), {
"time": cs.col(tcol, curve["time"], "numeric"), "surv": cs.col("Survival probability", curve["surv"], "numeric"),
"strata": cs.col(g, curve["strata"], "categorical", levels=levels) if levels else None,
})],
"values": values,
})
Find the table of survival at chosen times on the card, with its number at risk. A survival figure resting on a handful of people at risk deserves little trust, whatever the curve looks like.
Same curve, two dialects
ReadThe estimate is identical everywhere, but the default interval isn't. CodeSplash uses log–log intervals. R's survfit defaults to conf.type = "log"; lifelines uses log–log, so set R's explicitly when you need them to match.
import pandas as pd
from lifelines import KaplanMeierFitter
df = pd.read_csv("lung.csv")
km = KaplanMeierFitter().fit(df["time"], event_observed=df["dead"])
print(km.median_survival_time_)
print(km.confidence_interval_.loc[305:310])library(survival)
df <- read.csv("lung.csv")
km <- survfit(Surv(time, dead == "true") ~ 1, data = df, conf.type = "log-log")
print(km)
summary(km, times = 365)Check your understanding
CheckpointCheck yourself
The curve stands at 0.80 going into an event time. Twenty people are at risk and 2 have the event. What is the new survival estimate?
Show the answer
Answer: 0.72
.
Check yourself
How does a patient censored at day 100 affect the Kaplan–Meier curve?
Show the answer
Answer: a
Censoring changes the denominators of later steps but never causes a step of its own. On a plotted curve a censored patient is usually marked with a small tick.
Check yourself
A curve drops sharply from 30% to 15% at day 900, where 4 people are at risk. What should you conclude?
Show the answer
Answer: b
Late steps are large because few people remain. Report the number at risk under the curve, and don't read much into the tail.
Recap
Recap- Kaplan–Meier multiplies conditional survival across event times.
- Censored subjects count in the risk set until they leave, and never cause a step.
- The right end of a curve rests on few people, so always show the number at risk.
- Check the interval type when you compare libraries.
Concepts in this lesson