You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Optimize unique counts for object dtype (as used e.g. by OneHotEncoder) #34385
This issue is not yet ready for a PR. If you are interested in contributing to scikit-learn, please have a look at our contributing guidelines, and in particular the sections for new contributors and the "Needs triage" label.
If you click through to the interactive flamegraph you'll see sklearn.utils._encode._unique_python is 10% of this profile, and most of that time is actually in counting the unique values.
It's possible to make that significantly faster, with noticeable improvements on the linked benchmark; I'll try to find a benchmark that is more focused too.
Essentially you stick to Python's Counter and do post-processing on that, instead of subclassing and overriding it (cause it has a fast C implementation if you use it directly). I have a sketch that works, and will submit a PR that is less sketchy.
Started writing tests, and also found a bug in the current implementation: if you have multiple different nans (e.g. NAN = float("nan"); [np.nan, NAN, NAN]), you get incorrect counts, because for uniqueness purposes they are different, but the counting code merges their counts. So the counts would be {np.nan: 3, NAN: 3} in this case, instead of the correct {np.nan: 1, NAN: 2}.
In practice this isn't likely to be an issue, because for the common case you only ever get np.nan used as an indication of missing data, but technically it can happen.
Activity
itamarst commentedon Jun 24, 2026
Started writing tests, and also found a bug in the current implementation: if you have multiple different nans (e.g.
NAN = float("nan"); [np.nan, NAN, NAN]), you get incorrect counts, because for uniqueness purposes they are different, but the counting code merges their counts. So the counts would be{np.nan: 3, NAN: 3}in this case, instead of the correct{np.nan: 1, NAN: 2}.In practice this isn't likely to be an issue, because for the common case you only ever get
np.nanused as an indication of missing data, but technically it can happen.