Assign experiment variants by hashing cluster IDs in pandas
Role: Data Scientist
Category: Analytics & Experimentation
Difficulty: easy
Interview Round: Other
Implement `assign_clusters(df, salt)` to randomize by cluster so every user inherits their cluster's variant. `df` has columns `"user_id"` (str) and `"cluster_id"` (str), one row per user, with a RangeIndex. Hash the `cluster_id` and split 50/50 into `control`/`treatment`.
The function must meet these requirements:
- `variant = "control" if int(hashlib.md5(f"{salt}:{cluster_id}".encode("utf-8")).hexdigest(), 16) % 100 < 50 else "treatment"` (hash the cluster id, not the user id).
- Return a new DataFrame equal to `df` plus one appended column `"variant"` (dtype `object`). Never mutate `df`.
- Preserve the original row order and RangeIndex.
- All rows sharing a `cluster_id` have the same `variant`.
Example:
```python
df = pd.DataFrame({
"user_id": ["u1", "u2", "u3", "u4"],
"cluster_id": ["c1", "c1", "c2", "c2"],
})
out = assign_clusters(df, salt="exp_2024")
# out["variant"]: u1 and u2 share c1 -> same variant;
# u3 and u4 share c2 -> same variant
```
```hint Unit of randomization
Decide which single column the variant may depend on. Many rows share each value of that column, so you only need to compute the arm once per distinct value and then spread it back to the rows.
```
### Constraints & Assumptions
- `cluster_id` is always present and non-null.
- `df` has one row per user and a RangeIndex, which the output keeps.
- The 50/50 split is over cluster hashes, so arm sizes by user count may differ.
### What a Strong Answer Covers
- Reproducing the exact hash input (salt first, one colon, UTF-8, full md5 digest, modulo 100) so the assignment is deterministic.
- Making the variant a function of the cluster only, so no cluster is split across arms.
- Returning a copy with one appended `object` column, the original row order and index intact, and the input untouched.
- Why user counts per arm can differ under cluster randomization and what that means for the analysis.
### Follow-up Questions
- Why can cluster randomization produce unequal user counts per arm, and does it matter?
- How would you extend this to weighted or multi-arm splits while keeping clusters whole?
- Why does the hash include a salt, and what goes wrong if two experiments reuse the same salt?
Overview: Write a pandas function that assigns experiment variants by hashing cluster IDs, so every user inherits the arm of their cluster. It tests deterministic hash bucketing, keeping clusters whole, returning a new frame without mutating the input, and reasoning about unequal arm sizes.