Contextual Outlier Screening by Group
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement `contextual_outliers(df, group_col, val_col)`. For each non-null value of `val_col`, compute `global_z = (x - global_mean) / global_std` and `group_z = (x - group_mean) / group_std`, both with population std `ddof=0`. Return rows extreme within their group but not globally.
Requirements:
- Keep rows where `abs(group_z) > 2.0` and `abs(global_z) <= 2.0`. Nulls are ignored for stats and flagging.
- The result has columns exactly `['group', 'value', 'group_z', 'global_z']` and preserves the original index labels (also when it is empty).
- Sort by `abs(group_z)` descending, then original index ascending.
- Groups with std 0 produce no flags and must not raise or emit `inf`/`NaN` rows.
- If the global std is 0, avoid division-by-zero artifacts.
Example input (`group_col='group'`, `val_col='value'`):
```text
index group value
0 A 10
1 A 10
2 A 10
3 A 10
4 A 10
5 A 16
6 B 0
7 B 20
8 B 40
9 B NaN
```
Expected output:
```text
index group value group_z global_z
5 A 16.0 2.2361 0.1905
```
Group A has mean 11 and population std $\sqrt{5}$, so 16 is about 2.24 group standard deviations above its group mean. Across the nine non-null values (mean 14, std about 10.50) it is only 0.19 standard deviations above the mean. Row 8 has a global z of about 2.48, but its group z inside B is about 1.22, so it is not returned. Row 9 is null and is ignored.
```hint Row-aligned group statistics
Look for a groupby operation that returns one value per original row, on the original index, instead of one value per group.
```
```hint Zero-variance groups
Work out what dividing by a group std of 0 can produce for the rows of that group once floating point rounding is involved, and decide what to test before you filter.
```
### Constraints & Assumptions
- `df` is a pandas DataFrame. `val_col` is numeric and may contain nulls; `group_col` holds hashable group labels.
- Index labels are unique and sortable, since they break ties in the sort.
- Both the global and the group statistics use population std (`ddof=0`). pandas defaults to `ddof=1`.
- The cutoff is fixed at 2.0 for both conditions.
### Clarifying Questions to Ask
- Should rows whose group label is null count toward the global statistics, and can they ever be flagged?
- Should `value` keep the column's original dtype, or come back as float?
- Should the z-scores in the output be rounded, or returned at full precision?
### What a Strong Answer Covers
- Both z-scores computed with `ddof=0` on non-null values only, with the group statistics aligned to each row's original index.
- Zero-std groups and a zero global std handled without `inf`, `NaN` rows or an exception.
- Both conditions applied together, with the strict and non-strict comparisons exactly as specified.
- The exact output columns and index labels, including the empty case, sorted with a deterministic tie-break.
- The time and space cost of the approach.
### Follow-up Questions
- How would you generalize the fixed `2.0` threshold?
- Why does `ddof` matter here, and when would it bite?
- What is the smallest group size that can ever produce a flag at this threshold?
- What happens when one extreme value inflates its own group's std?
Overview: Write a pandas function that flags values that are extreme within their own group but ordinary across the whole dataset, using population z-scores. It tests groupby transform alignment, null handling, guards for zero-variance groups, and a deterministic sort order.