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)