Sub topic 8
Ranking values
This chapter assumes you can build a DataFrame, select a column as a Series, and use sort_values. It builds on the sales DataFrame from earlier chapters.
What rank does
rank returns a Series of the same length and index as the input. Each entry is the position of that value in sorted order. Unlike sort_values, it does not reorder rows. You get a new column you can keep, filter on or sort by later.
import pandas as pd
df = pd.DataFrame({
"region": ["North", "South", "North", "East", "South", "East"],
"product": ["A", "B", "B", "A", "A", "B"],
"units": [10, 5, None, 8, 12, 7],
"price": [2.5, 4.0, 4.0, 2.5, 2.5, 4.0],
})
df["units_rank"] = df["units"].rank(method="dense", ascending=False)
print(df[["units", "units_rank"]])By default, rank gives the smallest value rank 1. Passing ascending=False gives the largest value rank 1. The result is a float column (2.0, 5.0, NaN, 3.0, 1.0, 4.0) because the missing value stays NaN.
Choosing a tie method
Ties are where rank needs a decision. In the price column, three rows share 2.5 and three share 4.0. The method argument controls what they receive.
ties = pd.DataFrame({"price": df["price"]})
for m in ["average", "min", "max", "first", "dense"]:
ties[m] = df["price"].rank(method=m)
print(ties)| Row | price | average | min | max | first | dense |
|---|---|---|---|---|---|---|
| 0 | 2.5 | 2.0 | 1.0 | 3.0 | 1.0 | 1.0 |
| 1 | 4.0 | 5.0 | 4.0 | 6.0 | 4.0 | 2.0 |
| 2 | 4.0 | 5.0 | 4.0 | 6.0 | 5.0 | 2.0 |
| 3 | 2.5 | 2.0 | 1.0 | 3.0 | 2.0 | 1.0 |
| 4 | 2.5 | 2.0 | 1.0 | 3.0 | 3.0 | 1.0 |
| 5 | 4.0 | 5.0 | 4.0 | 6.0 | 6.0 | 2.0 |
averageis the default. Tied rows share the mean of the positions they occupy.mingives every tied row the lowest position. This is the usual "competition" ranking (1, 1, 3).maxgives every tied row the highest position.firstbreaks ties by order of appearance, so no two rows share a rank.densegives tied rows the same rank and never skips numbers afterwards.
Missing values
The na_option argument controls missing values. The default, "keep", leaves them as NaN. Use "bottom" or "top" to give them the last or first ranks. The same ranking logic applies to them as to any other value.
Ranking within groups and as percentages
Call rank on a grouped column to restart the ranking inside each group. Here, each row is ranked by units within its region.
df["rank_in_region"] = df.groupby("region")["units"].rank(ascending=False)
print(df[["region", "units", "rank_in_region"]])The ranks are 1, 2, NaN, 1, 1, 2. North's missing value stays NaN, and its other row is ranked 1.
Add pct=True to get each rank as a fraction of the number of ranked rows, between 0 and 1. This is useful for percentile-style comparisons.
Common errors
- Expecting
rankto sort. The rows stay in their original order. Follow it withsort_values("units_rank")if you need that. - Forgetting
ascending=False. For "top seller" rankings, the biggest value should usually be 1. - Treating the float result as integers. If you need integers, drop or fill the
NaNvalues first, then call.astype(int). - Using
rankwhen you only need the top few rows.nlargestis shorter for that.
Exercise
For s = pd.Series([30, 10, 30, 20]), what does s.rank(method="min", ascending=False) return?
Show answer
[1.0, 4.0, 1.0, 3.0]. Both 30s tie for first and receive the minimum position, 1. The value 20 is third in descending order, so it gets 3. The value 10 is last, so it gets 4. Rank 2 is skipped because two rows share rank 1.