Skip to content

DetectGaps

Base classes

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

⋔ Inheritance diagram

graph TD
  345788010["timeseries.DetectGaps"]
  1539482213["base.Op"]
  2751680898["builtins.object"]
  1539482213 --> 345788010
  2751680898 --> 1539482213

🛈 DocStrings

Bases: Op

Old pandastools detect_gaps / time gaps, on a column.

Source code in src/datacook/engine/ops/timeseries.py
class DetectGaps(base.Op):
    """Old pandastools `detect_gaps` / time gaps, on a column."""

    id = "detect_gaps"
    title = _("Number segments between gaps")
    description = _(
        "New column numbering the segments of the data (1, 2, ...): a new segment starts "
        "where the time (or a numeric column) jumps by more than the maximum gap."
    )
    category = categories.TIMESERIES
    icon = "mdi.arrow-split-vertical"

    class Params(base.Params):
        time_column: str = _time_field(title=N_("Column"))
        max_gap: str | float = Field(
            "1s",
            title=N_("Maximum gap"),
            description=N_("A duration (e.g. 1s, 5min) for date / time, a number otherwise."),
        )
        name: str = Field("segment", title=N_("New column"), min_length=1)

    @classmethod
    def apply(cls, params: Params, *inputs: Frame) -> Frame:
        import pandas as pd

        frame = inputs[0]
        _check_column(frame, params.time_column)
        gap = pd.Timedelta(params.max_gap) if isinstance(params.max_gap, str) else params.max_gap
        jumps = frame[params.time_column].diff().gt(gap).fillna(False).astype("int64")
        return frame.assign(**{params.name: jumps.cumsum() + 1})

    @classmethod
    def to_code(cls, params: Params, inputs: Sequence[str], output: str) -> str:
        var = inputs[0]
        gap = (
            f"pd.Timedelta({base.literal(params.max_gap)})"
            if isinstance(params.max_gap, str)
            else base.literal(params.max_gap)
        )
        time = series.column_code(var, params.time_column)
        expr = f'{time}.diff().gt({gap}).fillna(False).astype("int64").cumsum() + 1'
        return series.assign_code(var, output, {params.name: expr})

    @classmethod
    def from_code(cls, stmt: ast.stmt, bound: Mapping[str, Any]) -> base.Match | None:
        found = _single_assign(stmt, bound)
        if found is None:
            return None
        output, var, name, node = found
        column = _first_column(node, var)
        gt = next(
            (
                sub
                for sub in ast.walk(node)
                if isinstance(sub, ast.Call)
                and isinstance(sub.func, ast.Attribute)
                and sub.func.attr == "gt"
                and len(sub.args) == 1
            ),
            None,
        )
        if column is None or gt is None:
            return None
        arg = gt.args[0]
        try:
            if isinstance(arg, ast.Call) and base.dotted_name(arg.func) == "pd.Timedelta":
                max_gap = base.literal_value(arg.args[0])
            else:
                max_gap = base.literal_value(arg)
        except ValueError, IndexError:
            return None
        params = cls.Params(time_column=column, max_gap=max_gap, name=name)
        return series.confirm(cls, params, [var], output, stmt)

:fa-brands-github: Show source on GitHub