Skip to content

Bin

Base classes

Name Children Inherits
SeriesOp
datacook.engine.ops.series
A `ColumnOp` that is one call per column, declared like `CallOp`.

⋔ Inheritance diagram

graph TD
  2892175340["stats.Bin"]
  2451904138["series.SeriesOp"]
  124287307["series.ColumnOp"]
  1539482213["base.Op"]
  2751680898["builtins.object"]
  2451904138 --> 2892175340
  124287307 --> 2451904138
  1539482213 --> 124287307
  2751680898 --> 1539482213

🛈 DocStrings

Bases: SeriesOp

pd.cut: equal-width bins (a number) or bins between edges (a list).

Source code in src/datacook/engine/ops/stats.py
class Bin(series.SeriesOp):
    """`pd.cut`: equal-width bins (a number) or bins between edges (a list)."""

    id = "cut"
    title = _("Bin values")
    description = _(
        "Put numbers into intervals: a number of equal-width bins, or bins between given"
        " edges (histogram classes)."
    )
    category = categories.STATS
    icon = "mdi.chart-histogram"
    function = "pd.cut"
    positional = ("bins",)

    class Params(series.ColumnParams):
        suffix: str = Field(
            "_bin",
            title=N_("Suffix for new columns"),
            description=N_("Empty: replace the columns. Otherwise the results are new columns."),
        )
        bins: int | list[float] = Field(
            title=N_("Bins"),
            description=N_("A number of equal-width bins, or the bin edges (ascending)."),
        )
        right: bool = Field(True, title=N_("Bins include their right edge"))
        include_lowest: bool = Field(False, title=N_("First bin includes its left edge"))
        labels: list[str] | None = Field(
            None, title=N_("Labels"), description=N_("One per bin; empty: the intervals.")
        )
        precision: int = Field(3, title=N_("Precision of the interval labels"), ge=0)

        @model_validator(mode="after")
        def _check_bins(self) -> Self:
            if isinstance(self.bins, int):
                if self.bins < 1:
                    raise ValueError("at least one bin")
                n = self.bins
            else:
                if (
                    len(self.bins) < 2  # noqa: PLR2004
                    or any(a >= b for a, b in zip(self.bins, self.bins[1:]))
                ):
                    raise ValueError("bin edges: at least two, ascending")
                n = len(self.bins) - 1
            if self.labels is not None and len(self.labels) != n:
                raise ValueError(f"{n} labels needed")
            return self

:fa-brands-github: Show source on GitHub