Compute Pooled CTR by Experiment Variant in pandas
Role: Data Scientist
Category: Analytics & Experimentation
Difficulty: easy
Interview Round: Other
Implement `ctr_by_variant(df: pd.DataFrame) -> pd.Series` in `solution.py`. The frame has one row per user and three columns:
- `variant` (object): `'control'` or `'treatment'`
- `impressions` (int64): greater than 0
- `clicks` (int64)
Return the pooled click-through rate (CTR) of each variant, following these requirements:
- The CTR of a variant is `sum(clicks) / sum(impressions)` over its users. It is not the mean of the per-user ratios `clicks / impressions`.
- Return a `pd.Series` indexed by variant, with the index sorted ascending and named `'variant'`.
- Values are float64 and the Series is named `'ctr'`.
For example:
```python
import pandas as pd
df = pd.DataFrame({
"variant": ["control", "control", "treatment", "treatment"],
"impressions": [100, 200, 50, 150],
"clicks": [20, 10, 10, 12],
})
ctr_by_variant(df)
# variant
# control 0.10
# treatment 0.11
# Name: ctr, dtype: float64
```
Control has 30 clicks over 300 impressions, so its CTR is 0.10. Treatment has 22 clicks over 200 impressions, so its CTR is 0.11.
```hint Output contract
After a groupby, check which of the index name, the dtype and the Series name you get for free and which you still have to set yourself.
```
### Constraints & Assumptions
- One row per user, so each user belongs to exactly one variant.
- `impressions` is greater than 0 on every row, so each variant's denominator is positive.
- The only variant labels are `'control'` and `'treatment'`.
### What a Strong Answer Covers
- Summing clicks and impressions within each variant before dividing.
- Why the pooled rate differs from the mean of per-user rates, and which users each one gives more weight to.
- Meeting the output contract exactly: a Series named `ctr`, float64 values, and an index named `variant` sorted ascending.
- Edge cases such as rows with a missing variant label.
### Follow-up Questions
- The randomization unit is the user, but pooled CTR is a ratio of two sums. How would you get a standard error for the difference in pooled CTR between treatment and control?
- When would the mean of per-user CTRs be the better metric to report?
- How would you change the function to report CTR per variant per day?
Overview: Write a pandas function that returns the pooled click-through rate of each experiment variant as a named, sorted float Series. It tests ratio-of-sums aggregation with groupby, an exact output contract, and the difference between a pooled rate and an average of per-user rates.