Top two orders per region
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
Return the two highest-revenue orders in each region as a DataFrame with the columns `region`, `order_id` and `revenue`, sorted by region A to Z and within each region by revenue from highest to lowest. A region with a single order contributes just that order. Row labels do not matter.
What this exercise teaches
rank inside a groupby numbers the orders within each region, so a mask like r <= 2 keeps the top two per region however many orders the region has. head(2) on an unsorted groupby takes the first two rows as they appear, not the largest. nlargest on the whole table ignores the regions altogether.
A hint if you get stuck
Rank revenue within each region with groupby(...).rank(ascending=False), keep the rows ranked 1 and 2, then sort. Sorting first and using groupby().head(2) is another route.
Try it now, free, no account needed
The first 15 tasks 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 adds timed mode and the certificate.
Open this exerciseMore exercises in Analysis
- Rolling averagePro
- Month over month growthPro
- Running totalPro
- Rank with tiesPro
- Change from the previous periodPro
- Monthly totals with resamplePro
- Quartile bins with qcutPro
- Age bands with cutPro
- Classify with applyPro
- Running total per groupPro
- Monthly totals with to_periodPro
- Days since the previous orderPro