"The top three products in each category" is one of the most asked pandas questions in interviews and at work. Three patterns cover it:
- Sort, then take the head of each group:
df.sort_values("revenue", ascending=False).groupby("region").head(3). head keeps the first rows of each group in the current order.
- One row per group with idxmax:
df.loc[df.groupby("region")["revenue"].idxmax()] finds the row label of each group's maximum.
- Ties at the cut-off: when the third and fourth values are equal,
head(3) silently drops one. Rank within the group and keep ranks up to 3 to include everyone tied: df[df.groupby("dept")["salary"].rank(method="min", ascending=False) <= 3].
For totals per group (the top products by summed revenue), aggregate first, then apply the same patterns to the result.