Skip to content

Migrate ArbitraryOutlierCapper to narwhals, add polars support - #1034

Open
solegalli wants to merge 2 commits into
narwhals-migrationfrom
narwhals-arbitrary-outlier-capper
Open

Migrate ArbitraryOutlierCapper to narwhals, add polars support#1034
solegalli wants to merge 2 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.DataFrameIntoDataFrame).

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 and others added 2 commits August 25, 2026 17:04
Shared base for all outlier transformers (ArbitraryOutlierCapper extends
BaseOutlier directly; Winsoriser/OutlierTrimmer extend WinsorizerBase):
column reorder + NA/Inf checks in _check_transform_input_and_state(),
the fold-limit estimation in WinsorizerBase.fit() (gaussian/iqr/mad/
quantiles), and the capping step in BaseOutlier._transform() are now
dataframe-agnostic.

Capping (np.clip against per-column bounds) was benchmarked three ways
at 10k/50k/100k rows x 1/2/10 columns: pandas-native .clip() loop vs. a
single narwhals with_columns(nw.col(v).clip(lo, hi) for v in ...) vs.
grouping columns by which bound(s) apply and running up to 3 vectorized
numpy calls (np.clip/minimum/maximum) via to_numpy()/new_series(), mirroring
ReciprocalTransformer's numpy-acceleration pattern. narwhals-generic alone
was already close to parity (0.95-1.49x pandas-native - minimal loss,
mergeable per the imputation-base precedent), but the numpy-grouped version
was faster still: 0.16-0.82x of pandas-native on the homogeneous case
(single tail, all columns share the same bound - the common Winsoriser/
OutlierTrimmer case) and 0.42-1.52x on mixed-coverage dicts (the
ArbitraryOutlierCapper case, up to 3 groups). Adopted the numpy-grouped
version as the single merged code path for both backends.

A first numpy attempt used a blanket -inf/inf sentinel for the missing
side per column (like RelativeFeatures-style bound arrays) - that's a
correctness bug, not just a style choice: mixing an int64 numpy array
with a float -inf/inf bound upcasts the whole column to float64 even
when the real, present bound is an int (e.g. ArbitraryOutlierCapper's
own docstring example, `max_capping_dict=dict(x1=8)`, expects int64 out).
Grouping columns into "both bounds" / "right only" / "left only" buckets
and calling np.clip/minimum/maximum with only the bounds that actually
exist avoids ever introducing an inf, so dtype promotion matches pandas
.clip() exactly - verified byte-for-byte against the old pandas-only
implementation across all 4 capping methods x 3 tails, plus the int-dtype
and mixed-dict-coverage cases.

Also found and fixed a real bug introduced while migrating fit(): plain
np.mean/np.std/np.quantile/np.median propagate NaN, unlike pandas'
mean/std/quantile/median which skip NaN by default. With
missing_values="ignore" and NaN present, this silently produced NaN
caps instead of the caps computed from non-null data. Fixed by using
the nan-aware numpy variants (np.nanmean/nanstd/nanquantile/nanmedian).
Caught by tests/test_outliers/test_winsorizer.py::test_transformer_ignores_na_in_df,
which predates this migration but exercises exactly this path.

variables/feature names can be int or str; passing a plain list to
narwhals' .select() only works for string columns, so every .select()
call here uses nw.col(*variables) instead - .select(list_of_ints)
raises InvalidIntoExprError.

Verified: tests/test_outliers full suite - 83 passed, 3 pre-existing
failures in test_check_estimator_outliers.py (sklearn's check_estimator
feeds raw numpy arrays, which check_X() has always rejected per the
narwhals migration's dataframe-only contract; identical failure set
before and after this change). flake8 and mypy clean on the file.
Module imports and runs fit/_transform end-to-end on polars with pandas
import fully blocked. sphinx -W build clean (only the pre-existing
unrelated linkcode_resolve warning). All 4 capping-method x tail
combinations and the Winsoriser/OutlierTrimmer/ArbitraryOutlierCapper
docstring examples produce byte-identical output to the pre-migration
code (checked exact numeric values and dtypes).

Not migrated here (belongs to the 3 follow-on transformer branches):
ArbitraryOutlierCapper.fit()/transform(), Winsoriser's add_indicators
branch (pd.concat), and OutlierTrimmer.transform() (its own .le/.ge/.loc
row-filtering, which doesn't go through BaseOutlier._transform at all)
all still import pandas directly. Existing tests in tests/test_outliers
were left pandas-only rather than parametrized over polars, since they
exercise those still-pandas-only subclasses, not BaseOutlier/
WinsorizerBase directly - parametrizing them now would fail on reasons
unrelated to this file.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
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>
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