Outlier evidence table with reasons using Tukey fences in pandas

Quick Overview

Write a pandas function that returns only the outlier rows of a numeric column, each annotated with the breached Tukey fence, its direction, the distance past it and that distance in IQR units. It tests strict fence logic, zero-IQR and empty-result handling, index preservation and stable tie-breaking.

Outlier evidence table with reasons using Tukey fences in pandas

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: medium

Interview Round: Other

Write a function `outlier_rows_with_reason(df, col)` that returns an annotated evidence table for the outlier rows of the numeric column `col`. A value is an outlier when it lies strictly outside the Tukey fences `Q1 - 1.5 * IQR` and `Q3 + 1.5 * IQR`, where `IQR = Q3 - Q1`. Compute the quartiles with `Series.quantile` at the default `interpolation='linear'`, with NaNs dropped. A value exactly on a fence is not an outlier. The returned DataFrame must follow these rules: - It contains only the outlier rows, with columns exactly `['value', 'direction', 'fence', 'distance', 'pct_beyond']`, and it keeps the original index labels. - `value` is the offending value. `direction` is `'above_upper'` or `'below_lower'`. `fence` is the value of the fence that was breached. - `distance = abs(value - fence)` and `pct_beyond = 100 * distance / IQR`, rounded to 2 decimals. - Rows are sorted by `distance` descending, then by original index label ascending. - When there are no outliers, return an empty DataFrame with the five columns and the correct dtypes (`object` for `direction`, `float64` for the other four). An IQR of 0 counts as this case, so `pct_beyond` never divides by zero. Example: ```python df = pd.DataFrame({'x': [10, 11, 12, 13, 100, -50]}, index=['a', 'b', 'c', 'd', 'e', 'f']) outlier_rows_with_reason(df, 'x') ``` ```text value direction fence distance pct_beyond e 100.0 above_upper 16.5 83.5 3340.0 f -50.0 below_lower 6.5 56.5 2260.0 ``` With these six values the quartiles are 10.25 and 12.75, so the IQR is 2.5 and the fences are 6.5 and 16.5. Row `e` sits 83.5 above the upper fence, which is 33.4 IQRs, and it comes first because its distance is the larger one. A tie on `distance` is broken by the index label: ```python df = pd.DataFrame({'x': [40, 1, 2, 3, 4, 5, -34]}, index=[7, 1, 2, 3, 4, 5, 0]) outlier_rows_with_reason(df, 'x') ``` ```text value direction fence distance pct_beyond 0 -34.0 below_lower -3.0 31.0 1033.33 7 40.0 above_upper 9.0 31.0 1033.33 ``` Here the quartiles are 1.5 and 4.5 and the fences are -3 and 9. Both outliers are 31 away from their fence, so label 0 comes before label 7 even though it appears later in `df`. ```hint Order of the rows Think about the order the flagged rows are in before you sort, and how a stable sort can carry a secondary ordering for you. ``` ```hint Zero spread Work out what `pct_beyond` would be for a column whose IQR is 0, then check what the rules say the function should return in that case. ``` ### Constraints & Assumptions - `col` names a numeric (integer or float) column of `df`. It may contain NaN, and it may have no non-null values at all. - Index labels may be strings or integers, and they can be compared with each other. - The fence multiplier is fixed at 1.5. ### What a Strong Answer Covers - Fences computed from linear-interpolated quartiles of the non-null values, with strict comparisons so a value on a fence is not flagged. - The per-row direction, breached fence, distance and IQR-scaled `pct_beyond`, with the required rounding. - The output contract: only outlier rows, the five columns in order, original index labels kept, and the sort by distance with the index label breaking ties. - The empty result, including the IQR-of-zero case, returned with all five columns and their dtypes. - Missing values, including nullable dtypes, handled without errors. ### Follow-up Questions - How would you extend this to flag outliers across multiple columns at once? - Why report `pct_beyond` in IQR units instead of the raw `distance`? - A column has an IQR of 0 but still contains a few unusual values. What would you report for it instead of an empty table?

Overview: Write a pandas function that returns only the outlier rows of a numeric column, each annotated with the breached Tukey fence, its direction, the distance past it and that distance in IQR units. It tests strict fence logic, zero-IQR and empty-result handling, index preservation and stable tie-breaking.

General logo
General
Nov 25, 2026
mediumData ScientistOtherData Manipulation (SQL/Python)
0
0

Write a function outlier_rows_with_reason(df, col) that returns an annotated evidence table for the outlier rows of the numeric column col. A value is an outlier when it lies strictly outside the Tukey fences Q1 - 1.5 * IQR and Q3 + 1.5 * IQR, where IQR = Q3 - Q1. Compute the quartiles with Series.quantile at the default interpolation='linear', with NaNs dropped. A value exactly on a fence is not an outlier.

The returned DataFrame must follow these rules:

  • It contains only the outlier rows, with columns exactly ['value', 'direction', 'fence', 'distance', 'pct_beyond'] , and it keeps the original index labels.
  • value is the offending value. direction is 'above_upper' or 'below_lower' . fence is the value of the fence that was breached.
  • distance = abs(value - fence) and pct_beyond = 100 * distance / IQR , rounded to 2 decimals.
  • Rows are sorted by distance descending, then by original index label ascending.
  • When there are no outliers, return an empty DataFrame with the five columns and the correct dtypes ( object for direction , float64 for the other four). An IQR of 0 counts as this case, so pct_beyond never divides by zero.

Example:

df = pd.DataFrame({'x': [10, 11, 12, 13, 100, -50]},
                  index=['a', 'b', 'c', 'd', 'e', 'f'])
outlier_rows_with_reason(df, 'x')
   value    direction  fence  distance  pct_beyond
e  100.0  above_upper   16.5      83.5      3340.0
f  -50.0  below_lower    6.5      56.5      2260.0

With these six values the quartiles are 10.25 and 12.75, so the IQR is 2.5 and the fences are 6.5 and 16.5. Row e sits 83.5 above the upper fence, which is 33.4 IQRs, and it comes first because its distance is the larger one.

A tie on distance is broken by the index label:

df = pd.DataFrame({'x': [40, 1, 2, 3, 4, 5, -34]},
                  index=[7, 1, 2, 3, 4, 5, 0])
outlier_rows_with_reason(df, 'x')
   value    direction  fence  distance  pct_beyond
0  -34.0  below_lower   -3.0      31.0     1033.33
7   40.0  above_upper    9.0      31.0     1033.33

Here the quartiles are 1.5 and 4.5 and the fences are -3 and 9. Both outliers are 31 away from their fence, so label 0 comes before label 7 even though it appears later in df.

Constraints & Assumptions

  • col names a numeric (integer or float) column of df . It may contain NaN, and it may have no non-null values at all.
  • Index labels may be strings or integers, and they can be compared with each other.
  • The fence multiplier is fixed at 1.5.

What a Strong Answer Covers Guidance

  • Fences computed from linear-interpolated quartiles of the non-null values, with strict comparisons so a value on a fence is not flagged.
  • The per-row direction, breached fence, distance and IQR-scaled pct_beyond , with the required rounding.
  • The output contract: only outlier rows, the five columns in order, original index labels kept, and the sort by distance with the index label breaking ties.
  • The empty result, including the IQR-of-zero case, returned with all five columns and their dtypes.
  • Missing values, including nullable dtypes, handled without errors.

Follow-up Questions Guidance

  • How would you extend this to flag outliers across multiple columns at once?
  • Why report pct_beyond in IQR units instead of the raw distance ?
  • A column has an IQR of 0 but still contains a few unusual values. What would you report for it instead of an empty table?