Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
23 changes: 15 additions & 8 deletions src/freshdata/_core/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand All @@ -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)
Expand All @@ -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}"),
Expand All @@ -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 = []
Expand Down
24 changes: 24 additions & 0 deletions tests/test_backend_honesty.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Loading