Skip to content

Optimize unique counts for object dtype (as used e.g. by OneHotEncoder) #34385

Closed

Description

@itamarst

Warning

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.

I profiled https://gist.github.com/ogrisel/1b24301bfc90d61ab2138bb7fbf7f623 to get a sense of what it does.

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.

Activity

  1. added
    Needs Triage
    on Jun 24, 2026
  2. itamarst commented on Jun 24, 2026

    @itamarst
    ContributorAuthor

    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.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs Triage

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions