Pandas data engineering interview problem. Difficulty: intermediate. Pattern: Window Functions. About 14 minutes. Part of the Pro drill bank.
Top 2 products by revenue in each category, keeping products that tie for second place. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.
df has category, product and revenue. For each category return the products with the 2 highest revenues. Products that tie with the 2nd highest revenue are all kept, so a category can return more than 2 rows. A category with fewer than 2 products returns what it has. Columns: category, product, revenue. Sort by category, then revenue descending, then product. Reset the index. Assign the DataFrame to result.
Input: df category | product | revenue A | p1 | 100 A | p2 | 90 A | p3 | 90 A | p4 | 50 B | p5 | 70 B | p6 | 30 C | p7 | 10 Output: category | product | revenue A | p1 | 100 A | p2 | 90 A | p3 | 90 B | p5 | 70 B | p6 | 30 C | p7 | 10 Category A returns three rows because p2 and p3 tie for second place. B returns both its products and C its only one.
Topics: lakebench, pandas, groupby, rank, ties.
More interview problems · All interview problems · Learn data engineering
Interview-style drill: Top 2 products by revenue in each category, keeping products that tie for second place.
`df` has `category`, `product` and `revenue`. For each category return the products with the 2 highest revenues. Products that tie with the 2nd highest revenue are all kept, so a category can return more than 2 rows. A category with fewer than 2 products returns what it has. Columns: `category`, `product`, `revenue`. Sort by `category`, then revenue descending, then product. Reset the index. Assign the DataFrame to `result`.