Skip to content

A first look at time-to-event data

Why a plain average of follow-up times misleads, and how the Kaplan–Meier median describes survival with censored data.

Introductory ~10 min8 steps

What runs in CodeSplash

You will be able to

  • Recognize censored data
  • Explain why the mean of observed times is biased
  • Read a median survival and its interval

Read first

01

The clock hasn't stopped for everyone

Read

In a cancer study, some patients have died by the time you analyze. Others are alive, or have moved away. For them you know only that they survived at least until you last saw them. Those times are censoredCensoringFollow-up ended before the event happened, so you only know the event time is later than observed..

The same shape appears everywhere: time to churn, time to failure, time to a first purchase.

02

What does the average say?

Predict

Predict first

You average every patient's follow-up time, treating the last contact as the end. How does that compare with their true average survival?

Too highAbout rightToo low
Reveal

The answer: Too low

Too low. A censored time is a lower bound: those patients will live longer than the number you recorded. Dropping them is no better, because it throws away people who did well.

03

See the bias

Explore

Raise the censoring rate, then compare what happens if you drop censored patients with the true median and with the Kaplan–Meier estimate.

FExplorable · Why you cannot just drop censored patients

What goes wrong if you ignore or discard censored observations?

If you drop the censored patients, how does the median compare with the truth?

How sure?
0.10
0.100
300
median6.9Truth7.5Kaplan–Meier3.4Drop censored3.3As events

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

04

The Kaplan–Meier curve

Read

At each event time, the curve drops by the share of people still at risk who had the event. Censored people count until they leave, and then stop counting. Their information is used, and nothing is invented about them.

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…

How sure?
14
0.35

Higher: follow-up ends sooner, so more patients are censored.

4

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 first; the figure appears when you commit.

Make your prediction to see the result.

05

Describe a survival column

In the app

In this lung cancer study, 165 of 228 patients died during follow-up. The median survival is 310 days, with a 95% interval from 284 to 361 days.

Kaplan–Meier survivalRecorded · Python and R agreeRecorded 2026-11-17 · 24 values compared
R

median survival = 310

Events
165
Median survival
310
95% CI
[284, 361]

Plots

Kaplan–Meier curveWhat fraction survives (is event-free) over time, and do groups differ?
View data
upperlowerCensoredAt riskSurvival probabilitytime
11022810
0.99940.969302280.99565
0.99340.953902270.982511
0.99080.948102240.978112
0.98520.936702230.969313
0.98230.931102210.964915
0.97930.925502200.960526
0.97620.920002190.956130
0.97300.914602180.951831
0.96650.903802170.943053
0.96320.898502150.938654
0.95980.893202140.934259
0.95300.882802130.925460
0.94950.877602110.921161
0.94600.872502100.916762
0.93900.862202090.907965
0.93540.857202070.903571
0.93180.852102060.899179
0.92450.842002050.890481
0.91720.832102030.881688
0.91350.827112010.877292
0.90980.822101990.872893
0.90230.812201980.864095
0.89850.807311960.8596105
0.89090.797401940.8507107
0.88710.792501920.8463110
0.88330.787601910.8418116
0.87940.782701900.8374118
0.87550.777801890.8330122
0.87170.772901880.8285131
0.86390.763201870.8197132
0.86000.758401850.8153135
0.85600.753601840.8108142
0.85210.748801830.8064144
0.84420.739201820.7975145
0.84030.734401800.7931147
0.83630.729601790.7887153
0.82830.720101780.7798156
0.81630.705801760.7665163
0.80830.696401730.7577166
0.80420.691701710.7532167
0.80020.687001700.7488170
0.80020.687011690.7488173
0.80020.687011680.7488174
0.79610.682211670.7443175
0.79200.677501650.7398176
0.78780.672711640.7353177
0.77950.663101620.7262179
0.77530.658301600.7217180
0.76690.648801590.7126181
0.76270.644001570.7081182
0.75850.639201560.7035183
0.75850.639211550.7035185
0.75430.634501540.6989186
0.75430.634511530.6989188
0.75000.629601520.6943189
0.75000.629611510.6943191
0.75000.629611500.6943192
0.74570.624801490.6897194
0.74570.624811480.6897196

