rank
s.rank() assigns each value its position when sorted, 1 for the smallest; ascending=False gives 1 to the largest. Ties get the average rank by default; method="min" gives tied values the same lowest rank and method="dense" does that without skipping numbers.
Syntax
Series.rank(method="average", ascending=True, pct=False, na_option="keep")| Part | What it is |
|---|---|
method | "average" (default), "min", "max", "first" or "dense" for how ties are ranked |
ascending | False ranks the largest value 1 |
pct | True returns the percentile rank between 0 and 1 |
na_option | "keep" leaves NaN, "top" or "bottom" ranks them first or last |
Examples
import pandas as pd
df = pd.DataFrame({"name": ["Ana", "Ben", "Cara", "Dan"], "score": [90, 85, 90, 70]})
df["rank"] = df["score"].rank(ascending=False)
dfResult: name score rank 0 Ana 90 1.5 1 Ben 85 3.0 2 Cara 90 1.5 3 Dan 70 4.0
Ana and Cara tie for ranks 1 and 2 and get the average, 1.5.
df["score"].rank(ascending=False, method="min").astype(int).tolist()Result: [1, 3, 1, 4]
Competition ranking: both leaders are 1, the next is 3.
df["score"].rank(ascending=False, method="dense").astype(int).tolist()Result: [1, 2, 1, 3]
Common mistakes
- Ranks are floats like 1.5: that is the average tie method; use method="min", "dense" or "first" and astype(int) for whole numbers.
- Rank 1 is the smallest value when you wanted the largest: add ascending=False.
- NaN rows get NaN ranks and break astype(int); use na_option="bottom" or fill them first.
Practice rank
These drills check your answer on live data, free, no account needed.
- Rank with tiesRank the reps by `revenue`, highest first, so the top rep gets 1. Tied reps share the lower rank number (two reps tied for second both get 2, and the next rep gets 4).
- Top three earnersReturn the three highest-paid employees with only the `name` and `salary` columns, highest salary first.
Questions
How do I get the top N per group?
Rank within the group with method="first", then filter: df[df.groupby("k")["v"].rank(ascending=False, method="first") <= 3].
What is the SQL equivalent?
method="min" matches RANK(), "dense" matches DENSE_RANK() and "first" matches ROW_NUMBER().
Related
- sort_valuesHow to sort a pandas DataFrame with sort_values: ascending and descending, several columns with mixed order, NaN first, sort by index and reset the index.
- groupbyHow groupby works in pandas: group by one or more columns, apply sum, mean, count or size, get a flat table with as_index=False, and iterate over groups.
- cut and qcutHow to bin numeric data in pandas: pd.cut for fixed ranges with labels like age bands, pd.qcut for equal-sized quantile groups, right-closed edges and labels.
- idxmax and idxminHow to find which row holds the maximum or minimum in pandas with idxmax and idxmin, pull the full row with loc, get the max per group, and idxmax vs argmax.