polars.Expr.bin_intervals#

Expr.bin_intervals(
intervals: Sequence[Any] | Series | int,
*,
labels: Sequence[str_] | Literal[False],
include_intervals: bool = False,
right_closed: bool = False,
) → Expr[source]#

Bin values into discrete intervals delimited by breakpoints.

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

Strictly ascending breakpoints, or a positive integer giving the number of equal-width bins over [min, max]. Explicit breakpoints may have any orderable (non-nested) data type; an integer requires numeric input.

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

Explicit breakpoints make this elementwise. An integer derives breakpoints from the data, so bins are computed per group in group and window contexts.

A derived breakpoint is rounded to a value the input data type can represent, so membership right at a bin edge depends on the data type.

Examples

>>> df = pl.DataFrame({"foo": [-2, -1, 0, 1, 2]})
>>> df.with_columns(
...     pl.col("foo")
...     .bin_intervals([-1, 1], labels=["a", "b", "c"])
...     .alias("bin")
... )
shape: (5, 2)
┌─────┬──────┐
│ foo ┆ bin  │
│ --- ┆ ---  │
│ i64 ┆ enum │
╞═════╪══════╡
│ -2  ┆ a    │
│ -1  ┆ b    │
│ 0   ┆ b    │
│ 1   ┆ c    │
│ 2   ┆ c    │
└─────┴──────┘