Skip to content

missing

Class info

Classes

Name Children Inherits
DropMissing
datacook.engine.ops.missing
    DropMissingColumns
    datacook.engine.ops.missing
      FillBackward
      datacook.engine.ops.missing
        FillForward
        datacook.engine.ops.missing
        FillMissing
        datacook.engine.ops.missing
          FillWithStatistic
          datacook.engine.ops.missing
          `df.fillna(df[cols].mean())` (one fill value per column).
            FilterMissing
            datacook.engine.ops.missing
              Interpolate
              datacook.engine.ops.missing
                IsMissing
                datacook.engine.ops.missing
                  NanToMissing
                  datacook.engine.ops.missing
                  `df.mask(lambda d: d !\= d)`: NaN is the only value not equal to itself.

                    🛈 DocStrings

                    Missing value ops.

                    Missing values (policy). Tables use arrow-backed dtypes, where a missing value is a null (pd.NA): readers produce nulls, isna() / fillna() / dropna() and every op here work on nulls. A float NaN ("not a number", e.g. from a numpy computation or a Parquet file written that way) is a value in an arrow float column, not a missing one: "NaN to missing" turns NaNs into nulls. In numpy float columns (after a cast to "float64") pandas treats NaN as missing, so the ops behave the same there. Ops that write missing values write pd.NA, which keeps the column dtype (None would make it object).

                    FillWithStatistic

                    Bases: Op

                    df.fillna(df[cols].mean()) (one fill value per column).

                    The mode is df[cols].mode().head(1).squeeze(axis=0): the first mode per column, and no error on an empty table (.iloc[0] would raise).

                    Source code in src/datacook/engine/ops/missing.py
                    class FillWithStatistic(base.Op):
                        """`df.fillna(df[cols].mean())` (one fill value per column).
                    
                        The mode is `df[cols].mode().head(1).squeeze(axis=0)`: the first mode per column, and
                        no error on an empty table (`.iloc[0]` would raise).
                        """
                    
                        id = "fill_statistic"
                        title = _("Fill with mean / median / mode")
                        description = _(
                            "Fill missing values of each column with a statistic of that column"
                            " (mean, median, minimum, maximum or most frequent value)."
                        )
                        category = categories.NAN
                        icon = "mdi.format-color-fill"
                    
                        class Params(base.Params):
                            columns: list[str] = _columns()
                            statistic: Literal["mean", "median", "min", "max", "mode"] = Field(
                                "mean", title=N_("Statistic")
                            )
                    
                        @classmethod
                        def apply(cls, params: Params, *inputs: Frame) -> Frame:
                            frame = inputs[0]
                            part = frame[params.columns]
                            if params.statistic == "mode":
                                fill = part.mode().head(1).squeeze(axis=0)
                            else:
                                fill = getattr(part, params.statistic)()
                            return frame.fillna(fill)
                    
                        @classmethod
                        def to_code(cls, params: Params, inputs: Sequence[str], output: str) -> str:
                            frame = inputs[0]
                            part = f"{frame}[{base.literal(params.columns)}]"
                            if params.statistic == "mode":
                                fill = f"{part}.mode().head(1).squeeze(axis=0)"
                            else:
                                fill = f"{part}.{params.statistic}()"
                            return f"{output} = {frame}.fillna({fill})"
                    
                        @classmethod
                        def from_code(  # noqa: PLR0911
                            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.Call)
                                and isinstance(value.func, ast.Attribute)
                                and value.func.attr == "fillna"
                                and isinstance(value.func.value, ast.Name)
                                and (frame := value.func.value.id) in bound
                                and len(value.args) == 1
                                and not value.keywords
                                and isinstance(fill := value.args[0], ast.Call)
                            ):
                                return None
                            text = ast.unparse(fill)
                            prefix = f"{frame}["
                            if not text.startswith(prefix):
                                return None
                            index_end = text.find("].", len(prefix))
                            if index_end < 0:
                                return None
                            try:
                                columns = ast.literal_eval(text[len(prefix) : index_end])
                            except ValueError, SyntaxError:
                                return None
                            rest = text[index_end + 2 :]
                            statistic = {f"{s}()": s for s in STATISTICS if s != "mode"}.get(rest)
                            if rest == "mode().head(1).squeeze(axis=0)":
                                statistic = "mode"
                            if statistic is None or not isinstance(columns, list):
                                return None
                            params = cls.Params.model_validate({"columns": columns, "statistic": statistic})
                            return base.Match(params, (frame,), output)
                    

                    NanToMissing

                    Bases: Op

                    df.mask(lambda d: d != d): NaN is the only value not equal to itself.

                    Nulls compare as null (not True), so they stay; non-float columns are unchanged.

                    Source code in src/datacook/engine/ops/missing.py
                    class NanToMissing(base.Op):
                        """`df.mask(lambda d: d != d)`: NaN is the only value not equal to itself.
                    
                        Nulls compare as null (not True), so they stay; non-float columns are unchanged.
                        """
                    
                        id = "nan_to_missing"
                        title = _("NaN to missing")
                        description = _(
                            "Turn NaN ('not a number') values of float columns into missing values, so missing"
                            " value ops see them."
                        )
                        category = categories.NAN
                        icon = "mdi.help-circle-outline"
                    
                        class Params(base.Params):
                            columns: list[str] | None = _subset()
                    
                        @classmethod
                        def apply(cls, params: Params, *inputs: Frame) -> Frame:
                            frame = inputs[0]
                            if params.columns is None:
                                return frame.mask(_is_nan)
                            return frame.assign(**frame[params.columns].mask(_is_nan))
                    
                        @classmethod
                        def to_code(cls, params: Params, inputs: Sequence[str], output: str) -> str:
                            frame = inputs[0]
                            if params.columns is None:
                                return f"{output} = {frame}.mask(lambda d: d != d)"
                            part = f"{frame}[{base.literal(params.columns)}]"
                            return f"{output} = {frame}.assign(**{part}.mask(lambda d: d != d))"
                    
                        @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
                            text = ast.unparse(value)
                            for frame in bound:
                                if text == f"{frame}.mask(lambda d: d != d)":
                                    return base.Match(cls.Params(), (frame,), output)
                                prefix, suffix = f"{frame}.assign(**{frame}[", "].mask(lambda d: d != d))"
                                if text.startswith(prefix) and text.endswith(suffix):
                                    try:
                                        columns = ast.literal_eval(text[len(prefix) : -len(suffix)])
                                    except ValueError, SyntaxError:
                                        return None
                                    if not isinstance(columns, list):
                                        return None
                                    return base.Match(cls.Params(columns=columns), (frame,), output)
                            return None