Count Tukey IQR Outliers per Group in pandas
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement `count_outliers_per_group(df, group_col, value_col)`. For each group in `group_col`, it counts how many `value_col` rows fall outside that group's own 1.5×IQR Tukey fences.
Requirements:
- Per group, compute `Q1` and `Q3` with `quantile(0.25)` and `quantile(0.75)` using `interpolation='linear'`, and set `IQR = Q3 - Q1`.
- A value is an outlier when `value < Q1 - 1.5*IQR` or `value > Q3 + 1.5*IQR`. Both comparisons are strict, so a value exactly on a fence is not counted.
- Return a `pd.Series` of integer counts indexed by group label, sorted ascending.
- The Series name is not checked (the grader uses `assert_series_equal(..., check_names=False)`).
Example:
```python
df = pd.DataFrame({
"g": ["a", "a", "a", "a", "b", "b", "b"],
"v": [1, 2, 3, 100, 10, 11, 12],
})
count_outliers_per_group(df, "g", "v")
# g
# a 1
# b 0
# dtype: int64
```
```hint Where the quartiles come from
Each group is judged against its own distribution, so the quartiles have to be computed after grouping, one pair per group.
```
```hint Fence boundaries
Look closely at the comparison operators. A value equal to a fence must not be counted.
```
### What a Strong Answer Covers
- Computing Q1, Q3 and the IQR inside each group with linear interpolation.
- Strict comparisons against both fences, so boundary values are left out of the count.
- Returning an `int64` Series indexed by group label in ascending order.
- How NaN values, missing group keys and very small groups affect the counts.
- The cost of a per-group Python function and a vectorized alternative.
### Follow-up Questions
- How do groups with a single row or only NaN values behave, and would you guard them explicitly?
- How would you make this scale to millions of rows and many thousands of groups?
- How would the counts change with `interpolation='midpoint'`, or with 3×IQR fences instead of 1.5×IQR?
- When is a per-group fence a poor way to flag outliers?
Overview: Write a pandas function that counts, for each group in a DataFrame, how many values fall outside that group's own 1.5×IQR Tukey fences. It tests groupby logic, linear quantile interpolation, strict boundary comparisons, and edge cases such as NaN values and very small groups.