polars.Expr.bin_ranks#

Expr.bin_ranks(
ranks: Sequence[float] | int,
*,
labels: Sequence[str_] | Literal[False],
include_intervals: bool = False,
) Expr[source]#

Bin values by their position in sorted order.

Input must have an orderable data type; nested types (List, Array, and Struct) are not supported.

engine:In MemoryStreaming

Warning

This functionality is considered experimental. It may be removed or changed at any point without it being considered a breaking change.

Parameters:
ranks

Non-decreasing cumulative fractions in [0, 1], or a positive integer giving the number of near-equal-sized bins. Two equal fractions delimit an empty bin. For an integer, earlier bins receive any remainder.

labels

One label per bin, or False to return the integer bin index.

include_intervals

Return a struct with fields bin, left, and right. Boundaries are input values, not ranks; the first bin’s left and last bin’s right boundary are null.

Returns:
Expr

Expression of data type Enum, or UInt32 if labels is False, or Struct if include_intervals is set.

Notes

Membership is positional, so equal values may be split across adjacent bins in input order. Bins are computed per group in group and window contexts.

Examples

Unlike bin_quantiles(), rank bins may split equal values. Here, the bins contain 25%, 50%, and 25% of the values.

>>> df = pl.DataFrame({"x": [1, 1, 2, 2]})
>>> df.with_columns(
...     pl.col("x")
...     .bin_ranks([0.25, 0.75], labels=["low", "mid", "high"])
...     .alias("bin")
... )
shape: (4, 2)
┌─────┬──────┐
│ x   ┆ bin  │
│ --- ┆ ---  │
│ i64 ┆ enum │
╞═════╪══════╡
│ 1   ┆ low  │
│ 1   ┆ mid  │
│ 2   ┆ mid  │
│ 2   ┆ high │
└─────┴──────┘