Skip to content

SliceRows

Base classes

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

⋔ Inheritance diagram

graph TD
  1837082519["rows.SliceRows"]
  1539482213["base.Op"]
  2751680898["builtins.object"]
  1539482213 --> 1837082519
  2751680898 --> 1539482213

🛈 DocStrings

Bases: Op

Source code in src/datacook/engine/ops/rows.py
class SliceRows(base.Op):
    id = "slice_rows"
    title = _("Slice rows")
    description = _(
        "Keep rows by position: from start (inclusive) to stop (exclusive), every n-th row."
    )
    category = categories.ROWS
    icon = "mdi.table-split-cell"

    class Params(base.Params):
        start: int | None = Field(None, title=N_("Start"))
        stop: int | None = Field(None, title=N_("Stop"))
        step: int | None = Field(None, title=N_("Every n-th row"), ge=1)

    @classmethod
    def apply(cls, params: Params, *inputs: Frame) -> Frame:
        return inputs[0].iloc[params.start : params.stop : params.step]

    @classmethod
    def to_code(cls, params: Params, inputs: Sequence[str], output: str) -> str:
        start, stop = ("" if v is None else str(v) for v in (params.start, params.stop))
        index = f"{start}:{stop}" if params.step is None else f"{start}:{stop}:{params.step}"
        return f"{output} = {inputs[0]}.iloc[{index}]"

    @classmethod
    def from_code(cls, stmt: ast.stmt, bound: Mapping[str, Any]) -> base.Match | None:
        assign = base.assignment(stmt)
        if assign is None:
            return None
        output, value = assign
        if not (
            isinstance(value, ast.Subscript)
            and isinstance(value.value, ast.Attribute)
            and value.value.attr == "iloc"
            and isinstance(value.value.value, ast.Name)
            and (frame := value.value.value.id) in bound
            and isinstance(index := value.slice, ast.Slice)
        ):
            return None
        try:
            start, stop, step = (
                None if node is None else base.literal_value(node)
                for node in (index.lower, index.upper, index.step)
            )
        except ValueError:
            return None
        return base.Match(cls.Params(start=start, stop=stop, step=step), (frame,), output)

:fa-brands-github: Show source on GitHub