Compute the mean metric per variant over a fixed analysis window in pandas
Role: Data Scientist
Category: Analytics & Experimentation
Difficulty: easy
Interview Round: Other
Implement `metric_in_window_by_variant(df, start, end)` in Python with pandas. `df` has one row per event with columns `user_id` (object), `variant` (object, `'control'` or `'treatment'`), `event_time` (datetime64[ns]) and `value` (float64). Return the mean `value` per variant over in-window events.
```python
def metric_in_window_by_variant(df: pd.DataFrame, start: pd.Timestamp,
end: pd.Timestamp) -> dict:
...
```
Requirements:
- Keep rows with `start <= event_time < end` (half-open: start included, end excluded).
- Group in-window rows by `variant` and take the mean of `value`.
- Return a plain `dict` mapping variant name (`str`) to mean (`float`).
Example:
```python
df = pd.DataFrame({
"user_id": ["u1", "u2", "u3", "u4", "u5", "u6"],
"variant": ["control", "control", "control",
"treatment", "treatment", "treatment"],
"event_time": pd.to_datetime([
"2026-01-01 00:00", "2026-01-05 12:00", "2026-01-08 00:00",
"2025-12-31 23:00", "2026-01-03 09:00", "2026-01-07 23:59",
]),
"value": [10.0, 20.0, 100.0, 0.0, 30.0, 50.0],
})
start = pd.Timestamp("2026-01-01")
end = pd.Timestamp("2026-01-08")
metric_in_window_by_variant(df, start, end)
# {'control': 15.0, 'treatment': 40.0}
```
The control event at exactly `2026-01-01 00:00` is kept because the start is included, and the one at exactly `2026-01-08 00:00` is dropped because the end is excluded. The treatment event on 2025-12-31 falls before the window. That leaves control values 10 and 20 (mean 15.0) and treatment values 30 and 50 (mean 40.0).
```hint Boundaries first
Filter before you aggregate, and decide which comparison operator each end of the window needs.
```
### Constraints & Assumptions
- Both variants have at least one in-window event.
- `start` and `end` are timestamps with the same timezone handling as `event_time`.
- The mean is taken over events, so a user with several in-window events contributes each of them.
### What a Strong Answer Covers
- Correct handling of both window boundaries.
- Filtering before grouping, with the mean taken at the event level the task asks for.
- Plain Python output types: a `dict` with `str` keys and `float` values.
- What happens to a variant with no in-window events, and to missing values.
### Follow-up Questions
- How would you handle a variant with zero in-window events?
- Why does the half-open window convention matter for adjacent windows?
- How would the result and its variance change if the metric were the mean of per-user averages?
Overview: Write a pandas function that keeps experiment events inside a half-open time window and returns the mean metric value per variant as a plain dict. It tests timestamp filtering, boundary conventions for adjacent windows, and groupby aggregation with clean output types.