polars.Series.bin_intervals#

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

Bin values into discrete intervals delimited by breakpoints.

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

Series 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

>>> s = pl.Series("foo", [-2, -1, 0, 1, 2])
>>> s.bin_intervals([-1, 1], labels=["a", "b", "c"])
shape: (5,)
Series: 'foo' [enum]
[
    "a"
    "b"
    "b"
    "c"
    "c"
]