Skip to content

PRF Fast path for pandas Series in encoders - #34678

Open
cakedev0 wants to merge 28 commits into
scikit-learn:mainfrom
cakedev0:encoders/pandas_fast_path
Open

cakedev0 wants to merge 28 commits into
scikit-learn:mainfrom
cakedev0:encoders/pandas_fast_path

Conversation

@cakedev0

@cakedev0 cakedev0 commented Aug 7, 2026 •

Copy link
Copy Markdown
Member

This is my third attempt at this 😅 but I'm really convinced this is the good one.

Reference Issues/PRs

Towards #14953 (or even closes it?)

Previous attempts for reference:

This PR is an in-between: it's only for pandas (so no narwhals overhead), but has the same nice implementation pattern than the narwhals one (specialized paths in sklearn/utils/_encode.py).

What does this implement/fix? Explain your changes.

It changes _BaseEncoder._check_X to keep string or categorical dataframe columns as Series instead of forcing everything through check_array into numpy object arrays. It also simplifies it overall, which leads to a slight speed-up for the object path (which still goes through numpy conversion, etc. see comments in the code about why this choice).

Then in _unique/_encode, those Series are routed through special paths (_unique_pandas/_encode_pandas) that are particularly efficient for categorical dtype:

  • _unique_pandas leverages pd.factorize
  • _encode_pandas leverages pd.Index(uniques).get_indexer(values)

It also adds/fixes the support for recent pandas pyarrow-backed string Series (added non regression test parametrized over string[python]/string[pyarrow]).

Also, fixing code coverage led me to port the same optimization in LabelEncoder (to naturally use the return_inverse branch of _unique_pandas). I checked performance impact quickly, it's a clear win, similar to what happens with encoders.

AI usage disclosure

I used AI assistance for:

  • Quickly testing many paths, and running benchmarks on them.
  • Code generation (but very micro-managed, so should be very close to what I would have written by hand)

Any other comments?

An other nice thing with this PR: it compounds well with the "transform cache" idea I started exploring here cakedev0#13

Benchmarks

I ran python benchmarks/bench_encoders.py -l pandas -e ordinal,ordinal-max10 -o main.csv (pandas only, OrdinalEncoder (without and with counts computing), 5 OpenML datasets), on main and this branch and compared results.

No regressions anywhere in this matrix and some very big speed-ups for the categorical case (and could be even much more with a larger number of rows).

Object path is sometimes faster thanks to simplifications in _check_X only (no other optimizations for this path).

Numbers below are main_ms → this_branch_ms (speedup).

ordinal

dataset n format fit transform transform (1 row)
house_prices 1460 object 8.1 → 3.2 (2.5x) 11.8 → 6.9 (1.7x) 7.3 → 2.3 (3.2x)
house_prices 1460 string error → 8.4 error → 19.8 error → 11.5
house_prices 1460 categorical 17.4 → 8.1 (2.1x) 21.4 → 11.5 (1.9x) 11.2 → 11.1 (1.0x)
bank_marketing 5000 object 53.7 → 27.2 (2.0x) 113.4 → 86.7 (1.3x) 36.8 → 10.1 (3.6x)
bank_marketing 5000 string 122.1 → 54.5 (2.2x) 192.3 → 136.5 (1.4x) 41.1 → 41.3 (1.0x)
bank_marketing 5000 categorical 143.0 → 32.8 (4.4x) 207.9 → 51.9 (4.0x) 51.7 → 40.3 (1.3x)
amazon_employee_access 32769 object 16.5 → 14.7 (1.1x) 31.6 → 30.2 (1.0x) 5.8 → 4.8 (1.2x)
amazon_employee_access 32769 string 36.3 → 12.1 (3.0x) 56.2 → 31.6 (1.8x) 6.1 → 4.5 (1.4x)
amazon_employee_access 32769 categorical 45.2 → 11.3 (4.0x) 62.9 → 5.0 (12.6x) 6.7 → 3.9 (1.7x)
kddcup09_churn 50000 object 88.3 → 81.2 (1.1x) 199.0 → 192.5 (1.0x) 30.1 → 25.6 (1.2x)
kddcup09_churn 50000 string error → 66.5 error → 265.3 error → 24.1
kddcup09_churn 50000 categorical 248.1 → 61.8 (4.0x) 363.8 → 62.7 (5.8x) 36.8 → 33.2 (1.1x)
kick 72983 object 38.1 → 26.3 (1.4x) 120.4 → 105.9 (1.1x) 4.0 → 1.8 (2.2x)
kick 72983 string error → 28.8 error → 164.2 error → 6.2
kick 72983 categorical 133.1 → 12.3 (10.8x) 210.3 → 17.9 (11.7x) 5.8 → 6.5 (0.9x)

