KatInterview

Resampling Estimators: Confidence Intervals and Variance on a DataFrame

Statistics & ExperimentsModel answer
MediumModel answerStatistics & Experimentsresamplingbootstrapjackknife

Last updated

Implement bootstrap percentile confidence intervals and jackknife leave-one-out variance estimation for arbitrary scalar statistics on a pandas DataFrame.

Background

Many real-world metrics are complex ratio statistics — think "revenue per session" or "conversion rate weighted by cohort size" — where deriving an analytical standard error is either intractable or relies on assumptions the data may not satisfy. Non-parametric resampling methods sidestep these assumptions entirely: they estimate a statistic's variability by repeatedly recomputing it on perturbed versions of the original data.

Your task is to implement two such methods as Python functions that accept any pandas DataFrame and any callable statistic.

What to Implement

1. bootstrap_ci

Draw n_boot samples of size n with replacement from df (where n = len(df)). Evaluate stat_fn on each sample. Return the two-sided empirical percentile confidence interval at level ci:

  • Lower bound: the alpha / 2 quantile of the replicate distribution
  • Upper bound: the 1 - alpha / 2 quantile
  • where alpha = 1 - ci

2. jackknife_variance

Compute n leave-one-out statistics: for each position i, evaluate stat_fn on the DataFrame with row i removed. Then estimate the variance as:

Var_jack = ((n - 1) / n) * sum((stat_i - stat_mean)^2)

where stat_mean is the mean of the n leave-one-out values.

Function Signatures

import pandas as pd
from typing import Callable, Tuple

def bootstrap_ci(
    df: pd.DataFrame,
    stat_fn: Callable[[pd.DataFrame], float],
    n_boot: int = 1000,
    ci: float = 0.95,
    random_state: int | None = None,
) -> Tuple[float, float]:
    ...

def jackknife_variance(
    df: pd.DataFrame,
    stat_fn: Callable[[pd.DataFrame], float],
) -> float:
    ...

Constraints

  • 2 <= len(df) <= 10_000
  • stat_fn accepts a DataFrame and returns a scalar float
  • All row selection must be positional — the input DataFrame may have duplicate or non-contiguous index labels, and your implementation must not break in that case
  • Results must be reproducible when random_state is provided
  • Raise ValueError if len(df) < 2 in jackknife_variance
  • Numerical tolerance for correctness: 1e-4

Example

import pandas as pd
import numpy as np

data = pd.DataFrame({
    "clicks": [10, 20, 15, 30, 25],
    "views":  [100, 200, 150, 250, 200],
})

def click_rate(d: pd.DataFrame) -> float:
    return d["clicks"].sum() / d["views"].sum()

j_var = jackknife_variance(data, click_rate)
# approximately 3.5e-5

lo, hi = bootstrap_ci(data, click_rate, n_boot=2000, ci=0.90, random_state=42)
# lo and hi bracket the point estimate (~0.111)

What Is Expected

  • Correct implementation of both functions matching the mathematical definitions above
  • Proper handling of the positional indexing requirement
  • Reproducible bootstrap output under a fixed seed
  • A brief explanation of the scaling factor (n-1)/n in the jackknife formula and why positional indexing matters

Hints

Hint 1

For the bootstrap, generate all n_boot × n index arrays in one shot with a seeded RNG and use iloc — this handles duplicate index labels and is faster than calling sample() in a loop.

Hint 2

The jackknife factor (n-1)/n looks wrong at first glance compared to the usual 1/(n-1) in sample variance, but it's correct: leave-one-out estimates are highly correlated, so the raw sum of squared deviations is much smaller than for independent draws and needs to be inflated, not deflated.

Hint 3

A common bug is using df.drop(i) or df.loc[...] for the leave-one-out step — both break when the DataFrame has duplicate or non-contiguous integer labels. Build a boolean or integer position mask and always go through iloc.