Pandas interview question: find the bugs in outlier capping

MediumCode review

Problem

Shared data rules

The colleague’s capped AOV equals the plain AOV in every city, to the cent. Per city, find the September 2026 order count, AOV, and AOV with amounts above the 99th percentile capped at it.

Formulas

Code to fix

Fix it free
# September AOV by city: as is and with outliers capped at the 99th percentile
cap = orders['amount_usd'].quantile(0.99)
sept = orders[(orders['status'] == 'delivered')
              & (orders['created_at'] >= '2026-09-01')
              & (orders['created_at'] < '2026-10-01')].copy()
sept['capped_usd'] = sept['amount_usd']
sept[sept['capped_usd'] > cap]['capped_usd'] = cap
result = sept.groupby('city').agg(orders=('order_id', 'count'), avg_check_usd=('amount_usd', 'mean'), avg_check_capped_usd=('capped_usd', 'mean')).reset_index()

Example

Input: orders
order_idcreated_atstatuscityamount_usdRow note
12026-08-20 13:00deliveredNew York400← August — not in the cap either
22026-09-03 10:00deliveredNew York32
32026-09-04 19:00deliveredNew York82
42026-09-05 12:00deliveredBoston20
52026-09-06 15:00deliveredBoston24
62026-09-07 18:00deliveredBoston28
Expected output
cityordersavg_check_usdavg_check_capped_usd
New York25756
Boston32424

The cap is the 99th percentile of the five September amounts, $80, so the $82 order counts as $80. New York’s capped AOV is ($32 + $80) / 2 = $56.

Fix it free

Fix the notebook — code checks it on real pandas in your browser. No sign-up needed.

Skills it tests

More interview questions

All questions