In pandas, how do Series.rank's method options number tied revenues on a leaderboard, and what does pct=True change?
answer
- default splits the difference
- gaps after a tie, or none
- order of appearance breaks ties
- smallest gets rank 1 by default
- divide by count, or distinct count
basics
~20 sSeries.rank numbers values from 1, and method decides ties: 'average' (default) gives the mean rank, 'min' gives 1, 1, 3, 'dense' gives 1, 1, 2, 'max' the highest, 'first' order of appearance. pct=True rescales the ranks to fractions up to 1.
solid answer
~40 s`rank` gives rank 1 to the **smallest** value, so a leaderboard needs `ascending=False`. For tied revenues `method` decides the numbers: `'average'` (default) gives each tie the mean of their positions (1.5, 1.5), `'min'` the lowest (1, 1, 3 — competition ranking), `'max'` the highest, `'dense'` the lowest without gaps (1, 1, 2), and `'first'` breaks ties by order of appearance. NaN gets a NaN rank unless `na_option` is `'top'` or `'bottom'`. `pct=True` divides each rank by the number of non-missing values (with the default `na_option`) — except with `'dense'`, where it divides by the number of distinct values. A NumPy int or float column returns float64 ranks; in pandas 3.0 a nullable `Int64` column keeps `pd.NA` and returns `UInt64` (or `Float64` for `'average'` and `pct`).
code
python · 12 linesimport pandas as pd
revenue = pd.Series([1200, 950, 1200, 950, 400],
index=["Kettle", "Toaster", "Mixer", "Juicer", "Blender"])
board = pd.DataFrame({"revenue": revenue})
for method in ["average", "min", "max", "dense", "first"]:
board[method] = revenue.rank(method=method, ascending=False)
board["dense_pct"] = revenue.rank(method="dense", ascending=False, pct=True)
print(board)
print(revenue.rank(method="min").dtype)
print(revenue.astype("Int64").rank(method="min").dtype)go deeper
Remember that rank counts from 1 with the smallest value first, and that ascending=False puts the top seller at rank 1.
Explain each tie method with a concrete example, especially min against dense, and how pct=True and na_option change the output.
Show you know the traps: fractional default ranks, the float64 dtype, dense percentiles dividing by distinct values, and the 3.0 nullable result dtypes.
Settle which tie rule a team's leaderboards use and document it, because min, dense and first produce different places for the same data.
## What `rank` computes `Series.rank` (and `DataFrame.rank`, column by column) replaces each value with its **position in sorted order**, counting from 1. It returns an object of the same shape and index as the input, so the result can be assigned straight back as a column: ```python sales["place"] = sales["revenue"].rank(method="min", ascending=False) ``` The signature is `rank(axis=0, method="average", numeric_only=False, na_option="keep", ascending=True, pct=False)`. Two defaults catch people out: - `ascending=True` gives rank 1 to the **smallest** value. A leaderboard, where the top seller is first, needs `ascending=False`. - `method="average"` produces fractional ranks for ties, which surprises anyone expecting whole numbers. ## The five tie methods Take revenues `[1200, 950, 1200, 950, 400]` ranked with `ascending=False`: | `method` | ranks | rule for a tie | |---|---|---| | `'average'` (default) | 1.5, 3.5, 1.5, 3.5, 5 | mean of the positions the tie occupies | | `'min'` | 1, 3, 1, 3, 5 | lowest position; the next rank skips | | `'max'` | 2, 4, 2, 4, 5 | highest position the tie occupies | | `'dense'` | 1, 2, 1, 2, 3 | like `'min'`, but ranks rise by 1 between distinct values | | `'first'` | 1, 3, 2, 4, 5 | order of appearance in the Series | How to choose: - **`'min'`** is "competition ranking": two products tied for first, the next is third. It matches how many leaderboards and the SQL `RANK` function behave. - **`'dense'`** has no gaps, so the ranks count distinct revenue levels — useful for "the top three revenue levels", matching SQL's `DENSE_RANK`. - **`'first'`** gives every row a unique rank, which is what you need to number rows 1 to n; it breaks ties by position in the Series, and with `ascending=False` the earlier row still receives the lower rank. - **`'average'`** suits statistics, such as rank correlations, where ties should share the credit evenly. ## Missing values: `na_option` - `'keep'` (default): a NaN value gets a NaN rank and is not counted. - `'top'`: missing values receive the lowest ranks — first place. - `'bottom'`: missing values receive the highest ranks — last place. `'top'` and `'bottom'` refer to the ranking, so they hold whichever direction `ascending` sets. ## `pct=True`: percentile ranks With `pct=True` each rank is divided by a count, giving values between 0 and 1: 1. For `'average'`, `'min'`, `'max'` and `'first'`, the divisor is the number of **non-missing** values (with the default `na_option='keep'`). With five revenues, `method="min"` gives 0.2, 0.6, 0.2, 0.6, 1.0. 2. For `'dense'`, the divisor is the number of **distinct** non-missing values, again with `na_option='keep'`. With three revenue levels, the ranks become 1/3, 2/3 and 1. So `rank(pct=True, ascending=False) <= 0.1` marks the top tenth of rows, and the choice of method changes where ties fall around that line. ## The dtype of the result For an ordinary NumPy-backed column (int64, float64), `rank` returns **float64**, even for `method="min"` or `"dense"`, whose ranks are whole numbers. Displaying `1.0, 2.0` is harmless; to store integers while missing ranks may exist, cast with `astype("Int64")`, because `astype(int)` raises on NaN. In pandas 3.0, ranking a **nullable** column (`Int64`, `Float64`, `boolean`) keeps `pd.NA` for missing values and returns **`UInt64`** for `'min'`, `'max'`, `'dense'` and `'first'`, or **`Float64`** for `'average'` and for `pct=True`. pandas 2.x cast those results to float64 and turned `pd.NA` into NaN. ## Rank versus sort `rank` and `sort_values` answer different questions: - `sort_values` **reorders** the rows and leaves the values alone. - `rank` **keeps** the rows where they are and returns a new column of positions, aligned on the same index. A leaderboard usually wants both: compute the place with `rank(method="min", ascending=False)`, assign it as a column, then `sort_values("place")` to print it in order. Because the rank column is aligned on the index, it lands on the right rows no matter how the frame is ordered later. And unlike `head(n)` after a sort, a filter such as `place <= 3` keeps every product tied for third place. ## Scope Ranking **within** groups — "the rank of each product inside its region" — uses the groupby version of `rank` and belongs with group transforms. `Series.rank` ranks against the whole column.
- How do you number rows 1 to n by revenue with no shared ranks?Use `rank(method='first', ascending=False)`: every row gets a unique rank, and ties are broken by position in the Series, earlier rows first. If the tie-break should follow another column instead, sort by both columns first, then rank with `'first'`.
- Why are the dense percentile ranks different from the min percentile ranks on the same data?With `pct=True`, `'dense'` divides by the number of distinct values, while `'min'` divides by the number of non-missing values. Five revenues with three distinct levels give dense ranks 1/3, 2/3, 1, but min ranks 0.2, 0.6, 1.0.
- How do you turn rank output into integers when some revenues are missing?The float64 result holds NaN for missing values, so `astype(int)` raises. Cast with `astype('Int64')`, which stores whole numbers and `pd.NA`. In pandas 3.0, starting from a nullable `Int64` column already gives `UInt64` ranks for the whole-number methods.
A race result: two runners crossing the line together are both listed first and the next finisher third, which is method='min'; a podium that hands out gold, gold, silver for the same finish is method='dense'.
- rank gives rank 1 to the largest value by default
- method='dense' leaves gaps after a tie
- rank with method='min' returns an integer dtype for an int64 column
- With the default na_option, pct=True divides by a row count that includes missing values
- method='first' gives tied values the same rank
Assumes pandas 3.0: rank on nullable Int64, Float64 or boolean columns keeps pd.NA and returns UInt64 (Float64 for average or pct), where 2.x returned float64 with NaN.