Report per-segment outlier counts under local and global Tukey fences in pandas
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Write `segment_outlier_report(df, seg_col, val_col)` that, for each segment of `seg_col`, counts its values outside segment-local Tukey fences and outside global fences computed once from the full `val_col`. Return one row per segment.
The result must meet these requirements:
- Columns exactly `['segment', 'n', 'local_lower', 'local_upper', 'n_local_outliers', 'n_global_outliers', 'disagreement']`. `n`, `n_local_outliers`, `n_global_outliers` and `disagreement` are `int64`, and the two fences are `float64`.
- Fences: `Q1 - 1.5*IQR`, `Q3 + 1.5*IQR` with default `interpolation='linear'`. Nulls are excluded from all quantiles and counts, and `n` is the segment's non-null count.
- Counts use only the segment's own values strictly outside (`< lower` or `> upper`) its own fences or the global fences.
- `disagreement = n_global_outliers - n_local_outliers`.
- Sort by `disagreement` descending, then `segment` ascending, then `reset_index(drop=True)`.
Example:
```python
import numpy as np
import pandas as pd
df = pd.DataFrame({
'store': ['a'] * 5 + ['b'] * 6 + ['c'] * 3,
'sales': [10, 11, 12, 13, 20,
10, 11, 12, 13, 14, np.nan,
40, 41, 42],
})
segment_outlier_report(df, 'store', 'sales')
```
```text
segment n local_lower local_upper n_local_outliers n_global_outliers disagreement
0 c 3 39.0 43.0 0 3 3
1 b 5 8.0 16.0 0 0 0
2 a 5 8.0 16.0 1 0 -1
```
The 13 non-null values give global quartiles of 11 and 20, so the global fences are -2.5 and 33.5. Every value in `c` is above 33.5, but none is outside `c`'s own fences. The 20 in `a` is above `a`'s local upper fence of 16 but inside the global range. The null in `b` is excluded, so its `n` is 5.
```hint Where the nulls go
Decide at which step nulls are removed, and check that the global quartiles, each segment's quartiles and `n` all follow from that one choice.
```
```hint Check a fence by hand
For a segment of 5 sorted values, linear interpolation puts Q1 and Q3 exactly on the 2nd and 4th values. Use that to test your fences before trusting the counts.
```
### Constraints & Assumptions
- `val_col` is numeric and may contain nulls. `seg_col` holds sortable labels and may be categorical.
- Rows with a null segment label are part of the full column, so they count toward the global fences, but they get no row of their own.
- A segment whose values are all null has no fences and is left out of the report.
### What a Strong Answer Covers
- Global fences computed once from all non-null values, and local fences per segment, both with linear-interpolation quartiles and the 1.5 multiplier.
- Strict inequalities and null handling applied the same way under both rules.
- What a positive or a negative disagreement says about a segment.
- The exact columns, dtypes and sort order, including segments with very few values.
- The cost of the quantile computations and the per-segment work.
### Follow-up Questions
- How would you handle a segment with too few values to form a stable IQR?
- How would you adapt the fences for a right-skewed distribution?
- With millions of rows and thousands of segments, how would you remove the Python loop over segments?
Overview: Write a pandas function that counts, for each segment, the values outside its own Tukey fences and outside fences computed from the whole column, then ranks segments by the difference. It tests quantile-based outlier rules, null handling, groupby logic and an exact output schema.