Dense rank within a group
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
Rank every salary in `pay` within its department, with 1 for the highest salary. People with the same salary share a rank, and the next lower salary gets the next rank with no gap (1, 1, 2, not 1, 1, 3). Return the ranks as a Series aligned with the original rows.
What this exercise teaches
rank on a groupby restarts the numbering in every group and keeps the result aligned with the original rows. The method decides what ties get: the default is the average of their positions, min leaves a gap after them, and dense does not. This is DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) in SQL.
A hint if you get stuck
rank works on a grouped column too. method="dense" gives ties the same rank without leaving a gap, and ascending=False makes the highest value number 1.
Try it now, free, no account needed
Your first 8 exercises 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 unlocks every exercise, timed mode and the certificate.
Open this exerciseMore exercises in Analysis
- Rolling average
- Month over month growth
- Running total
- Rank with ties
- Change from the previous period
- Monthly totals with resample
- Quartile bins with qcut
- Age bands with cut
- Classify with apply
- Running total per group
- Top two orders per region
- Monthly totals with to_period
- Days since the previous order
- Label rows with np.where
- First order per customer
- Drawdown from the running high