Sub topic 8
Ranking values
This chapter assumes you can build a DataFrame, select a column as a Series, and use sort_values and nlargest. It covers rank, which turns values into positions without reordering any rows.
What rank does
Series.rank() returns a new Series of the same length and index. Each entry is the position of that value in the sorted order of the column. Row order does not change, so you can store the result as a new column and keep the original layout.
Two points trip people up:
- By default the smallest value gets rank 1. For "largest is first" you must pass
ascending=False. - The result has a float dtype, even when every rank is a whole number. Missing values stay as
NaN, and integer dtype cannot holdNaN.
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)The largest value, 12 units, gets rank 1. The next is 10, which gets rank 2, and so on down to 5 units at rank 5. The row with a missing value gets NaN in units_rank.
Rank versus sort
Sorting reorders rows. Ranking labels them. The two are related, because sorting by a rank column gives the same row order as sorting by the original column, with ties placed according to the method you chose.
| Task | Tool | Row order changes |
|---|---|---|
| Show rows from largest to smallest | `sort_values` | Yes |
| Keep the three largest rows | `nlargest` | Yes |
| Add a position column and keep the layout | `rank` | No |
Use rank when the position is itself data. Examples are a leaderboard column, a percentile feature, or a "top 1 per group" filter.
Handling ties
Real data has repeated values, and the method argument decides what rank each tied value gets. Here is a small Series with a tie.
import pandas as pd
scores = pd.Series([90, 85, 85, 70, None], index=list("abcde"))
methods = ["average", "min", "max", "first", "dense"]
ranks = pd.DataFrame(
{m: scores.rank(method=m, ascending=False) for m in methods}
)
print(ranks)Rows b and c both hold 85. This table shows the ranks for the non-missing rows.
| Row | Score | average | min | max | first | dense |
|---|---|---|---|---|---|---|
| a | 90 | 1.0 | 1.0 | 1.0 | 1.0 | 1.0 |
| b | 85 | 2.5 | 2.0 | 3.0 | 2.0 | 2.0 |
| c | 85 | 2.5 | 2.0 | 3.0 | 3.0 | 2.0 |
| d | 70 | 4.0 | 4.0 | 4.0 | 4.0 | 3.0 |
The methods behave as follows:
averageis the default. Tied rows share the mean of the positions they occupy, which is why you see 2.5.mingives every tied row the lowest position in the group. This is the "competition" style used in sports, where two silver medals are followed by a bronze at position 4.maxgives every tied row the highest position in the group.firstbreaks ties by order of appearance, so every row gets a unique rank from 1 to n.denseis likeminbut leaves no gaps. The row after a tie gets the next integer.
The choice matters downstream. If you filter with rank <= 3, min can return more than three rows when there is a tie, first returns exactly three, and dense returns every row among the top three distinct values.
Missing values
By default, rank leaves missing values as NaN and ignores them when computing positions. The na_option argument changes this:
"keep"is the default. The result isNaN."top"treats missing values as the smallest, so they take the first ranks."bottom"treats missing values as the largest, so they take the last ranks.
Note that "top" and "bottom" refer to ascending order. With ascending=False, "bottom" still gives the missing values the numerically largest ranks, but they no longer sit at the end of a descending sort. Check the result on a small example before relying on it.
import pandas as pd
scores = pd.Series([90, 85, 85, 70, None], index=list("abcde"))
print(scores.rank(method="min", ascending=False, na_option="bottom"))Row e now gets rank 5.0 instead of NaN. Prefer the default "keep" when the missing values mean "unknown", because a rank for an unknown value looks like real information. Use "bottom" only when a missing value really should count as last.
Percentile ranks with pct
pct=True returns the rank as a fraction between 0 and 1. The rank is divided by the number of non-missing values, so the largest rank becomes 1.0.
import pandas as pd
scores = pd.Series([90, 85, 85, 70, None], index=list("abcde"))
print(scores.rank(method="min", ascending=False, pct=True))There are four non-missing values, so the ranks 1, 2, 2 and 4 become 0.25, 0.5, 0.5 and 1.0. The missing value stays NaN. This is useful for features such as "this order is in the top 25% of units".
Ranking within groups
groupby objects have their own rank. It ranks each group separately and returns a Series aligned to the original rows, in the same way as transform.
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["rank_in_region"] = (
df.groupby("region")["units"].rank(method="first", ascending=False)
)
print(df)
best_per_region = df[df["rank_in_region"] == 1]
print(best_per_region)The rank_in_region column holds 1.0, 2.0, NaN, 1.0, 1.0, 2.0 for rows 0 to 5. The NaN belongs to the North row with missing units. The filter then keeps one row per region with a value: row 0 for North, row 4 for South and row 3 for East.
Using method="first" guarantees at most one row per group with rank 1. With min, a tie for first place would keep several rows per group.
Converting ranks to integers
When you use first, min, max or dense, every rank is a whole number. If there are no missing values you can convert with astype(int). If there are, use the nullable integer type, which keeps the missing entries as <NA>.
import pandas as pd
units = pd.Series([10, 5, None, 8, 12, 7])
ranks = units.rank(method="first", ascending=False).astype("Int64")
print(ranks)Do not do this with method="average" when ties exist, because 2.5 cannot be converted to an integer and pandas raises an error.
Common mistakes
- Forgetting
ascending=Falseand getting rank 1 for the smallest value. - Reading the default
averageranks as integers. Half-values signal ties. - Filtering
rank <= nand assuming you get exactlynrows. Ties can add rows or, withdense, many rows. - Ranking across the whole DataFrame when you meant per group. Call
groupby(...).rank()for the second case. - Expecting
rankto sort. It never reorders rows, so callsort_valueson the rank column if you need that.
Exercise
A Series is s = pd.Series([4, 7, 7, 9]). What does s.rank(method="min", ascending=False) return, and what does method="dense" return instead?
Show answer
With method="min" and ascending=False the ranks are 4.0, 2.0, 2.0, 1.0. The value 9 is first, the two 7s share position 2, and 4 is at position 4. With method="dense" the ranks are 3.0, 2.0, 2.0, 1.0, because no number is skipped after the tie.
Exercise
Using the sales DataFrame with region and units columns, write one expression that adds a column rank_in_region giving 1 to the row with the most units in each region, with exactly one rank 1 per region that has data. Which method do you choose and why?
Show answer
df["rank_in_region"] = df.groupby("region")["units"].rank(method="first", ascending=False). The first method breaks ties by order of appearance, so each region has a single row with rank 1. Missing units stay NaN.