Skip to content

SeriesOp

Sub classes

Name Children Inherits
_CategoryOp
datacook.engine.ops.categorical
ToDatetime
datacook.engine.ops.dates
    Strftime
    datacook.engine.ops.dates
      TzLocalize
      datacook.engine.ops.dates
        TzConvert
        datacook.engine.ops.dates
          RoundTime
          datacook.engine.ops.dates
            FillForward
            datacook.engine.ops.missing
            Interpolate
            datacook.engine.ops.missing
              Rank
              datacook.engine.ops.stats
                Bin
                datacook.engine.ops.stats
                `pd.cut`: equal-width bins (a number) or bins between edges (a list).
                  TextOp
                  datacook.engine.ops.strings
                  Shift
                  datacook.engine.ops.timeseries
                    Diff
                    datacook.engine.ops.timeseries
                      PctChange
                      datacook.engine.ops.timeseries
                        Abs
                        datacook.engine.ops.values
                          Clip
                          datacook.engine.ops.values

                            Base classes

                            Name Children Inherits
                            ColumnOp
                            datacook.engine.ops.series
                            The base of all per-column ops: one series per selected column, put back by `assign()`.

                            â‹” Inheritance diagram

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

                            🛈 DocStrings

                            Bases: ColumnOp

                            A ColumnOp that is one call per column, declared like CallOp.

                            • accessor ("str", "dt", "cat" or None) + method: df["a"].str.upper();
                            • or function (dotted name; pd = pandas): pd.to_datetime(df["a"], ...);
                            • method_param: a param whose value picks the method (methods maps values to method names, default: the value itself); it is not passed to the call.

                            Params in positional are passed positionally, the others as keywords when they differ from their default (or are listed in always). The selection params (columns, column, suffix) are never passed.

                            frame_call = True: the method works on a frame column by column (abs, clip, ffill), so the code calls it once on the selected columns and puts the result back, out = a.assign(**a[["x", "y"]].clip(lower=0)), or on the whole frame when the columns field allows None (out = a.ffill()). No accessor, function or suffix then.

                            Source code in src/datacook/engine/ops/series.py
                            class SeriesOp(ColumnOp):
                                """A `ColumnOp` that is one call per column, declared like `CallOp`.
                            
                                - `accessor` (`"str"`, `"dt"`, `"cat"` or None) + `method`: `df["a"].str.upper()`;
                                - or `function` (dotted name; `pd` = pandas): `pd.to_datetime(df["a"], ...)`;
                                - `method_param`: a param whose value picks the method (`methods` maps values to
                                  method names, default: the value itself); it is not passed to the call.
                            
                                Params in `positional` are passed positionally, the others as keywords when they differ
                                from their default (or are listed in `always`). The selection params (`columns`,
                                `column`, `suffix`) are never passed.
                            
                                `frame_call = True`: the method works on a frame column by column (`abs`, `clip`,
                                `ffill`), so the code calls it once on the selected columns and puts the result back,
                                `out = a.assign(**a[["x", "y"]].clip(lower=0))`, or on the whole frame when the
                                `columns` field allows None (`out = a.ffill()`). No accessor, function or suffix then.
                                """
                            
                                accessor: ClassVar[str | None] = None
                                method: ClassVar[str | None] = None
                                method_param: ClassVar[str | None] = None
                                methods: ClassVar[Mapping[str, str]] = {}
                                function: ClassVar[str | None] = None
                                positional: ClassVar[tuple[str, ...]] = ()
                                always: ClassVar[tuple[str, ...]] = ()
                                frame_call: ClassVar[bool] = False
                            
                                @classmethod
                                def method_name(cls, params: Any) -> str:
                                    if cls.method_param is not None:
                                        value = getattr(params, cls.method_param)
                                        return cls.methods.get(value, value)
                                    assert cls.method is not None
                                    return cls.method
                            
                                @classmethod
                                def call_args(cls, params: Any) -> tuple[list[Any], dict[str, Any]]:
                                    skip = (*SELECTION, cls.method_param) if cls.method_param else SELECTION
                                    return base.call_arguments(params, cls.positional, cls.always, skip)
                            
                                @classmethod
                                def call(cls, params: Any, obj: Any) -> Any:
                                    """The declared call on a series (or, with `frame_call`, a frame)."""
                                    args, kwargs = cls.call_args(params)
                                    if cls.function is not None:
                                        module, _sep, name = cls.function.rpartition(".")
                                        func = getattr(importlib.import_module({"pd": "pandas"}.get(module, module)), name)
                                        return func(obj, *args, **kwargs)
                                    if cls.accessor is not None:
                                        obj = getattr(obj, cls.accessor)
                                    return getattr(obj, cls.method_name(params))(*args, **kwargs)
                            
                                @classmethod
                                def call_code(cls, params: Any, source: str, indent: int = 0) -> str:
                                    """Code of `call()` on the expression `source`."""
                                    args, kwargs = cls.call_args(params)
                                    if cls.function is not None:
                                        return base.format_call(
                                            cls.function, [source, *map(base.literal, args)], kwargs, indent
                                        )
                                    prefix = f"{source}.{cls.accessor}" if cls.accessor is not None else source
                                    func = f"{prefix}.{cls.method_name(params)}"
                                    return base.format_call(func, list(map(base.literal, args)), kwargs, indent)
                            
                                @classmethod
                                def series(cls, params: Any, frame: Frame, column: str) -> pd.Series:
                                    return cls.call(params, frame[column])
                            
                                @classmethod
                                def expr(cls, params: Any, var: str, column: str) -> str:
                                    return cls.call_code(params, column_code(var, column))
                            
                                @classmethod
                                def apply(cls, params: Any, *inputs: Frame) -> Frame:
                                    if not cls.frame_call:
                                        return super().apply(params, *inputs)
                                    frame = inputs[0]
                                    columns = cls.selected(params)
                                    if columns is None:
                                        return cls.call(params, frame)
                                    missing = [c for c in columns if c not in frame.columns]
                                    if missing:
                                        raise base.OpError(f"unknown columns: {missing}")
                                    return frame.assign(**cls.call(params, frame[columns]))
                            
                                @classmethod
                                def to_code(cls, params: Any, inputs: Sequence[str], output: str) -> str:
                                    if not cls.frame_call:
                                        return super().to_code(params, inputs, output)
                                    var = inputs[0]
                                    columns = cls.selected(params)
                                    if columns is None:
                                        return f"{output} = {cls.call_code(params, var, len(output) + 3)}"
                                    prefix = f"{output} = {var}.assign(**"
                                    call = cls.call_code(params, f"{var}[{base.literal(columns)}]", len(prefix))
                                    return f"{prefix}{call})"
                            
                                @classmethod
                                def from_code(cls, stmt: ast.stmt, bound: Mapping[str, Any]) -> base.Match | None:
                                    if not cls.frame_call:
                                        return super().from_code(stmt, bound)
                                    found = frame_call(stmt, bound)
                                    if found is None:
                                        return None
                                    output, var, columns, call = found
                                    options = cls._call_options(call)
                                    selection = cls.selection(columns)
                                    if options is None or selection is None:
                                        return None
                                    params = cls.Params(**selection, **options)
                                    return base.Match(params, (var,), output)  # like `CallOp`: `clip(upper=2)` is fine
                            
                                @classmethod
                                def _call_options(cls, call: Link) -> dict[str, Any] | None:
                                    """The params (besides the selection) of a recognised call link; None if not this op."""
                                    options = cls._method_options(call.name)
                                    if options is None:
                                        return None
                                    try:
                                        args, kwargs = call.literal_args()
                                    except ValueError:  # not literal: user code
                                        return None
                                    if len(args) > len(cls.positional):
                                        return None
                                    if not set(kwargs) <= set(cls.Params.model_fields):
                                        return None  # like `CallOp`: `df.ffill(axis=1)` is user code
                                    options.update(zip(cls.positional, args))
                                    options.update(kwargs)
                                    return options
                            
                                @classmethod
                                def _method_options(cls, name: str) -> dict[str, Any] | None:
                                    if cls.method_param is None:
                                        return {} if name == cls.method else None
                                    reverse = {v: k for k, v in cls.methods.items()}
                                    value = reverse.get(name, name)
                                    annotation = cls.Params.model_fields[cls.method_param].annotation
                                    annotation = getattr(annotation, "__value__", annotation)  # `type X = Literal[...]`
                                    if value not in typing.get_args(annotation):
                                        return None
                                    return {cls.method_param: value}
                            
                                @classmethod
                                def match_expr(cls, node: ast.expr, var: str) -> tuple[str, dict[str, Any]] | None:  # noqa: PLR0911
                                    if cls.function is not None:
                                        if not (
                                            isinstance(node, ast.Call)
                                            and base.dotted_name(node.func) == cls.function
                                            and node.args
                                            and all(kw.arg is not None for kw in node.keywords)
                                        ):
                                            return None
                                        column = column_of(node.args[0], var)
                                        kwargs = {k.arg: k.value for k in node.keywords if k.arg}
                                        call = Link("call", "", tuple(node.args[1:]), kwargs)
                                        options: dict[str, Any] | None = {}
                                    else:
                                        chain = unchain(node)
                                        if chain is None:
                                            return None
                                        root, links = chain
                                        n = 3 if cls.accessor is not None else 2
                                        if len(links) != n or links[-1].kind != "call":
                                            return None
                                        column = chain_column(root, links, var)
                                        if cls.accessor is not None and links[1] != Link("attr", cls.accessor):
                                            return None
                                        call = links[-1]
                                        options = cls._method_options(call.name)
                                    if column is None or options is None:
                                        return None
                                    args, kwargs = call.literal_args()
                                    if len(args) > len(cls.positional):
                                        return None
                                    options.update(zip(cls.positional, args))
                                    options.update(kwargs)
                                    return column, options
                            

                            call classmethod

                            call(params: Any, obj: Any) -> Any
                            

                            The declared call on a series (or, with frame_call, a frame).

                            Source code in src/datacook/engine/ops/series.py
                            @classmethod
                            def call(cls, params: Any, obj: Any) -> Any:
                                """The declared call on a series (or, with `frame_call`, a frame)."""
                                args, kwargs = cls.call_args(params)
                                if cls.function is not None:
                                    module, _sep, name = cls.function.rpartition(".")
                                    func = getattr(importlib.import_module({"pd": "pandas"}.get(module, module)), name)
                                    return func(obj, *args, **kwargs)
                                if cls.accessor is not None:
                                    obj = getattr(obj, cls.accessor)
                                return getattr(obj, cls.method_name(params))(*args, **kwargs)
                            

                            call_code classmethod

                            call_code(params: Any, source: str, indent: int = 0) -> str
                            

                            Code of call() on the expression source.

                            Source code in src/datacook/engine/ops/series.py
                            @classmethod
                            def call_code(cls, params: Any, source: str, indent: int = 0) -> str:
                                """Code of `call()` on the expression `source`."""
                                args, kwargs = cls.call_args(params)
                                if cls.function is not None:
                                    return base.format_call(
                                        cls.function, [source, *map(base.literal, args)], kwargs, indent
                                    )
                                prefix = f"{source}.{cls.accessor}" if cls.accessor is not None else source
                                func = f"{prefix}.{cls.method_name(params)}"
                                return base.format_call(func, list(map(base.literal, args)), kwargs, indent)
                            

                            :fa-brands-github: Show source on GitHub