Pandasdrill

Level 5: Analysis Exercise 61 of 63 Pro

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 exercise

More exercises in Analysis