Rank level-shift changepoint candidates in a daily time series with pandas
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement `changepoint_candidates(df, window, top_n)` for a `df` indexed by a daily `DatetimeIndex` with a numeric `value` column. Score each valid position by comparing the mean of the `window` values immediately before it (`mean_before`) with the mean of the `window` values immediately after it (`mean_after`), and return the `top_n` largest absolute shifts.
The result must follow these rules:
- Valid positions need a full `window` on both sides: indices in `[window, len(df) - window - 1]`. The point itself belongs to neither side.
- Columns, in this order: `date` (datetime64[ns], the changepoint timestamp itself), `mean_before`, `mean_after`, `delta` (`mean_after - mean_before`), `pct_shift` (`delta / mean_before`), `direction`.
- Compute `delta` and `pct_shift` from the unrounded means, then round the four float columns to 4 decimal places. `direction` is `'shift_up'` if `delta > 0`, else `'shift_down'`.
- Sort by `abs(delta)` descending, then `date` ascending, then `reset_index(drop=True)`. The sort and `direction` use the rounded `delta`, so the output agrees with the numbers it shows.
- If fewer than `top_n` valid positions exist, return all of them.
For example, with six consecutive days starting on 2024-01-01:
```python
dates = pd.date_range("2024-01-01", periods=6, freq="D")
df = pd.DataFrame({"value": [10, 10, 10, 20, 20, 20]}, index=dates)
changepoint_candidates(df, window=2, top_n=1)
```
```text
date mean_before mean_after delta pct_shift direction
0 2024-01-03 10.0 20.0 10.0 1.0 shift_up
```
Only indices 2 and 3 have two values on each side. Both compare [10, 10] with [20, 20], so both have a delta of 10.0, and the date tie-break keeps 2024-01-03.
```hint Window means without a loop
A rolling mean gives a trailing window at every position at once. Work out the offset that keeps the point itself out of the window, and how to get the leading window the same way.
```
```hint Short series
Check what your function returns when the series has fewer than `2 * window + 1` rows.
```
### Constraints & Assumptions
- `window` and `top_n` are both at least 1.
- The index is sorted and daily with no gaps, so no gap handling is required.
- `mean_before` is non-zero in the test data.
### What a Strong Answer Covers
- The exact range of valid positions, with both windows excluding the point itself.
- Window means computed in a vectorized pass, or a clear statement of the cost of a per-position loop.
- A deterministic order (absolute delta descending, then date ascending) that still holds after rounding.
- The output contract: column order and dtypes, a reset index, the zero-delta direction, and an empty result for a short series.
### Follow-up Questions
- How would you guard `pct_shift` against a zero `mean_before`?
- How would you make this scale to millions of rows?
- Why is a raw mean difference a weak changepoint test, and how would you improve it?
- One real shift gives high scores at several adjacent positions, as in the example. How would you report one candidate per shift?
Overview: Write a pandas function that scores each day of a daily series by the gap between the mean of the window before it and the window after it, then returns the largest level shifts. It tests rolling-window indexing, off-by-one boundaries, deterministic sorting and an exact output format.