Create labeled ranges
Transform numeric measurements into named ranges for reporting or downstream grouping.
Polars · Module
Bins continuous expression values into discrete categories using explicit breakpoints. It can return labeled categories or include each value’s bin endpoint.
Use Expr.cut to map continuous expression values into discrete bins defined by unique breakpoints. By default it returns an Enum expression; requesting breakpoints adds the bin endpoint and changes the result to a Struct.
Expr.cut(breaks: Sequence[float], *, labels: Sequence[str_] | None = None, left_closed: bool = False, include_breaks: bool = False) → Expr| Name | Type | Description |
|---|---|---|
breaks | Sequence[float] | Unique numeric cut points defining the bin boundaries. |
labels | Sequence[str_] | None = None | Category names; the count must be the number of breaks plus one. The documentation also describes False for integer bin indexes. |
left_closed | bool = False | Whether intervals use the left boundary as closed rather than the default right boundary. |
include_breaks | bool = False | Whether to include the selected bin’s right endpoint in the output. |
Expr of data type Enum by default, or Struct when include_breaks=True.
breaks argument must contain unique numeric cut points.left_closed=True when interval membership should include the left boundary.include_breaks=True adds each observation’s bin endpoint to the result.bin_intervals() for new code.False selecting integer bin indexes.import polars as pl
df = pl.DataFrame({"score": [-2, -1, 0, 1, 2]})
result = df.with_columns(
pl.col("score")
.cut([-1, 1], labels=["low", "medium", "high"])
.alias("band")
)
print(result)Assigns each score to one of three labeled intervals.
Transform numeric measurements into named ranges for reporting or downstream grouping.
Retain the boundary associated with each value for audit or analysis.
Use integer category identifiers instead of textual labels.
Expr.cut do?cut takes unique numeric breakpoints and assigns each value to a discrete interval. It returns an Enum expression unless include_breaks=True, which produces a Struct containing the category and right endpoint.
Follow-up: How would you preserve the endpoint in the result? Set include_breaks=True; the output type changes from Enum to Struct.
The labels sequence names the resulting categories. Its length must equal the number of breakpoints plus one, because breakpoints divide the value range into that many bins.
Follow-up: What if integer bin identifiers are preferred? The documentation specifies passing labels=False for the integer bin index.
Intervals are right-closed by default. Set left_closed=True to make them left-closed instead.
Follow-up: How can the newer behavior retain right-closed cut bins? The documentation says to use bin_intervals() with right_closed=True.
polars.Expr.bin_intervalspolars.Series.cutpolars.Expr.qcut