Flag outliers per group with IQR

Pandas data engineering interview problem. Difficulty: intermediate. Pattern: Data Quality. About 16 minutes. Part of the Pro drill bank.

Compute the interquartile range per category and flag values that fall outside the 1.5 IQR boundaries. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.

Given a DataFrame data with columns category and val: For each category, identify outlier values using the interquartile range (IQR) method: Let Q1 be the 25th percentile and Q3 be the 75th percentile of val within that category. IQR = Q3 - Q1 A row is an outlier if val < Q1 - 1.5 * IQR or val > Q3 + 1.5 * IQR. Add a boolean column is_outlier (True if the value is an outlier, False otherwise). Retain original column ordering and row order. Reset the index. Assign the final DataFrame to result.

Requirements

  • Evaluate IQR independently within each category.
  • Preserve original row order.

Constraints

  • category is a string.
  • val is a numeric float or integer.

Examples

Input: data category | val A | 10.0 A | 12.0 A | 11.0 A | 13.0 A | 50.0 B | 100.0 B | 102.0 B | 99.0 B | 101.0 B | 5.0 Output: category | val | is_outlier A | 10 | False A | 12 | False A | 11 | False A | 13 | False A | 50 | True B | 100 | False B | 102 | False B | 99 | False B | 101 | False B | 5 | True Values 50.0 in group A and 5.0 in group B exceed 1.5 times the IQR bounds for their respective groups.

Topics: lakebench, pandas, quantile, boolean-mask.

More interview problems · All interview problems · Learn data engineering

intermediate

Flag outliers per group with IQR

Interview-style drill: Compute the interquartile range per category and flag values that fall outside the 1.5 IQR boundaries.

Given a DataFrame `data` with columns `category` and `val`: For each `category`, identify outlier values using the interquartile range (IQR) method: - Let `Q1` be the 25th percentile and `Q3` be the 75th percentile of `val` within that category. - `IQR = Q3 - Q1` - A row is an outlier if `val < Q1 - 1.5 * IQR` or `val > Q3 + 1.5 * IQR`. Add a boolean column `is_outlier` (`True` if the value is an outlier, `False` otherwise). Retain original column ordering and row order. Reset the index. Assign the final DataFrame to `result`.