Skip to content

Add support for bools in SimpleImputer #26292

Open

Description

@bryant1410

Describe the workflow you want to enable

Suppose you wanna impute a bool array. Because it has NaNs, it's gonna be of dtype float and work fine:

>>> np.asarray([[True, False, np.nan]]).dtype
dtype('float64')

However, now suppose that the value you pass actually has no NaNs (e.g., because the current data happens to have no NaNs), so there's nothing to impute. In this case, the array is of type bool:

>>> np.asarray([[True, False]]).dtype
dtype('bool')

Which makes the imputation fail because bool isn't supported:

import numpy as np
from sklearn.impute import SimpleImputer

SimpleImputer(strategy="most_frequent").fit(np.asarray([[True, False]]))

This previous code generates an exception:

Traceback (most recent call last):
  # ...
  File ".../lib/python3.10/site-packages/sklearn/utils/_set_output.py", line 140, in wrapped
    data_to_wrap = f(self, X, *args, **kwargs)
  File ".../lib/python3.10/site-packages/sklearn/base.py", line 878, in fit_transform
    return self.fit(X, **fit_params).transform(X)
  File ".../lib/python3.10/site-packages/sklearn/impute/_base.py", line 390, in fit
    X = self._validate_input(X, in_fit=True)
  File ".../lib/python3.10/site-packages/sklearn/impute/_base.py", line 352, in _validate_input
    raise ValueError(
ValueError: SimpleImputer does not support data with dtype bool. Please provide either a numeric array (with a floating point or integer dtype) or categorical data represented either as an array with integer dtype or an array of string values with an object type.

This is because np.asarray([[True, False]]).dtype.kind is "b", which is not in {"i", "u", "f", "O"} and so it fails.

Describe your proposed solution

My solution is to support bool. I believe it shouldn't be a great effort.

Describe alternatives you've considered, if relevant

An alternative solution is for me to create a custom imputer class that copy-pastes the behavior I want from SimpleImputer and makes it work for bools.

Additional context

No response

Activity

  1. bryant1410 commented on Apr 28, 2023

    @bryant1410
    ContributorAuthor

    #2888 is a related issue, but it seems that back then all bools were dtype object. The closed issue is old, so maybe NumPy changed this behavior.

  2. added
    Moderate
    and removed
    Needs Triage
    on May 4, 2023
  3. adrinjalali commented on May 4, 2023

    @adrinjalali
    Member

    This is not an easy issue, and we'd need to support extension arrays as well (like arrays with pd.NA and boolean dtype). This should also be fixed in all imputers.

  4. bryant1410 commented on May 4, 2023

    @bryant1410
    ContributorAuthor

    I think that bools that had NaNs were working fine for me; the problem was when they did not have them.

  5. adrinjalali commented on May 4, 2023

    @adrinjalali
    Member

    Yes, that's because if there's a nan, the whole array is converted into a float64 array, and then everything works fine. Things also work fine if you convert them to dtype=object.

  6. removed their assignment
    on May 4, 2023
  7. Aniket-Mahindrakar commented on Jun 12, 2023

    @Aniket-Mahindrakar

    Only if the strategy selected is "most_frequent" or "constant" should we permit imputing boolean arrays. We must validate the fill_value for the "constant" strategy to see if it is a boolean or not, and if it is, we must fill the NA values with the appropriate boolean value. The outcome is evident in the case of the "most_frequent" method. The array's most prevalent boolean value must be used to swap out the NA values for them. Also, the fill_value should be set to False by default.

    To implement this modification, I would like to submit a pull request.

  8. Higgs32584 commented on Jan 27, 2024

    @Higgs32584
    Contributor

    Could we possibly do something like this?

            if X.dtype.kind == 'b':
                if self.strategy == 'most_frequent':
                    # For most_frequent strategy, impute with the most frequent boolean value
                    most_frequent_bool = np.bincount(X.astype(int)).argmax()
                    self.fill_value = bool(most_frequent_bool)
                elif self.strategy == 'constant':
                    # For constant strategy, use the provided fill_value if it's boolean
                    if isinstance(self.fill_value, bool):
                        self.fill_value = bool(self.fill_value)
                    else:
                        raise ValueError("fill_value should be a boolean for constant strategy.")
    
  9. ritvi-alagusankar commented on Jul 9, 2025

    @ritvi-alagusankar
    Contributor

    @adrinjalali I have opened #31730 to support bools in SimpleImputer. Please take a look when you can and let me know if there are further changes needed.

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

    ModerateNew Featurehelp wanted

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions