Migrate ArbitraryOutlierCapper to narwhals, add polars support - #1034
Merged
Merged
Conversation
solegalli
force-pushed
the
narwhals-arbitrary-outlier-capper
branch
from
September 14, 2026 20:46
7b80eea to
1f818a9
Compare
Collaborator
Author
|
Updated this branch:
Locally: |
solegalli
force-pushed
the
narwhals-arbitrary-outlier-capper
branch
from
September 15, 2026 10:01
1f818a9 to
c80cd08
Compare
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
force-pushed
the
narwhals-arbitrary-outlier-capper
branch
from
September 19, 2026 06:54
c80cd08 to
1c6fa6f
Compare
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…ng test Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Migrates
ArbitraryOutlierCapperto narwhals with polars support.fit()only builds dicts from user input and validates viacheck_numerical_variables(already narwhals-generic) — no numeric computation. The only pandas-specific line wasfeature_names_in_ = X.columns.to_list(), replaced with the sameis_pandas-guarded patternWinsorizerBase.fit()already uses.transform()was already dataframe-agnostic viaBaseOutlier._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 viato_numpy()beforenp.clip, forcing a common dtype and upcasting age to float64. The pre-narwhals code clipped each column independently. Reproduces identically on both backends; lives inbase_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, usingnw.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-existingcheck_estimatorfailures. flake8 / mypy clean, sphinx -W clean.Stacked on
narwhals-outliers-base(its own PR). Until that merges this PR's diff also contains the sharedBaseOutlier/WinsorizerBasecommit; review that one first.