Skip to content

Narwhals mean median imputer - #1015

Merged
solegalli merged 6 commits into
narwhals-migrationfrom
narwhals-mean-median-imputer
Aug 30, 2026
Merged

solegalli merged 6 commits into
narwhals-migrationfrom
narwhals-mean-median-imputer

Conversation

@solegalli

Copy link
Copy Markdown
Collaborator

No description provided.

@solegalli
solegalli force-pushed the narwhals-migration branch 2 times, most recently from e9f7d69 to 04c88dc Compare August 30, 2026 15:49
solegalli and others added 2 commits August 30, 2026 18:03
Fit's mean()/median() computation is split by backend and, on the
pandas branch, additionally rewritten to use NumPy directly. Benchmarked
(10k-100k rows x 1-10 cols): narwhals-on-pandas vs pandas-native
.mean()/.median() showed the same real, not minimal, loss (1.0-3.0x)
already documented for BaseImputer's fillna and CategoricalImputer's
mode(), so pandas keeps its own fast path. Going further, benchmarked a
bulk NumPy nanmean/nanmedian pass (to_numpy() + axis=0 reduction,
mirroring MathFeatures' reducer pattern) against pandas-native
.mean()/.median() and found NumPy consistently as fast or faster
(ratios 0.5-1.05x) - a real win, so the pandas branch now uses NumPy
instead of pandas' own methods. For polars, the equivalent NumPy
round-trip was benchmarked too and lost to narwhals' native per-column
mean()/median() expressions (1.8-3.5x slower for mean; mixed but
trending slower for median at scale), so the polars/narwhals branch
computes stats with a single narwhals select() of one expression per
variable instead - benchmarked against a per-column loop and against
select()+to_native().to_dicts() and found select()+rows(named=True) is
equal-or-faster and backend-agnostic (no reliance on a polars-only
to_dicts() method).

All-NaN/all-null columns produce matching values on both backends
(verified directly): NumPy's nanmean/nanmedian warn on all-NaN slices
where pandas' methods don't, so those warnings are suppressed the same
way MathFeatures does. Nullable extension dtypes that would produce
object arrays fall back to pandas' native .mean()/.median(), same
guard as MathFeatures' dtype.kind check.

Found and fixed a real crash: narwhals' select() with zero expressions
collapses row count to 0 too, so stats.rows(named=True)[0] would
IndexError when return_empty=True yields no numerical variables on
polars input. Added an explicit empty-variables guard that skips the
backend branch entirely instead of relying on backend-specific
zero-column behaviour.

Rewrote tests as one parametrized test per behaviour over
pd.DataFrame/pl.DataFrame (a self-contained DATA dict replacing the
pandas-only df_na fixture, matching the CategoricalImputer migration's
pattern), keeping the MeanImputer/MeanMedianImputer deprecation-warning
parametrization on top.

Verified: tests/test_imputation full suite - 99 passed (up from 95
pre-migration, same tests plus new polars parametrizations), same 7
pre-existing failures in test_check_estimator_imputers.py (sklearn's
check_estimator feeds raw numpy arrays, rejected by check_X's
dataframe-only contract from the base migration - confirmed identical
root cause against the pre-migration baseline via git stash). flake8
and mypy clean. mean_median.py's actual import chain (base_imputer,
dataframe_checks, variable_handling) verified pandas-free with pandas
blocked, using direct module loading to bypass the sibling
not-yet-migrated imputers in imputation/__init__.py. sphinx -W build
clean (only the pre-existing unrelated linkcode_resolve warning). Every
doc example (docstring pandas/polars examples and the new "With
polars" section in MeanImputer.rst) re-run against live output.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
check_X now returns a narwhals DataFrame; fit() passed it to
find/check_numerical_variables, the is_pandas mean()/median() fast path and
_get_feature_names_in, which then took their non-pandas path (spurious
is_pandas_dataframe warning, hard failure on integer column names). check_X
is pure validation, so stop rebinding X and keep working with the native
input.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@solegalli
solegalli force-pushed the narwhals-mean-median-imputer branch from 7b8f6d5 to a34cbcf Compare August 30, 2026 16:04
Comment thread feature_engine/imputation/mean_median.py Outdated
Comment thread feature_engine/imputation/mean_median.py Outdated
Comment thread feature_engine/imputation/mean_median.py Outdated
@solegalli
solegalli merged commit 73c0041 into narwhals-migration Aug 30, 2026
3 of 10 checks passed
@solegalli
solegalli deleted the narwhals-mean-median-imputer branch August 30, 2026 16:59
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