ordinal-max10

Very similar speed-ups

Details
dataset n format fit transform transform (1 row)
house_prices 1460 object 12.1 → 6.8 (1.8x) 11.9 → 6.9 (1.7x) 7.4 → 2.3 (3.2x)
house_prices 1460 string error → 9.3 error → 20.0 error → 11.5
house_prices 1460 categorical 22.0 → 9.0 (2.4x) 22.3 → 11.4 (2.0x) 11.3 → 11.1 (1.0x)
bank_marketing 5000 object 103.7 → 77.0 (1.3x) 113.6 → 87.0 (1.3x) 35.9 → 10.1 (3.6x)
bank_marketing 5000 string 175.0 → 58.7 (3.0x) 193.6 → 139.3 (1.4x) 41.2 → 41.4 (1.0x)
bank_marketing 5000 categorical 193.3 → 37.4 (5.2x) 208.2 → 52.8 (3.9x) 52.8 → 40.5 (1.3x)
amazon_employee_access 32769 object 41.5 → 39.3 (1.1x) 32.1 → 28.9 (1.1x) 5.9 → 4.9 (1.2x)
amazon_employee_access 32769 string 65.3 → 19.4 (3.4x) 59.2 → 32.6 (1.8x) 6.2 → 4.6 (1.3x)
amazon_employee_access 32769 categorical 71.7 → 18.5 (3.9x) 63.9 → 5.4 (11.8x) 6.7 → 4.0 (1.7x)
kddcup09_churn 50000 object 226.7 → 217.3 (1.0x) 208.0 → 197.7 (1.1x) 30.1 → 25.7 (1.2x)
kddcup09_churn 50000 string error → 100.3 error → 269.7 error → 24.3
kddcup09_churn 50000 categorical 404.6 → 96.9 (4.2x) 390.6 → 71.1 (5.5x) 35.8 → 33.2 (1.1x)
kick 72983 object 117.0 → 93.8 (1.2x) 124.9 → 110.3 (1.1x) 4.0 → 1.9 (2.1x)
kick 72983 string error → 34.3 error → 170.9 error → 6.4
kick 72983 categorical 198.1 → 17.5 (11.3x) 215.2 → 22.6 (9.5x) 5.8 → 6.6 (0.9x)

Add a pandas-specific fast path in `_BaseEncoder._check_X`/`_unique`/`_encode`
that avoids materializing Categorical/Arrow-backed pandas columns into a full
per-row numpy object array before uniquing/encoding. Non-numeric pandas
columns are kept as native Series through `_check_X`, and `_unique`/`_encode`
dispatch to `pandas.factorize`/`Series.unique`/`Index.get_indexer` for
non-object dtypes, falling back to the existing set()/dict-based path for
plain object dtype where pandas' own call overhead isn't worth paying.
@cakedev0 cakedev0 changed the title [WIP] PRF Fast path for pandas Series in encoders PRF Fast path for pandas Series in encoders Aug 7, 2026
@cakedev0
cakedev0 marked this pull request as ready for review August 7, 2026 21:05
@DeaMariaLeon

DeaMariaLeon commented Aug 10, 2026 •

Copy link
Copy Markdown
Member

Maybe @MarcoGorelli has an opinion?
EDIT: For context there was some talk during a call today that Narwhals introduces a lot of overhead sometimes.

