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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@ adheres to [Semantic Versioning](https://semver.org/).
stays `"REF-9921"` instead of becoming `-9921.0`. On a Polars LazyFrame, this check
runs one query on the parse_currency columns inside `apply_plan`.

### Changed

- When `apply_plan` skips a replayed `parse_currency` step, it now warns
(`UserWarning`, naming the column), and `CleanReport.actions` leaves the step
out. Before, the report listed the step as applied although the column was
unchanged.

## [3.0.0] - 2026-11-28

3.0 replaces the 2.x API with a small plan-and-apply core for pandas and
Expand Down
14 changes: 14 additions & 0 deletions src/freshdata/_core/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,16 @@ def _reject(a: ActionRecord, cfg: CleanConfig, backend: str, reason: str = "unkn
raise ValueError(f"{msg}. Fix the plan, or set CleanConfig(strict_backend=False) to skip it with a warning.")
warnings.warn(f"{msg}. Skipped.", UserWarning, stacklevel=4)

def _skip_currency(a: ActionRecord, col: str, skipped: list[ActionRecord]) -> None:
"""Record and warn that a replayed parse_currency step left the column unchanged."""
skipped.append(a)
warnings.warn(
f"parse_currency skipped on column {col!r}: it has values that are not currency strings. "
"The column is unchanged.",
UserWarning,
stacklevel=4,
)

def _bounds(a: ActionRecord) -> tuple[float, float] | None:
lower, upper = a.parameters.get("lower"), a.parameters.get("upper")
if isinstance(lower, Real) and isinstance(upper, Real):
Expand Down Expand Up @@ -86,6 +96,7 @@ def suggest_plan(self, df: pd.DataFrame, cfg: CleanConfig) -> CleanPlan:

def apply_plan(self, df: pd.DataFrame, plan: CleanPlan, cfg: CleanConfig) -> pd.DataFrame:
out = df.copy()
self.skipped: list[ActionRecord] = []
# Execute explicitly planned actions
renames = {}
for a in plan.actions:
Expand Down Expand Up @@ -120,6 +131,7 @@ def apply_plan(self, df: pd.DataFrame, plan: CleanPlan, cfg: CleanConfig) -> pd.
& ~text.str.fullmatch(CURRENCY_REGEX)
)
if invalid_mask.any():
_skip_currency(a, col, self.skipped)
continue
cleaned = s.astype(str).str.replace(
r"[^\d.-]", "", regex=True
Expand Down Expand Up @@ -279,6 +291,7 @@ def add(action: ActionRecord, count: pl.Expr | None = None, when: pl.Expr | None
def apply_plan(self, df: pl.DataFrame | pl.LazyFrame, plan: CleanPlan, cfg: CleanConfig) -> pl.DataFrame | pl.LazyFrame:
import polars as pl

self.skipped: list[ActionRecord] = []
cur = df
# 1. Renames
renames = {a.column: a.parameters["to"] for a in plan.actions if a.stage == "column_names" and a.action == "normalize_name"}
Expand Down Expand Up @@ -319,6 +332,7 @@ def apply_plan(self, df: pl.DataFrame | pl.LazyFrame, plan: CleanPlan, cfg: Clea
else:
has_invalid = validation.item()
if has_invalid:
_skip_currency(a, col_name, self.skipped)
continue
exprs[col_name] = (
expr.cast(pl.String)
Expand Down
6 changes: 4 additions & 2 deletions src/freshdata/_core/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,15 @@ def apply_plan(
return_report: bool = False,
) -> Any:
cfg = config or CleanConfig()
cleaned: Any = resolve_backend(df).apply_plan(df, plan, cfg)
backend = resolve_backend(df)
cleaned: Any = backend.apply_plan(df, plan, cfg)
if return_report:
orig_r = 0 if type(df).__name__ == "LazyFrame" else len(df)
clean_r = 0 if type(cleaned).__name__ == "LazyFrame" else len(cleaned)
orig_c = _column_count(df)
clean_c = _column_count(cleaned)
rep = CleanReport(orig_r, clean_r, orig_c, clean_c, plan.actions)
applied = tuple(a for a in plan.actions if not any(a is s for s in backend.skipped))
rep = CleanReport(orig_r, clean_r, orig_c, clean_c, applied)
return cleaned, rep
return cleaned

Expand Down
25 changes: 25 additions & 0 deletions tests/test_skipped_currency_report.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""A replayed parse_currency step that is skipped must not show in the report."""

import pandas as pd
import pytest

import freshdata as fd

pl = pytest.importorskip("polars")

PLAN = fd.suggest_plan(pd.DataFrame({"amount": ["$10", "$20", "$30"]}))
NEW = {"amount": ["$50", "REF-9921", "N/A"]}


@pytest.mark.parametrize("make", [pd.DataFrame, pl.DataFrame, pl.LazyFrame])
def test_skipped_parse_currency_warns_and_is_not_reported(make):
assert "parse_currency" in [a.action for a in PLAN.actions]
with pytest.warns(UserWarning, match="parse_currency.*'amount'"):
_, report = fd.apply_plan(make(NEW), PLAN, return_report=True)
assert "parse_currency" not in [a.action for a in report.actions]


@pytest.mark.parametrize("make", [pd.DataFrame, pl.DataFrame, pl.LazyFrame])
def test_applied_parse_currency_is_still_reported(make):
_, report = fd.apply_plan(make({"amount": ["$50", "$60"]}), PLAN, return_report=True)
assert "parse_currency" in [a.action for a in report.actions]
Loading