polars.Expr.bin_quantiles#
- Expr.bin_quantiles(
- quantiles: Sequence[float] | int,
- *,
- labels: Sequence[str_] | Literal[False],
- include_intervals: bool = False,
- right_closed: bool = False,
Bin values into discrete intervals delimited by quantiles of the data.
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 quantileq, the value of the breakpoint is the sorted value atfloor(q * (len - 1)).- labels
One label per bin, or
Falseto return the integer bin index.- include_intervals
Return a struct with fields
bin,left, andright. 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, orUInt32iflabelsisFalse, orStructifinclude_intervalsis set.
See also
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 are1,1, and2, 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 breakpoint1repeats.>>> 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 │ └─────┴──────┘