SQL ROW_NUMBER: latest order per customer
A pandas exercise from Pandasdrill. Solve it with a Python editor in your browser running real pandas, and it is checked the moment you submit.
The task
In SQL you would number each customer's orders with `ROW_NUMBER() OVER (PARTITION BY customer ORDER BY date DESC)` and keep row 1. Return each customer's most recent order, whatever its status, with the columns `customer`, `date` and `amount`.
What this exercise teaches
Sorting by date and taking tail(1) per group is the pandas form of ROW_NUMBER ... = 1. Taking the max of date and the max of amount separately is the classic mistake: the two maximums can come from different orders, so the row is one that never existed.
A hint if you get stuck
Sort by date, then keep the last row of each customer group.
Try it now, free, no account needed
Your first 8 exercises on Pandasdrill are free. Open it on the practice page, solve it, and get instant feedback with a hint. A free account adds the worked solution; Pro unlocks every exercise, timed mode and the certificate.
Open this exercise