From 05b89232105775d05d49ded0de916b413a180e72 Mon Sep 17 00:00:00 2001 From: Johnny Wilson Dougherty Date: Sat, 28 Nov 2026 21:46:55 +0530 Subject: [PATCH] fix(polars): plan missing-value actions only where pandas does The Polars planner added impute_median for every numeric column, also for columns with no nulls. The fill used a Float64 median, so applying the plan turned Int64 columns into Float64. pandas skips those columns. The planner now gets one keep flag per missing-value action from its one planning query and drops the actions that change no cell: a fill needs some nulls but not only nulls, drop_nulls needs nulls (or an empty frame), ffill needs one filled cell. The rules match stage_missing in pandas. Int columns with no nulls stay Int64. The README output loses the no-op "invoice_total: impute_median" line. --- CHANGELOG.md | 5 +++++ README.md | 1 - src/freshdata/_core/backends.py | 23 +++++++++++++++-------- tests/test_backend_honesty.py | 24 ++++++++++++++++++++++++ 4 files changed, 44 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 150da6d..836cec7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -79,6 +79,11 @@ Polars. Code written for 2.x needs changes. `freshdata-migrate` (install - pandas `rows_affected` counts the cells an action changes. Polars counts the nulls that imputation fills or `drop_nulls` removes. Where Polars does not count (to keep planning to one cheap query), `rationale` says so. +- The Polars planner plans a missing-value action only where pandas does: a + fill when a column has some nulls but not only nulls, a `drop_nulls` when it + has nulls. Before, Polars planned `impute_median` for every numeric column, + and applying it turned `Int64` columns with no nulls into `Float64`. Polars + plans now have fewer actions, and those columns stay `Int64`. ### Never released diff --git a/README.md b/README.md index de0aeb6..65f1752 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,6 @@ for action in plan.actions: # [column_names] Segment: normalize_name {'to': 'segment'} # [strings] segment: strip_strings {} # [column_names] Invoice Total: normalize_name {'to': 'invoice_total'} -# [missing] invoice_total: impute_median {} # [outliers] signup_age: clip_iqr {'lower': 27.875, 'upper': 48.875} # [duplicates] *: drop_duplicates {} # customer_id (id) and churned (target) get no imputation, stripping, or clipping. diff --git a/src/freshdata/_core/backends.py b/src/freshdata/_core/backends.py index a97accc..28b1333 100644 --- a/src/freshdata/_core/backends.py +++ b/src/freshdata/_core/backends.py @@ -185,10 +185,14 @@ def suggest_plan(self, df: pl.DataFrame | pl.LazyFrame, cfg: CleanConfig) -> Cle cfg_eff = normalize_config(cfg) bounded: dict[str, tuple[pl.Expr, str]] = {} counts: dict[int, pl.Expr] = {} # action index -> rows_affected, filled by the one query below + # action index -> keep it? Like pandas, plan no fill that changes no cell, so int columns stay int. + keep: dict[int, pl.Expr] = {} - def add(action: ActionRecord, count: pl.Expr | None = None) -> None: + def add(action: ActionRecord, count: pl.Expr | None = None, when: pl.Expr | None = None) -> None: if count is not None: counts[len(actions)] = count + if when is not None: + keep[len(actions)] = when actions.append(action) for orig, dtype in schema.items(): @@ -204,19 +208,22 @@ def add(action: ActionRecord, count: pl.Expr | None = None) -> None: # Mirror the pandas stage order: IQR bounds see the imputed column. base = col impute_strat = _impute_strategy(name, cfg_eff) + nulls = col.null_count() + fillable = (nulls > 0) & (nulls < pl.len()) if impute_strat == "drop": - add(ActionRecord("missing", name, "drop_nulls", {}), col.null_count()) + add(ActionRecord("missing", name, "drop_nulls", {}), nulls, (nulls > 0) | (pl.len() == 0)) elif impute_strat == "mode": - add(ActionRecord("missing", name, "impute_mode", {}), col.null_count()) + add(ActionRecord("missing", name, "impute_mode", {}), nulls, fillable) base = base.fill_null(_pl_mode(base)) elif impute_strat == "ffill": base = base.forward_fill() - add(ActionRecord("missing", name, "impute_ffill", {}), col.null_count() - base.null_count()) + filled = nulls - base.null_count() + add(ActionRecord("missing", name, "impute_ffill", {}), filled, filled > 0) elif dtype.is_numeric() and impute_strat in ("median", "auto"): - add(ActionRecord("missing", name, "impute_median", {}), col.null_count()) + add(ActionRecord("missing", name, "impute_median", {}), nulls, fillable) base = base.fill_null(base.median()) elif dtype.is_numeric() and impute_strat == "mean": - add(ActionRecord("missing", name, "impute_mean", {}), col.null_count()) + add(ActionRecord("missing", name, "impute_mean", {}), nulls, fillable) base = base.fill_null(base.mean()) outlier_strat = _outlier_strategy(name, cfg_eff) @@ -226,7 +233,7 @@ def add(action: ActionRecord, count: pl.Expr | None = None) -> None: add(ActionRecord("duplicates", "*", "drop_duplicates", {}, rationale=_uncounted("a full-row hash"))) k = cfg_eff.iqr_factor - stat_exprs = [e.alias(f"c{i}") for i, e in counts.items()] + stat_exprs = [e.alias(f"c{i}") for i, e in counts.items()] + [e.alias(f"k{i}") for i, e in keep.items()] for i, (base, _) in enumerate(bounded.values()): stat_exprs += [base.count().alias(f"n{i}"), base.quantile(0.25, interpolation="linear").alias(f"q25_{i}"), @@ -237,7 +244,7 @@ def add(action: ActionRecord, count: pl.Expr | None = None) -> None: stats = df.lazy().select(stat_exprs).collect().row(0, named=True) actions = [ dataclasses.replace(a, rows_affected=int(stats[f"c{i}"] or 0)) if i in counts else a - for i, a in enumerate(actions) + for i, a in enumerate(actions) if stats.get(f"k{i}", True) ] out_names = {a.parameters["to"] for a in actions if a.action == "normalize_name"} | set(schema) bounded_actions = [] diff --git a/tests/test_backend_honesty.py b/tests/test_backend_honesty.py index d5efb60..c6dbd59 100644 --- a/tests/test_backend_honesty.py +++ b/tests/test_backend_honesty.py @@ -238,3 +238,27 @@ def test_rows_affected_counts_changed_cells_on_both_backends(): plan = fd.suggest_plan(frame, cfg).actions assert {(a.action, a.rows_affected) for a in plan if not a.rationale} == {("normalize_name", 0), ("impute_median", 1)} assert {a.action for a in plan if "not computed" in a.rationale} == {"strip_strings", "clip_iqr"} + + +@pytest.mark.parametrize("impute", ["median", "mean", "mode", "ffill", "drop"]) +def test_polars_plans_missing_actions_only_where_pandas_does(impute): + import freshdata as fd + + # qty has no nulls, gone is all nulls, age has one null. + data = {"qty": [1, 2, 3, 4], "gone": [None, None, None, None], "age": [30.0, None, 31.0, 32.0]} + cfg = CleanConfig(default_impute=impute, strip_strings=False, fix_dtypes=False) + def missing(plan): + # Row counts after a drop differ: pandas counts each drop on the rows left, Polars on the input. + return {(a.column, a.action) for a in plan.actions if a.stage == "missing"} + want = missing(fd.suggest_plan(pd.DataFrame(data), cfg)) + for frame in (pl.DataFrame(data), pl.LazyFrame(data)): + assert missing(fd.suggest_plan(frame, cfg)) == want + + +def test_polars_keeps_int_dtype_when_no_value_is_missing(): + import freshdata as fd + + frame = pl.LazyFrame({"qty": [1, 2, 3, 4], "age": [30.0, None, 31.0, 32.0]}) + out = fd.apply_plan(frame, fd.suggest_plan(frame)).collect() + assert out.schema["qty"] == pl.Int64 + assert out["qty"].to_list() == [1, 2, 3, 4]