Skip to content

Handle pd.Categorical in encoders #14953

Open

Description

@jnothman

In sklearn.preprocessing._encoders._BaseEncoder, columns with pd.Categorical dtype are converted to arrays.

Xi = check_array(Xi, ensure_2d=False, dtype=None,

If the categories ordering is explicitly specified by the user to the constructor of OneHotEncoder or OrdinalEncoder, then this is fine... but if 'auto' is used, lexicographic ordering will be assumed, disregarding the encoding order determined by the Categorical dtype.

I propose that we raise a warning if:

  • a feature passed to OneHotEncoder or OrdinalEncoder has a Pandas Categorical dtype (is there a way to duck type this?)
  • the categories for that feature are 'auto'
  • the lexicographically sorted features do not match the feature's dtype.categories ordering.

The warning might be something like UserWarning("'auto' categories is used, but the Categorical dtype provided is not consistent with the automatic lexicographic ordering")... or else something more intelligible.

We may change this warning to a FutureWarning with "From version 0.24 the category ordering specified by a Categorical dtype will be respected in encoders."

Activity

  1. added
    Easy
    Moderate
    on Sep 11, 2019
  2. harsh020 commented on Sep 16, 2019

    @harsh020
    Contributor

    @jnothman Hi, I am a bit new to open source and would like to work on this issue, if available.

    Let me know if I got things correct,

    • a feature passed to OneHotEncoder or OrdinalEncoder has a Pandas Categorical dtype (is there a way to duck type this?)
    • the categories for that feature are 'auto'
    • the lexicographically sorted features do not match the feature's dtype.categories ordering.

    if any of the above point hold true we need to raise warning.

    Few queries,

    • should we raise the warning in the __init__ , or during fit or the _fit of the base class.
    • could you please explain a bit on the third point, i.e,
    • the lexicographically sorted features do not match the feature's dtype.categories ordering.

    Few queries in general, if you don't mind answering them -

    • the check_array function in validation.py also used in this mentioned module, does it return the encoded i.e, converts the values to float? If yes, then what about the strings?
    • if the check_array does the main job for us then why use _encode? Why does _encode gives the list of features the dtype of object rather than 'str' or 'int'? Is it just bcs its a list?

    Thanks.

  3. jnothman commented on Sep 16, 2019

    @jnothman
    MemberAuthor
  4. harsh020 commented on Sep 17, 2019

    @harsh020
    Contributor

    @jnothman Thanks.
    Just one more thing the last point

    the lexicographically sorted features do not match the feature's dtype.categories ordering.

    Do we have lexicographically sorted feature list? And what is feature's dtype.categories (is it the self.categories_ list that we are finding?)

    Thanks.

  5. jnothman commented on Sep 18, 2019

    @jnothman
    MemberAuthor
  6. harsh020 commented on Sep 18, 2019

    @harsh020
    Contributor

    if self.categories == 'auto':

    @jnothman Hey, I thought of doing it as -
    In the lines above in line 85, within the if condition we can just check whether the other two conditions are true, that is whether X_list[i] is a categorical dtype and then we can check cats variable has same order as that of X_list[i]'s dtype.category.

    Is it a feasible approach?

    Thanks.

  7. amueller commented on Sep 18, 2019

    @amueller
    Member

    I agree with the proposed behavior, but I doubt this issue will be easy ;) [also this issue is tagged easy and moderate?]

  8. harsh020 commented on Sep 19, 2019

    @harsh020
    Contributor

    @amueller Thanks for the heads up, I won't be opening any PR until I make sure that the approach is correct and get it reviewed by you guys.

    In the lines above in line 85, within the if condition we can just check whether the other two conditions are true, that is whether X_list[i] is a categorical dtype and then we can check cats variable has same order as that of X_list[i]'s dtype.category.

    And from your reply I think that this approach won't be any good. Still working on it.

    Thanks.

  9. harsh020 commented on Sep 19, 2019

    @harsh020
    Contributor

    @jnothman I was going through the check_array function, please correct me if wrong, the function converts any type of object passed to it to an array of features with string values.

    If, so I think we need to verify the three conditions to raise the warning in the check_array function itself.

    Thanks.

  10. jnothman commented on Sep 21, 2019

    @jnothman
    MemberAuthor
  11. thomasjpfan commented on Oct 23, 2019

    @thomasjpfan
    Member

    It would be nice to have support for this now and not wait till 0.24. Is adding option in categories a good idea? (I do not have a good idea what this new option would be called. categories=use-pandas-categories-if-avaliable?)

  12. jnothman commented on Oct 23, 2019

    @jnothman
    MemberAuthor
  13. jorisvandenbossche commented on Oct 28, 2019

    @jorisvandenbossche
    Member

    This duplicates #12086 somewhat, there is some discussion there as well (but basically what @jnothman is proposing here to introduce a warning for it). Will close the other issue.

    I agree with @thomasjpfan that it would be nice to already have the new behaviour now, but I was wondering if we cannot combine that we the changes in OrdinalEncoder for strings with categories='sort' / 'auto' ? For example, if people specify categories='auto', we use the order of the categorical dtype, if categories='sort', we lexicographically sort them (the current behaviour).
    That way it could also be possible to raise a warning in the default case, but having a way for users to both have the new behaviour or keep the old behaviour and silence the warning.

    BTW, I don't think that the actual implementation to use the categorical dtype's categories should be very hard (there is actually a PR for this: #13351), as the required preparatory work to handle a DataFrame column by column is already done (#13253).

  14. 23 remaining items

  15. adrinjalali commented on Aug 22, 2021

    @adrinjalali
    Member

    Doesn't seem like we'd get this in time. Moving to 2.0

  16. modified the milestones: 1.0, 2.0 on Aug 22, 2021
  17. amueller commented on Jan 22, 2024

    @amueller
    Member

    is there a current/ recent issue tracking the support for pd.categorical? So it was added to hgb, not not anywhere else, right?
    I feel like there should be a consistent story, and a lot of conversation has happened over the last .. 5 years? but I can't finda current status or summary.
    I saw #24967, and some related thoughts in #27947, but I haven't seen anything more recent?

  18. glemaitre commented on Jan 22, 2024

    @glemaitre
    Member

    We have a related PR that wants to leverage this feature: #27911

  19. amueller commented on Jan 22, 2024

    @amueller
    Member

    Thanks, that's quite interesting, but also somewhat orthogonal. I was thinking more about the API surface. Currently a user doesn't know whether categorical features are treated correctly or not in a model without reading the documentation of each model and default hyper-parameters. Passing categoricals encoded as integers and with categorical dtype to LogisticRegression, RandomForestClassifier and HistogramGradientBoostingClassifier has very different results.

  20. glemaitre commented on Jan 23, 2024

    @glemaitre
    Member

    Indeed, we did not got the discussion. HistGradientBoosting is the first model that handle categorical feature in a "native manner". I assume that we could have something similar for all tree-based approach avoiding. You get missing values and categorical handling without the need of preprocessing.

    For linear model, we got kind of backward by deprecating normalize parameter and totally rely on the ColumnTransformer. The fact that you need to handle both numerical + categorical + missing values make those models trickier.

    The pattern of using the TableVectorizer from skrubs (https://skrub-data.org/stable/generated/skrub.TableVectorizer.html#skrub.TableVectorizer) could be a way to simplify such pipeline and the same pattern could also potentially used with tree-based models but I'm not sure if this necessary when one deals only with numerical and categorical (when dates come to play then it could be useful).

    But I rather think that we should have the discussion on that topic.

  21. lorentzenchr commented on May 28, 2026

    @lorentzenchr
    Member

    Update as of scikit-learn 1.9

    Note

    This approach works by either detecting a categorical dtype of features or by ordinal-encoding features and then specifying their positions.

    Current Problems

    #18894 demonstrates that the above outlined solution still has problems, in particular for more than 255 categories. One needs:

    • Reduce categories to 255 or split such features into multiple features (unsolved).
    • Apply OrdinalEncoder and then later somehow infer their position which is non-trivial.

    Summary for OrdinalEncoder

    Use cases

    1. Necessary preprocessing step (in a ColumnTransformer) for native categorical support of estimators. The native categorical support is always for categories without order.
    2. Preprocessing for ordered categorical features

    For the first use case, ordering of the categories has no effect on the predictions of the fitted estimator (apart from randomness). For display and inspection purposes, having control over the order might be desirable.
    For the second use, having control over the ordering is necessary.

    Concluding Suggestion: OrdinalEncoder(categories="auto") should use given order of dtype if available.

  22. ThibaultDECO commented on Jun 22, 2026

    @ThibaultDECO
    Contributor

    Is there any update on this issue?

  23. cakedev0 commented on Aug 17, 2026

    @cakedev0
    Member

    I just saw this issue. My PR #34678 should close it I guess, or at least partially close it? (I don't have the time to read all this thread sorry).

    Concluding Suggestion: OrdinalEncoder(categories="auto") should use given order of dtype if available.

    @lorentzenchr do you still think that? I think I agree.

  24. lcrmorin commented on Aug 24, 2026

    @lcrmorin

    I was interested in the initial issue, so read it all... @thomasjpfan @ogrisel read through #15050 and #15396. Looks like it stalled on time, not disagreement - #15396 had real review before you closed it planning a cat.codes rewrite, and @ogrisel's default-behavior suggestion never got picked up. Now, #34678 may already fix this as a side effect of pd.factorize(sort=True) on Categorical dtype. Would a dedicated solution still be needed ?

  25. lorentzenchr commented on Sep 9, 2026

    @lorentzenchr
    Member

    Concluding Suggestion: OrdinalEncoder(categories="auto") should use given order of dtype if available.

    @lorentzenchr do you still think that? I think I agree.

    I would prefer the order as given by the dtype. But more important is to test and document it.

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

    Breaking ChangeModeratemodule:preprocessing

    Type

    No type

    Projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions