Resampling Estimators: Confidence Intervals and Variance on a DataFrame
Statistics & ExperimentsModel answerLast 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 / 2quantile of the replicate distribution - Upper bound: the
1 - alpha / 2quantile - 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_000stat_fnaccepts a DataFrame and returns a scalarfloat- 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_stateis provided - Raise
ValueErroriflen(df) < 2injackknife_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)/nin 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Both methods answer the same question — how much does this statistic vary? — by recomputing it on slightly different versions of the data rather than via a closed-form formula. The implementations are short, but several non-obvious correctness details matter.
Bootstrap confidence interval
Treat the observed data as a stand-in for the true population. Draw n rows with replacement n_boot times, evaluate the statistic on each sample, and read off the desired quantiles. The core idea: if the empirical distribution is a good proxy for the population, the spread of replicate statistics approximates the statistic's true sampling distribution.
Key implementation choices:
- Generate all indices at once.
rng.integers(0, n, size=(n_boot, n))produces the full(n_boot × n)index matrix in one NumPy call. Looping overn_bootcalls tonp.random.choiceis slower and harder to seed reproducibly. - Use
ilocthroughout.df.iloc[idx[b]]selects rows by position, ignoring whatever labels the index carries.df.sample(...)uses label-based sampling internally and can behave unexpectedly with duplicate labels. - Quantile calculation.
np.percentile(reps, [100*alpha/2, 100*(1-alpha/2)])is a direct translation of the definition.
Jackknife variance
Recompute the statistic n times, each time omitting exactly one row by position. The variance estimate scales the spread of those leave-one-out values by (n-1)/n.
Why (n-1)/n and not 1/(n-1)? Leave-one-out replicates share n-2 of their n-1 rows with every other replicate, so they are highly correlated. Their raw variance (i.e., average squared deviation from their mean) is on the order of 1/(n-1)^2 times a unit-scale quantity, not 1/n. The factor (n-1)/n inflates this to recover the correct variance scale. A sanity check with the sample mean confirms this: for stat_fn = mean, the formula returns exactly s²/n, the textbook variance of the sample mean.
Positional indexing. Using df.iloc[np.arange(n) != i] selects all positions except i regardless of what the index labels are. df.drop(i) would drop every row whose label equals i, which silently deletes multiple rows when labels are duplicated — a subtle bug that only surfaces with non-standard DataFrames.
Complexity
| Method | Time | Space |
|---|---|---|
| Bootstrap | O(n_boot · (n + C(n))) | O(n_boot · n) for index matrix |
| Jackknife | O(n · C(n)) | O(n) per call |
For a linear statistic like a ratio of sums, C(n) = O(n), making jackknife O(n²). At n = 10,000 this is 10k calls on ~10k rows each — about 10⁸ row-touches, which is workable but slow for expensive stat_fn. If the statistic is decomposable, you could compute all leave-one-out values in O(n) total by maintaining running totals; but since stat_fn is a black box, the generic loop is the right contract here.
Common mistakes
- Using
df.drop(i)instead of positional masking — breaks on duplicate index labels - Calling
df.sample(n, replace=True)— ignores the seed and uses label-based sampling - Using
1/(n-1)as the scaling factor — overcounts variance by a factor of~n - Forgetting to reset the index on bootstrap resamples (not required here since
stat_fnreceives the sliced DataFrame, but can cause issues ifstat_fnuses.reset_index()internally)
Solution
import numpy as np
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]:
n = len(df)
if n < 1:
raise ValueError("df must contain at least one row")
if n_boot < 1:
raise ValueError("n_boot must be >= 1")
if not (0.0 < ci < 1.0):
raise ValueError("ci must be strictly between 0 and 1")
rng = np.random.default_rng(random_state)
# Build the full index matrix in one call — reproducible and fast.
# Shape: (n_boot, n), values are positional integers in [0, n).
idx = rng.integers(0, n, size=(n_boot, n))
reps = np.empty(n_boot, dtype=float)
for b in range(n_boot):
# iloc ensures positional selection regardless of index labels.
reps[b] = float(stat_fn(df.iloc[idx[b]]))
alpha = 1.0 - ci
lo, hi = np.percentile(reps, [100.0 * alpha / 2.0, 100.0 * (1.0 - alpha / 2.0)])
return float(lo), float(hi)
def jackknife_variance(
df: pd.DataFrame,
stat_fn: Callable[[pd.DataFrame], float],
) -> float:
n = len(df)
if n < 2:
raise ValueError("jackknife_variance requires at least 2 rows")
positions = np.arange(n)
stats = np.empty(n, dtype=float)
for i in range(n):
# Drop row at position i by building a boolean mask over positions.
# This is immune to duplicate or non-contiguous index labels.
stats[i] = float(stat_fn(df.iloc[positions != i]))
stat_mean = stats.mean()
return float((n - 1) / n * np.sum((stats - stat_mean) ** 2))
Verifying the example
For the five-row click-rate DataFrame, the leave-one-out rates are approximately 0.1125, 0.1143, 0.1133, 0.1077, and 0.1071. Their mean is ~0.1110. The sum of squared deviations is ~4.4e-5. Multiplying by 4/5 gives Var_jack ≈ 3.5e-5, so the standard error is ~0.006 — small relative to the point estimate of 0.111.
Key follow-up: when does jackknife fail?
The jackknife relies on the statistic changing smoothly when one row is removed. The sample median violates this: for even n, removing any single row shifts the median to one of just two values, so all leave-one-out estimates cluster at two points. The resulting variance estimate is inconsistent (it doesn't converge to the truth as n grows). The fix is either a delete-d jackknife with d → ∞ at an appropriate rate, or switching to the bootstrap, which is consistent for quantiles.