Python
All Top 50 Python & Pandas Interview Questions#40
Select Top N Records Per Group with nlargest() in Pandas
MediumAmazonInterview Question #40
Asked at AmazonGiven an e-commerce catalog, select the top 2 highest-priced products for each `department`.
Input Table: products
4 rows preview| product_id | department | price |
|---|---|---|
| 1 | Tech | 1200 |
| 2 | Tech | 800 |
| 3 | Tech | 400 |
| 4 | Books | 35 |
Expected Output Structure3 rows
| department | product_id | price |
|---|---|---|
| Tech | 1 | 1200 |
| Tech | 2 | 800 |
| Books | 4 | 35 |
Interview Context
Asked frequently in data analyst and business analyst technical rounds. Focus on clean filtering, optimal indexing usage, and unambiguous column selection.
Python 3.10 (Pandas)
Environment Ready
Click "Run & Test" to execute your Pandas code against the test assertions.