First 60 of 187 rows.

Cumulative hazardHow has risk built up over time?
View data
Survival probabilitytime
10
0.99565
0.982511
0.978112
0.969313
0.964915
0.960526
0.956130
0.951831
0.943053
0.938654
0.934259
0.925460
0.921161
0.916762
0.907965
0.903571
0.899179
0.890481
0.881688
0.877292
0.872893
0.864095
0.8596105
0.8507107
0.8463110
0.8418116
0.8374118
0.8330122
0.8285131
0.8197132
0.8153135
0.8108142
0.8064144
0.7975145
0.7931147
0.7887153
0.7798156
0.7665163
0.7577166
0.7532167
0.7488170
0.7488173
0.7488174
0.7443175
0.7398176
0.7353177
0.7262179
0.7217180
0.7126181
0.7081182
0.7035183
0.7035185
0.6989186
0.6989188
0.6943189
0.6943191
0.6943192
0.6897194
0.6897196

First 60 of 187 rows.

Log–log survivalAre the hazards proportional, and could the times be Weibull?
View data
Survival probabilitytime
10
0.99565
0.982511
0.978112
0.969313
0.964915
0.960526
0.956130
0.951831
0.943053
0.938654
0.934259
0.925460
0.921161
0.916762
0.907965
0.903571
0.899179
0.890481
0.881688
0.877292
0.872893
0.864095
0.8596105
0.8507107
0.8463110
0.8418116
0.8374118
0.8330122
0.8285131
0.8197132
0.8153135
0.8108142
0.8064144
0.7975145
0.7931147
0.7887153
0.7798156
0.7665163
0.7577166
0.7532167
0.7488170
0.7488173
0.7488174
0.7443175
0.7398176
0.7353177
0.7262179
0.7217180
0.7126181
0.7081182
0.7035183
0.7035185
0.6989186
0.6989188
0.6943189
0.6943191
0.6943192
0.6897194
0.6897196

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

CurvenEventsMedian95% CI low95% CI highRMST (τ = 365)SE
All228165310284361263.227.799

Survival at chosen times

CurveTimeAt riskSurvival95% CI low95% CI high
All1001960.86400.81220.9023
All365650.40920.33870.4784
All730130.11570.06760.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
))
Python

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

CurvenEventsMedian95% CI low95% CI highRMST (τ = 365)SE
All228165310284361263.227.799

Survival at chosen times

CurveTimeAt riskSurvival95% CI low95% CI high
All1001960.86400.81220.9023
All365650.40920.33870.4784
All730130.11570.06760.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,
})

The median is where the curve crosses 50%. If it never crosses, you don't have a median yet.

06

What you need in your data

Read

Two columns per subject: the time to the event or to last contact, and an event flag saying which it was.

The Survival track goes on to compare groups, Cox regression and competing risks.

07

Check your understanding

Checkpoint

Check yourself

A customer signed up 90 days ago and hasn't churned. How should you record them?

Show the answer

Answer: b

You know they lasted at least 90 days. Censoring keeps that information without claiming an event happened.

Check yourself

What's the median survival in the lung study, in days?

Show the answer

Answer: 310

Read it from the card: the time at which the curve crosses 50%.

Check yourself

What happens if you analyze only patients whose death you observed?

Show the answer

Answer: b

The excluded people are those who did well enough to still be alive. That biases the estimate down.

08

Recap

Recap
  • A censored time is a lower bound, so don't average it or drop it.
  • Kaplan–Meier uses people until they leave the risk set.
  • Report the median survival with its interval and the number of events.

Concepts in this lesson