Skip to content

Migrate ArbitraryOutlierCapper to narwhals, add polars support - #1034

Merged
solegalli merged 6 commits into
narwhals-migrationfrom
narwhals-arbitrary-outlier-capper
Sep 19, 2026
Merged

solegalli merged 6 commits into
narwhals-migrationfrom
narwhals-arbitrary-outlier-capper

Conversation

@solegalli

Copy link
Copy Markdown
Collaborator

Migrates ArbitraryOutlierCapper to narwhals with polars support.

fit() only builds dicts from user input and validates via check_numerical_variables (already narwhals-generic) — no numeric computation. The only pandas-specific line was feature_names_in_ = X.columns.to_list(), replaced with the same is_pandas-guarded pattern WinsorizerBase.fit() already uses. transform() was already dataframe-agnostic via BaseOutlier._transform(); only type hints changed (pd.DataFrame → IntoDataFrame).

Merge vs split: benchmarked fit+transform end-to-end at 10k/50k/100k rows × 1/2/10 cols. pandas-native (pre-migration) vs migrated-on-pandas were within noise (~0.9–1.1x); polars ran 2–4x faster on both. No split — single merged path. Confirmed the module needs zero pandas (reloaded with sys.modules["pandas"] = None, ran fit/transform on polars; int64 stays int64 for a same-dtype capping dict).

Known pre-existing bug (flagged, not fixed here): in the already-merged BaseOutlier._transform(), when a capping dict spans columns of different dtypes that land in the same bound-group (e.g. max_capping_dict={"age": 50, "fare": 200}, age int64 / fare float64, both "right only"), the group's columns are stacked into one 2D array via to_numpy() before np.clip, forcing a common dtype and upcasting age to float64. The pre-narwhals code clipped each column independently. Reproduces identically on both backends; lives in base_outlier.py, shared with Winsoriser/OutlierTrimmer, out of this file's scope.

Tests rewritten to one parametrized test per behaviour over pd.DataFrame/pl.DataFrame, using nw.from_native(...).to_dict(as_series=False) for backend-agnostic assertions. Docs "With polars" section added (float dtypes throughout, to sidestep the dtype-upcast issue above); pandas Titanic walkthrough untouched (no network in sandbox).

Verified: tests/test_outliers — 88 passed (up from 83), same 3 pre-existing check_estimator failures. flake8 / mypy clean, sphinx -W clean.


Stacked on narwhals-outliers-base (its own PR). Until that merges this PR's diff also contains the shared BaseOutlier / WinsorizerBase commit; review that one first.

@solegalli
solegalli force-pushed the narwhals-arbitrary-outlier-capper branch from 7b80eea to 1f818a9 Compare September 14, 2026 20:46
@solegalli

Copy link
Copy Markdown
Collaborator Author

Updated this branch:

Locally: test_arbitrary_capper.py 18 passed; no new failures in tests/test_outliers. flake8 and mypy clean.

solegalli and others added 4 commits September 19, 2026 08:53
fit() only builds dicts from user input and validates variables/dtypes
via check_numerical_variables (already narwhals-generic) - no numeric
computation, so nothing to branch on there. The only pandas-specific
lines were the feature_names_in_ assignment (X.columns.to_list(), a
pandas-Index method), replaced with the same is_pandas-guarded pattern
WinsorizerBase.fit() already uses (list(X.columns) for pandas,
nw.from_native(X).columns - already list[str] - otherwise). transform()
was already dataframe-agnostic via BaseOutlier._transform(); only its
type hints changed (pd.DataFrame -> IntoDataFrame).

Benchmarked fit+transform end-to-end at 10k/50k/100k rows x 1/2/10
columns: pandas-native (pre-migration) vs the migrated code on pandas
were within noise of each other (~0.9-1.1x), and polars ran 2-4x faster
than pandas on both. No pandas/polars branch needed - merged single
path, consistent with the is_pandas-only-for-.columns precedent already
set in WinsorizerBase.

Confirmed the module needs zero pandas: reloaded artbitrary.py in
isolation with sys.modules["pandas"] = None (simulating an uninstalled
pandas) and ran fit/transform end-to-end on a polars frame - works,
and int64 stays int64 for a same-dtype capping dict (the class
docstring's own x1 example).

Found, while doing so, a real dtype-preservation bug in the already-
merged BaseOutlier._transform() (base_outlier.py, commit 71bf7cf on
this branch's base) that predates this migration and is not introduced
here: when a capping-dict spans columns of different dtypes that land
in the same bound-group (e.g. max_capping_dict={"age": 50, "fare": 200}
with age int64 and fare float64 - both "right_only"), the group's
columns are stacked into one 2D array via to_numpy() before np.clip,
which forces a common dtype and upcasts age to float64. The pre-
narwhals code (verified against 71bf7cf^) clipped each column
independently (X[feature] = X[feature].clip(...)), so int columns
never picked up a neighboring float column's dtype. Confirmed this
reproduces identically on both pandas and polars (same merged code
path) and is untouched by this commit - it lives in base_outlier.py,
shared with Winsoriser/OutlierTrimmer, out of this file's scope.
Flagged separately rather than fixed here.

Rewrote test_arbitrary_capper.py to one parametrized test per behavior
over pd.DataFrame/pl.DataFrame (previously pandas-only), using
nw.from_native(...).to_dict(as_series=False) for backend-agnostic
assertions in place of pd.testing.assert_frame_equal, following the
same pattern used for ReciprocalTransformer/ArcsinTransformer. Added a
verified "With polars" section to the docs (float dtypes throughout, to
sidestep the dtype-upcast issue above rather than put an unexplained
surprise in a user-facing example); left the pre-existing pandas
Titanic walkthrough untouched - no network access in this environment
to re-verify the fetch_openml/CSV-backed output.

Verified: tests/test_outliers full suite - 88 passed (up from 83, all
5 new instances are the added polars parametrizations), same 3
pre-existing check_estimator failures as the pre-migration baseline
(numpy-array input, unrelated to this change). flake8 and mypy clean.
sphinx -W build clean (only the pre-existing linkcode_resolve warning).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Bind the narwhals frame returned by check_X and set feature_names_in_ and
n_features_in_ from it, instead of treating the check_X result as a native
frame, mirroring the imputation and encoding modules.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…r tests

Replace the file-local _to_dict helper and parametrize decorators with the
shared test structure: make_df fixture, isinstance(X, make_df) plus to_dict()
checks, missing values written as None, and pytest.raises(match=re.escape(msg)).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@solegalli
solegalli force-pushed the narwhals-arbitrary-outlier-capper branch from c80cd08 to 1c6fa6f Compare September 19, 2026 06:54
solegalli and others added 2 commits September 19, 2026 09:00
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…ng test

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@solegalli
solegalli merged commit a54622a into narwhals-migration Sep 19, 2026
3 of 10 checks passed
@solegalli
solegalli deleted the narwhals-arbitrary-outlier-capper branch September 19, 2026 07:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant