Implement stratified blocked A/B assignment balanced within each segment
Role: Data Scientist
Category: Analytics & Experimentation
Difficulty: medium
Interview Round: Other
Implement `stratified_assign` for blocked A/B assignment. Each distinct `"segment"` value is a stratum, and each stratum is split as evenly as possible between `"control"` and `"treatment"`. `df` has columns `"user_id"` (str) and `"segment"` (str) and a RangeIndex. Return a new DataFrame equal to `df` plus a `"variant"` column of dtype object, keeping the original row order and RangeIndex.
```python
def stratified_assign(df: pd.DataFrame, seed: int) -> pd.DataFrame:
```
Follow this convention so the same seed always gives the same output:
- Create exactly one generator, `rng = np.random.default_rng(seed)`.
- Process the strata in ascending sorted order of their `"segment"` values, consuming the single `rng` in that order.
- For a stratum of `n_s` rows, taken in `df`'s original order, draw `order = rng.permutation(n_s)` exactly once.
- Within the stratum, the row at position `order[i]` gets `"control"` if `i` is even and `"treatment"` otherwise, so an odd-sized stratum gets one extra control.
- Never mutate `df`.
```python
df = pd.DataFrame({
"user_id": ["u0", "u1", "u2", "u3", "u4"],
"segment": ["US", "CA", "US", "CA", "US"],
})
# Strata in sorted order: "CA" (rows 1, 3), then "US" (rows 0, 2, 4).
# "CA" gets one control and one treatment; "US" gets two controls and one treatment.
# Which rows get which arm depends on the seed. Row order and the RangeIndex are unchanged.
```
```hint Two kinds of position
Keep a row's position inside its stratum, which is what the permutation refers to, separate from its position in `df`, which is where the label has to go.
```
```hint Stream order
The draws for one stratum change the generator state for every stratum after it. Check that the loop order and the number of draws match the convention exactly.
```
### Constraints & Assumptions
- `"segment"` has no nulls and all its values are strings.
- `df` has a RangeIndex, and the output keeps it.
- The `"variant"` column must have dtype object.
### What a Strong Answer Covers
- A correct mapping from permuted positions inside a stratum back to rows of `df`.
- Exact reproducibility: one generator, strata in sorted order, one permutation per stratum.
- A new DataFrame with the original order, the original index and an object-dtype `"variant"` column, with the input left untouched.
- Why blocking guarantees balance within one in every stratum, and the time cost of the approach.
### Follow-up Questions
- Why draw one permutation per stratum instead of shuffling all rows once?
- How would you extend this to unequal allocation, such as 70/30?
- How do you keep assignments stable when new users arrive over time?
- How should the analysis of the experiment account for the stratified design?
Overview: Implement blocked A/B assignment in pandas that randomizes users within each segment so control and treatment differ by at most one per segment. It tests reproducible use of a seeded generator, careful index bookkeeping and why stratified randomization balances covariates across arms.