Pooled Reply Rates per Category with Wilson Intervals in pandas
SQL & DataModel answerLast updated
Clean a job-postings table, compute invitation-weighted reply rates per category with 95% Wilson intervals, rank the top 5, and check the weighting identity numerically.
A marketplace exports a CSV where each row is one job posting:
| column | meaning |
|---|---|
job_id | identifier of the posting |
job_category | category label |
invitations_sent | integer >= 0, providers invited to the job |
provider_responses | integer >= 0, providers who replied |
region | region of the job |
created_at | ISO date the job was created |
Write pandas code that does the following.
- Compute a per-job
response_rate = provider_responses / invitations_sent. Rows withinvitations_sent = 0have an undefined rate and must be excluded. - For each
job_category, compute the invitation-weighted response rate and a 95% Wilson score confidence interval. - Return the top 5 categories by weighted rate. Break ties using the lower bound of the interval (higher is better).
- Handle bad data robustly. Rows with
provider_responses > invitations_sent, negative counts, or impossible dates must be logged and dropped, not allowed to crash the pipeline or skew results. - Verify numerically that the job-level invitation-weighted average equals the overall rate computed from summed numerators and denominators, within
1e-9.
Explain your design choices and the complexity of your approach.
Hints
Hint 1
Write out the weighted mean of per-job rates with weights equal to invitations. The invitation factor cancels, so the result is a ratio of two sums. What does that imply about how to aggregate?
Hint 2
Build a dictionary of named boolean masks, one per validation rule. Log the count and a few example job_ids for each rule, OR the masks together, and drop once. Remember that NaN comparisons evaluate to False, so fill them as invalid.
Hint 3
Treat each category as a binomial with n equal to total invitations and successes equal to total responses. Implement the Wilson formula vectorized and clip to [0, 1]. Sort with the rate and lower bound descending and the category name as a final deterministic key.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
What is really being tested
This looks like an aggregation question, but it is mostly about correctness. A strong answer shows four things:
- The invitation-weighted mean of per-job rates is the same as the pooled ratio of sums.
- The Wilson interval is implemented correctly and vectorized.
- Rows are validated before any math, and each drop is logged with a reason.
- The key identity is checked in code, not assumed.
Core idea: weighted rate equals pooled rate
For job i in a category, let the weight be its invitations n_i and its rate r_i = k_i / n_i, where k_i is its responses. Then
sum(n_i * r_i) / sum(n_i) = sum(k_i) / sum(n_i)
So the category's weighted rate is just total responses divided by total invitations. Implement it as a groupby sum of numerators and denominators. The common mistake is groupby().mean() on the per-job rate. That gives a job with 1 invitation the same influence as a job with 500, and it is a different (and noisier) estimator.
Wilson interval
Treat each category as a binomial with n = total invitations and p = total responses / n. With z = 1.96 for 95%:
denom = 1 + z^2 / n
center = (p + z^2 / (2n)) / denom
half = z * sqrt(p(1-p)/n + z^2 / (4n^2)) / denom
interval = [center - half, center + half]
Wilson is preferred over the Wald interval p ± z*sqrt(p(1-p)/n) because it never collapses to zero width at p = 0 or 1, behaves well for small n, and stays essentially within [0, 1]. Clip anyway to absorb floating-point noise.
One caveat to mention: the binomial model assumes invitations are independent trials. Invitations within one job are correlated, so the interval is somewhat optimistic. A cluster bootstrap over jobs is the natural follow-up.
Validation rules
Apply the rules before any aggregation. A row can break several rules, so log a count per rule but drop the row once.
| Problem | Action |
|---|---|
| Non-numeric or fractional counts | log, drop |
| Negative counts | log, drop |
provider_responses > invitations_sent | log, drop |
Unparseable, future, or implausibly old created_at | log, drop |
| Blank category | log, drop |
Duplicate job_id | log, keep first |
invitations_sent == 0 | exclude, log at info level (undefined rate, not corruption) |
Code
import logging
import numpy as np
import pandas as pd
log = logging.getLogger("response_rates")
Z95 = 1.959963984540054
COLUMNS = ["job_id", "job_category", "invitations_sent",
"provider_responses", "region", "created_at"]
def clean_jobs(df, earliest="2005-01-01", latest=None):
absent = set(COLUMNS) - set(df.columns)
if absent:
raise ValueError(f"missing columns: {sorted(absent)}")
latest = pd.Timestamp.now(tz="UTC") if latest is None else pd.Timestamp(latest, tz="UTC")
earliest = pd.Timestamp(earliest, tz="UTC")
inv = pd.to_numeric(df["invitations_sent"], errors="coerce")
resp = pd.to_numeric(df["provider_responses"], errors="coerce")
when = pd.to_datetime(df["created_at"], errors="coerce", utc=True)
cat = df["job_category"].astype("string").str.strip()
rules = {
"unparseable_counts": inv.isna() | resp.isna(),
"fractional_counts": (inv % 1 != 0) | (resp % 1 != 0),
"negative_counts": (inv < 0) | (resp < 0),
"responses_exceed_invitations": resp > inv,
"invalid_date": when.isna() | (when < earliest) | (when > latest),
"blank_category": cat.isna() | (cat == ""),
}
drop = pd.Series(False, index=df.index)
for name, mask in rules.items():
mask = mask.fillna(True).astype(bool) # unknown means invalid
if mask.any():
log.warning("%s: %d rows (sample ids %s)", name, mask.sum(),
df.loc[mask, "job_id"].head(5).tolist())
drop |= mask
out = df.loc[~drop].assign(
invitations_sent=inv[~drop].astype("int64"),
provider_responses=resp[~drop].astype("int64"),
created_at=when[~drop],
job_category=cat[~drop],
)
dupes = out["job_id"].duplicated(keep="first")
if dupes.any():
log.warning("duplicate job_id: %d rows dropped", dupes.sum())
out = out[~dupes]
zero = out["invitations_sent"] == 0
if zero.any():
log.info("excluding %d rows with zero invitations", zero.sum())
out = out[~zero].copy()
out["response_rate"] = out["provider_responses"] / out["invitations_sent"]
return out
def wilson(k, n, z=Z95):
k = np.asarray(k, dtype=float)
n = np.asarray(n, dtype=float)
p = k / n
d = 1 + z**2 / n
c = (p + z**2 / (2 * n)) / d
h = z * np.sqrt(p * (1 - p) / n + z**2 / (4 * n**2)) / d
return np.clip(c - h, 0, 1), np.clip(c + h, 0, 1)
def by_category(clean):
g = (clean.groupby("job_category")
.agg(jobs=("job_id", "size"),
invitations=("invitations_sent", "sum"),
responses=("provider_responses", "sum"))
.reset_index())
g["weighted_rate"] = g["responses"] / g["invitations"]
g["ci_low"], g["ci_high"] = wilson(g["responses"], g["invitations"])
return g
def check_identity(clean, cats, tol=1e-9):
w, r = clean["invitations_sent"], clean["response_rate"]
job_level = (w * r).sum() / w.sum()
pooled = clean["provider_responses"].sum() / w.sum()
assert abs(job_level - pooled) < tol, (job_level, pooled)
per_cat = ((clean.assign(x=w * r).groupby("job_category")["x"].sum())
/ clean.groupby("job_category")["invitations_sent"].sum())
gap = (per_cat - cats.set_index("job_category")["weighted_rate"]).abs()
assert (gap < tol).all()
return pooled
def top_categories(df, k=5):
clean = clean_jobs(df)
if clean.empty:
raise ValueError("no valid rows after cleaning")
cats = by_category(clean)
overall = check_identity(clean, cats)
top = (cats.sort_values(["weighted_rate", "ci_low", "job_category"],
ascending=[False, False, True])
.head(k).reset_index(drop=True))
return top, overall
Why this is correct
- Weighting: the check compares the weighted job-level mean against pooled sums overall and per category. The
1e-9tolerance only absorbs floating-point summation order. A larger gap signals a bug, for example zero-invitation rows reaching one path but not the other. - Ranking: the sort key is rate descending, then Wilson lower bound descending, then category name ascending so output is deterministic. Exact float ties between equal fractions such as 1/2 and 50/100 are identical in IEEE arithmetic, so the tie-break fires as intended.
- Cleaning: invalid rows never reach the aggregation.
fillna(True)makes unknown values count as invalid instead of silently passing.
Complexity
Cleaning and aggregation are one pass each, so O(N) time with O(N) memory. Sorting the categories costs O(C log C), where C is the number of categories and is typically tiny.
Trade-offs and common mistakes
- Averaging per-job rates unweighted, or weighting and then dividing by the wrong total.
- Using a Wald interval, which gives zero-width intervals at p = 0 or 1.
- Ranking purely by rate, so a category with 3 invitations and 3 responses beats a large category at 95%. This is why the lower bound matters. A stricter option is to rank by the lower bound itself or to enforce a minimum volume.
- Dropping rows silently instead of logging reasons, which makes the pipeline impossible to audit.
- Treating
invitations_sent = 0as a rate of 0. It is undefined and must be excluded, not zero-filled.
Likely follow-ups
- Equivalent SQL:
SUM(responses) / SUM(invitations)grouped by category, with the Wilson formula in a CTE. - Cluster bootstrap by job for honest intervals.
- Partial pooling (empirical Bayes shrinkage) for categories with very few invitations.