Leaderboards
Add a leaderboard position to a DataFrame column, choosing how equal scores share ranks.
Polars · Module
Assign ranks to expression values while handling ties through configurable methods. It can rank ascending or descending and can be scoped to groups with over.
Calling rank on an expression produces an expression containing ranks for the non-null values. Choose a tie strategy with method, optionally reverse the ordering with descending, and provide seed when using random tie assignment; combine it with over to rank within groups.
Expr.rank(method: RankMethod = 'average', *, descending: bool = False, seed: int | None = None) → Expr| Name | Type | Description |
|---|---|---|
method | RankMethod = 'average' | Tie-ranking strategy: average, min, max, dense, ordinal, or random. |
descending | bool = False | Rank in descending order when true. |
seed | int | None = None | Seed used when method is random. |
Expr
import polars as pl
df = pl.DataFrame({"group": ["a", "a", "b"], "value": [10, 10, 5]})
result = df.with_columns(
pl.col("value").rank(method="dense").over("group").alias("rank")
)
print(result)Ranks values within each group using dense ranking, so tied values share a rank and the next rank is consecutive.
Add a leaderboard position to a DataFrame column, choosing how equal scores share ranks.
Compute per-category positions by combining rank with over.
Create deterministic distinct ordering for ties with ordinal ranking.
rank assigns ordered rank values while applying the selected method to ties. The default method is average, and descending reverses the ranking direction.
Follow-up: How would you rank independently within categories? Use the rank expression with over, such as pl.col("score").rank().over("category").
The methods are average, min, max, dense, ordinal, and random. Ordinal gives every value a distinct rank based on occurrence order, whereas random breaks ties without depending on that order.
Follow-up: Which method gives consecutive ranks after ties? Dense ranking: tied values receive the minimum-style rank, and the next distinct value receives the immediately following rank.
The method returns an Expr, so it can be used inside select or with_columns and combined with windowing through over. Only non-null values receive ranks; nulls are preserved.
Follow-up: What should you verify when ranking grouped data with nulls? Confirm that the ranking is scoped with over and that null entries remain null within each group.
polars.Expr.rolling_rankpolars.Expr.overpolars.Expr.sort