Assign variants per cluster and roll user metrics up to one row per cluster in pandas
Role: Data Scientist
Category: Analytics & Experimentation
Difficulty: medium
Interview Round: Other
Implement `def cluster_rollup(df: pd.DataFrame, salt: str) -> pd.DataFrame`: assign variants per cluster, then roll the metric up to one row per cluster. `df` has one row per user with columns `"user_id"` (str), `"cluster_id"` (str) and `"metric"` (float).
The function must meet these requirements:
- Per cluster: `variant = "control" if int(hashlib.md5(f"{salt}:{cluster_id}".encode("utf-8")).hexdigest(), 16) % 100 < 50 else "treatment"`. Users inherit their cluster's variant.
- Exactly one row per cluster, indexed by distinct `cluster_id` sorted ascending, index name `"cluster_id"`.
- Columns exactly `["variant", "n_users", "cluster_mean"]` in that order.
- `variant` dtype `object`, `n_users` dtype `int64` (user count).
- `cluster_mean` dtype `float64`: unweighted mean of the cluster's `"metric"`.
Example:
```python
df = pd.DataFrame({
"user_id": ["u1", "u2", "u3", "u4"],
"cluster_id": ["cA", "cA", "cB", "cB"],
"metric": [1.0, 3.0, 2.0, 2.0],
})
cluster_rollup(df, salt="exp1")
# variant n_users cluster_mean
# cluster_id
# cA <arm> 2 2.0
# cB <arm> 2 2.0
```
Each cluster has two users. The mean for cA is (1.0 + 3.0) / 2 = 2.0 and the mean for cB is (2.0 + 2.0) / 2 = 2.0. Each `<arm>` cell is "control" or "treatment", whichever the hash rule gives for `"exp1:cA"` and `"exp1:cB"`.
```hint Order of operations
Aggregate first. Once there is one row per cluster, the cluster ids are the index, and each arm can be computed exactly once from them.
```
```hint Output contract
Check what `groupby` already gives you for sort order, index name and the count's dtype. Then build the variant column so pandas has no room to infer a different dtype for it.
```
### What a Strong Answer Covers
- Computing the variant once per cluster with the exact hash rule, so every user in a cluster shares an arm.
- Aggregating to one row per cluster with the user count and the unweighted mean of `metric`.
- Meeting the output contract: ascending index named `"cluster_id"`, the exact column order, and all three dtypes.
- Why the analysis unit should match the randomization unit, in terms of intra-cluster correlation and variance.
### Follow-up Questions
- Why not weight `cluster_mean` by `n_users` when comparing arms?
- How would you extend this to a stratified or covariate-adjusted analysis?
- Given this frame, how would you test whether treatment changed the metric, and what sample size drives the test's power?
Overview: Write a pandas function that assigns experiment arms per cluster with a salted hash and rolls user metrics up to one row per cluster. It tests groupby aggregation, an exact output contract for index, columns and dtypes, and why the analysis unit should match the randomization unit.