polars.Expr.bin_quantiles#

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

Bin values into discrete intervals delimited by quantiles of the data.

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:
quantiles

Non-decreasing quantiles in [0, 1], or a positive integer giving the number of bins. Two equal quantiles delimit an empty bin. Input must be numeric. For quantile q, the value of the breakpoint is the sorted value at floor(q * (len - 1)).

labels

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

include_intervals

Return a struct with fields bin, left, and right. The first bin’s left and last bin’s right boundary are null.

right_closed

Use right-closed (left, right] rather than left-closed [left, right) bins.

Returns:
Expr

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

Notes

Breakpoints are input values and are computed per group in group and window contexts. The integer form is computed directly rather than by expanding it to potentially inexact floating-point quantiles.

Examples

Unlike bin_ranks(), all equal values remain in the same bin, so a bin can be empty. Here the breakpoints are 1, 1, and 2, giving the bins [-inf, 1), [1, 1), [1, 2), and [2, inf). The first is empty because a left-closed bin excludes its right boundary, and the second because the breakpoint 1 repeats.

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