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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ adheres to [Semantic Versioning](https://semver.org/).
`id_columns`, and a negative `iqr_factor`. Options with no effect
(`strategy`, most `role` values, `default_outliers="auto"`) warn.
- pandas `clean()` is about 33% faster on string-heavy frames.
- Mixed-type columns containing non-currency values are no longer currency-parsed.

### Fixed

Expand Down
33 changes: 31 additions & 2 deletions src/freshdata/_core/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
ProfileReport,
)
from freshdata._core.stages import (
CURRENCY_REGEX,
_impute_strategy,
_is_protected,
_outlier_strategy,
Expand Down Expand Up @@ -109,7 +110,17 @@ def apply_plan(self, df: pd.DataFrame, plan: CleanPlan, cfg: CleanConfig) -> pd.
if pd.api.types.is_string_dtype(s) or pd.api.types.is_object_dtype(s):
out[col] = s.astype(object).apply(_strip_str)
elif key == ("dtypes", "parse_currency"):
cleaned = s.astype(str).str.replace(r"[^\d.-]", "", regex=True)
text = s.astype(str).str.strip()
invalid_mask = (
s.notna()
& text.ne("")
& ~text.str.fullmatch(CURRENCY_REGEX)
)
if invalid_mask.any():
continue
cleaned = s.astype(str).str.replace(
r"[^\d.-]", "", regex=True
)
out[col] = pd.to_numeric(cleaned, errors="coerce")
elif key in _PANDAS_FILLS:
val = a.parameters.get("value")
Expand Down Expand Up @@ -283,8 +294,26 @@ def apply_plan(self, df: pl.DataFrame | pl.LazyFrame, plan: CleanPlan, cfg: Clea
if key == ("strings", "strip_strings"):
exprs[col_name] = expr.str.strip_chars()
elif key == ("dtypes", "parse_currency"):
text = expr.cast(pl.String).str.strip_chars()
invalid = (
expr.is_not_null()
& text.ne("")
& ~text.str.contains(CURRENCY_REGEX.pattern)
)
validation = cur.select(
invalid.any().alias("has_invalid")
)

if isinstance(validation, pl.LazyFrame):
has_invalid = validation.collect().item()
else:
has_invalid = validation.item()
if has_invalid:
continue
exprs[col_name] = (
expr.cast(pl.String).str.replace_all(r"[^\d.-]", "").cast(pl.Float64, strict=False)
expr.cast(pl.String)
.str.replace_all(r"[^\d.-]", "")
.cast(pl.Float64, strict=False)
)
elif key == ("missing", "impute_median"):
exprs[col_name] = expr.fill_null(val if val is not None else expr.median())
Expand Down
60 changes: 49 additions & 11 deletions src/freshdata/_core/stages.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,17 +101,55 @@ def stage_dtypes(df: pd.DataFrame, cfg: CleanConfig) -> Tuple[pd.DataFrame, List
for col in out.columns:
if _is_protected(col, cfg_eff):
continue
if pd.api.types.is_object_dtype(out[col]) or pd.api.types.is_string_dtype(out[col]):
sample = out[col].dropna().head(20).astype(str)
if sample.empty:
continue
has_symbol = sample.str.contains(r"[\$€£¥]").any()
matches_pattern = sample.apply(lambda v: bool(CURRENCY_REGEX.match(v)))
if has_symbol and (matches_pattern.sum() / len(sample)) >= 0.7:
parsed = int(out[col].notna().sum())
cleaned = out[col].astype(str).str.replace(r"[^\d.-]", "", regex=True)
out[col] = pd.to_numeric(cleaned, errors="coerce")
actions.append(ActionRecord("dtypes", str(col), "parse_currency", {"target_dtype": "float64"}, parsed))

if not (
pd.api.types.is_object_dtype(out[col])
or pd.api.types.is_string_dtype(out[col])
):
continue

sample = out[col].dropna().head(20).astype(str)

if sample.empty:
continue

has_symbol = sample.str.contains(r"[\$€£¥]").any()
matches_pattern = sample.str.fullmatch(CURRENCY_REGEX)

if not has_symbol or (matches_pattern.sum() / len(sample)) < 0.7:
continue

# Validate original values before removing currency symbols.
text = out[col].astype(str).str.strip()

invalid_mask = (
out[col].notna()
& text.ne("")
& ~text.str.fullmatch(CURRENCY_REGEX)
)

# Skip conversion if non-currency values are present.
if invalid_mask.any():
continue

cleaned = out[col].astype(str).str.replace(
r"[^\d.-]", "", regex=True
)
parsed = pd.to_numeric(cleaned, errors="coerce")

parsed_count = int(out[col].notna().sum())
out[col] = parsed

actions.append(
ActionRecord(
"dtypes",
str(col),
"parse_currency",
{"target_dtype": "float64"},
parsed_count,
)
)

return out, actions

def stage_duplicates(df: pd.DataFrame, cfg: CleanConfig) -> Tuple[pd.DataFrame, List[ActionRecord]]:
Expand Down
78 changes: 78 additions & 0 deletions tests/test_reviewer_fixes.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,81 @@ def test_polars_impute_mean_and_duplicates():
lazy_cleaned = fd.apply_plan(df.lazy(), plan, cfg).collect()
assert len(lazy_cleaned) == 3


def test_pandas_currency_plan_preserves_mixed_replay_values():
training = pd.DataFrame({
"amount": ["$10", "$20", "$30", "$40"]
})
replay = pd.DataFrame({
"amount": ["$50", "REF-9921", "N/A"]
})

plan = fd.suggest_plan(training)
assert any(a.action == "parse_currency" for a in plan.actions)

result = fd.apply_plan(replay, plan)

assert result["amount"].tolist() == ["$50", "REF-9921", "N/A"]


def test_pandas_currency_plan_converts_valid_replay_values():
training = pd.DataFrame({
"amount": ["$10", "$20", "$30", "$40"]
})
replay = pd.DataFrame({
"amount": ["$50", "$60", "$70"]
})

plan = fd.suggest_plan(training)
result = fd.apply_plan(replay, plan)

assert result["amount"].tolist() == [50.0, 60.0, 70.0]


def test_polars_currency_plan_preserves_mixed_replay_values():
training = pd.DataFrame({
"amount": ["$10", "$20", "$30", "$40"]
})
replay = pl.DataFrame({
"amount": ["$50", "REF-9921", "N/A"]
})

plan = fd.suggest_plan(training)
assert any(a.action == "parse_currency" for a in plan.actions)

result = fd.apply_plan(replay, plan)

assert result["amount"].to_list() == ["$50", "REF-9921", "N/A"]


def test_polars_currency_plan_preserves_mixed_lazy_replay_values():
training = pd.DataFrame({
"amount": ["$10", "$20", "$30", "$40"]
})
replay = pl.DataFrame({
"amount": ["$50", "REF-9921", "N/A"]
}).lazy()

plan = fd.suggest_plan(training)
result = fd.apply_plan(replay, plan)

assert isinstance(result, pl.LazyFrame)
assert result.collect()["amount"].to_list() == [
"$50", "REF-9921", "N/A"
]


def test_polars_currency_plan_converts_valid_replay_values():
training = pd.DataFrame({
"amount": ["$10", "$20", "$30", "$40"]
})

replay = pl.DataFrame({
"amount": ["$50", "$60", "$70"]
})

plan = fd.suggest_plan(training)
result = fd.apply_plan(replay, plan)

assert result["amount"].to_list() == [50.0, 60.0, 70.0]

20 changes: 20 additions & 0 deletions tests/test_stages.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,3 +175,23 @@ def test_protected_id_and_target_columns_are_not_stripped_or_parsed():
assert out["p"].tolist() == [" $1,000 ", "$2", "$3"]
assert out["user_id"].tolist() == [" 7 ", "8", "9"]
assert out["free"].tolist() == [1, 2, 3]


def test_currency_parser_preserves_identifiers():
df = pd.DataFrame({
"price": ["$10.00", "$20.00", "$30.00", "REF-9921"]
})

result, actions = stage_dtypes(df, CleanConfig())

assert result["price"].tolist() == [
"$10.00",
"$20.00",
"$30.00",
"REF-9921",
]

assert not any(
action.action == "parse_currency"
for action in actions
)
Loading