Skip to content

SetTimeColumn

Base classes

Name Children Inherits
Op
datacook.engine.ops.base
Base class for operations. Subclasses set the metadata class variables.

⋔ Inheritance diagram

graph TD
  1160968978["timeseries.SetTimeColumn"]
  1539482213["base.Op"]
  2751680898["builtins.object"]
  1539482213 --> 1160968978
  2751680898 --> 1539482213

🛈 DocStrings

Bases: Op

Source code in src/datacook/engine/ops/timeseries.py
class SetTimeColumn(base.Op):
    id = "set_time_column"
    title = _("Use as time column")
    description = _(
        "Make a date / time (or numeric) column the time of the table: rows are sorted by "
        "it and time series steps use it by default."
    )
    category = categories.TIMESERIES
    icon = "mdi.clock-outline"

    class Params(base.Params):
        time_column: str = _time_field()

    @classmethod
    def apply(cls, params: Params, *inputs: Frame) -> Frame:
        frame = inputs[0]
        _check_column(frame, params.time_column)
        import pandas as pd

        dtype = frame[params.time_column].dtype
        if not (is_datetime(str(dtype)) or pd.api.types.is_numeric_dtype(dtype)):
            msg = f"{params.time_column!r} is {dtype}: convert it to date / time first"
            raise base.OpError(msg)
        return frame.sort_values(params.time_column, kind="stable", ignore_index=True)

    @classmethod
    def to_code(cls, params: Params, inputs: Sequence[str], output: str) -> str:
        column = base.literal(params.time_column)
        return f'{output} = {inputs[0]}.sort_values({column}, kind="stable", ignore_index=True)'

    @classmethod
    def from_code(cls, stmt: ast.stmt, bound: Mapping[str, Any]) -> base.Match | None:  # noqa: PLR0911
        assign = base.assignment(stmt)
        if assign is None:
            return None
        chain = series.unchain(assign[1])
        if chain is None:
            return None
        root, links = chain
        if not (isinstance(root, ast.Name) and root.id in bound and len(links) == 1):
            return None
        call = links[0]
        if call.kind != "call" or call.name != "sort_values" or len(call.args) != 1:
            return None
        try:
            args, _kwargs = call.literal_args()
        except ValueError:
            return None
        if not isinstance(args[0], str):
            return None
        params = cls.Params(time_column=args[0])
        return series.confirm(cls, params, [root.id], assign[0], stmt)

:fa-brands-github: Show source on GitHub