Comment thread sklearn/utils/_encode.py Outdated
"""
import pandas as pd

codes, index = pd.factorize(values, sort=True, use_na_sentinel=False)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't this change the order of the categories compared to 'unique()'?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The sort=True should avoid that.

Comment thread sklearn/utils/_encode.py Resolved
@MarcoGorelli

Copy link
Copy Markdown
Contributor

Maybe @MarcoGorelli has an opinion? EDIT: For context there was some talk during a call today that Narwhals introduces a lot of overhead sometimes.

thanks for the ping!

In general we try to keep overhead minimal (even negative sometimes, compared with how most people write pandas https://narwhals-dev.github.io/narwhals/overhead/)

@cakedev0 may I ask which operations incurred overhead? I'm aware of the sort issue raising for categorical columns in pyarrow, but I've not come across any performance issues - more than happy to address this upstream if you point us in the right direction 🙏

@cakedev0

Copy link
Copy Markdown
Member Author

It was a while ago already 😅 but IIRC it was not really that narwhals adds overhead in itself, it's either one of those:

  • the API doesn't provide the primitives I need: having factorize will help here.
  • the API requires additional "safety steps" to make sure the pandas path respect the documented behavior (I think narwhals aligns more naturally with polars, am I correct?).

I asked a LLM to try to implement narwhals equivalent of the _encode_pandas and _unique_pandas of this PR, trying to match their speed and here is the answer (which aligns with my experience as far as I remember):

[LLM speaking:]

Result: a genuine narwhals implementation cannot beat the current pandas fast path — it's consistently 2–11x slower.

Root cause, not just overhead:

  • Narwhals has no public factorize/get_indexer primitive. Its closest analog, replace_strict, is implemented on the pandas backend as pd.Index(old).get_indexer(native) — i.e. exactly what _encode_pandas already does — but then wraps it in extra work (building a new Series, .where() masking for the default, dtype conversion) that our direct call skips. So encode is close-ish (1.1–1.3x slower for string, 3–5x for category) but never faster.
  • _unique_pandas uses pd.factorize, a single hash-table pass. The narwhals equivalent (drop_nulls() → unique() → sort(nulls_last=True)) is multiple materializing passes, and for string dtype this was 5–11x slower — the biggest gap in the whole benchmark.
  • A value_counts()-based variant (single pass for uniques+counts) didn't help; it still needs a second pass for return_inverse, and building/sorting the small value_counts frame in Python added its own cost.

The only variant that matched pandas performance was the "hybrid" one — which special-cases if backend is pandas: call the existing _unique_pandas/_encode_pandas. That's not really a narwhals implementation, it's the current code with a narwhals dispatch wrapper on top (pure overhead on the hot path), and it only earns its keep if the goal is to also support polars/pyarrow columns through the same functions.

[me again:]

The last paragraph is probably what I'll do in the next PR: replace the pandas path by a narwhals path with inside it a fast path for pandas.

I could have started by the narwhals path and then specialize it for pandas, but personally I would not approve a perf PR with an unclear speed trade-off.

@lcrmorin

lcrmorin commented Aug 24, 2026 •

Copy link
Copy Markdown

Hey @cakedev0 I noticed there's no test covering OrdinalEncoder(categories="auto") against a pd.Categorical with a deliberately non-alphabetical order (checked the diff and the rest of the test file, nothing exercises that case). Since pd.factorize(sort=True) follows the dtype's own category order rather than sorting alphabetically, adding that test would lock in behavior that effectively closes #14953. Mind if I put together that test and open it as a follow-up?

@ogrisel ogrisel moved this from PR waiting for reviews to In progress in Labs Sep 14, 2026
@cakedev0

Copy link
Copy Markdown
Member Author

Hi @lcrmorin

Since pd.factorize(sort=True) follows the dtype's own category order rather than sorting alphabetically

Thank you, this is a good catch and this is a problem, currently with this PR:

  • pandas categorical use dtype
  • polars enum use alphabetical order

For now, I will maintain alphabetical order for the pandas path too.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants