class sklearn.preprocessing.CategoricalEncoder(encoding=’onehot’, categories=’auto’, dtype=<class ‘numpy.float64’>, handle_unknown=’error’)[source]

Encode categorical features as a numeric array.

The input to this transformer should be an array-like of integers or strings, denoting the values taken on by categorical (discrete) features. The features can be encoded using a one-hot (aka one-of-K or dummy) encoding scheme (encoding='onehot', the default) or converted to ordinal integers (encoding='ordinal').

This encoding is needed for feeding categorical data to many scikit-learn estimators, notably linear models and SVMs with the standard kernels.

Read more in the User Guide.

encoding : str, ‘onehot’, ‘onehot-dense’ or ‘ordinal’

The type of encoding to use (default is ‘onehot’):

  • ‘onehot’: encode the features using a one-hot aka one-of-K scheme (or also called ‘dummy’ encoding). This creates a binary column for each category and returns a sparse matrix.
  • ‘onehot-dense’: the same as ‘onehot’ but returns a dense array instead of a sparse matrix.
  • ‘ordinal’: encode the features as ordinal integers. This results in a single column of integers (0 to n_categories - 1) per feature.
categories : ‘auto’ or a list of lists/arrays of values.

Categories (unique values) per feature:

  • ‘auto’ : Determine categories automatically from the training data.
  • list : categories[i] holds the categories expected in the ith column. The passed categories must be sorted and should not mix strings and numeric values.

The used categories can be found in the categories_ attribute.

dtype : number type, default np.float64

Desired dtype of output.

handle_unknown : ‘error’ (default) or ‘ignore’

Whether to raise an error or ignore if a unknown categorical feature is present during transform (default is to raise). When this parameter is set to ‘ignore’ and an unknown category is encountered during transform, the resulting one-hot encoded columns for this feature will be all zeros. In the inverse transform, an unknown category will be denoted as None. Ignoring unknown categories is not supported for encoding='ordinal'.

categories_ : list of arrays

The categories of each feature determined during fitting (in order corresponding with output of transform).

See also

performs a one-hot encoding of integer ordinal features. The OneHotEncoder assumes that input features take on values in the range [0, max(feature)] instead of using the unique values.
performs a one-hot encoding of dictionary items (also handles string-valued features).
performs an approximate one-hot encoding of dictionary items or strings.


Given a dataset with two features, we let the encoder find the unique values per feature and transform the data to a binary one-hot encoding.

>>> from sklearn.preprocessing import CategoricalEncoder
>>> enc = CategoricalEncoder(handle_unknown='ignore')
>>> X = [['Male', 1], ['Female', 3], ['Female', 2]]
CategoricalEncoder(categories='auto', dtype=<... 'numpy.float64'>,
          encoding='onehot', handle_unknown='ignore')
>>> enc.categories_
[array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)]
>>> enc.transform([['Female', 1], ['Male', 4]]).toarray()
array([[ 1.,  0.,  1.,  0.,  0.],
       [ 0.,  1.,  0.,  0.,  0.]])
>>> enc.inverse_transform([[0, 1, 1, 0, 0], [0, 0, 0, 1, 0]])
array([['Male', 1],
       [None, 2]], dtype=object)


fit(X[, y]) Fit the CategoricalEncoder to X.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
inverse_transform(X) Convert back the data to the original representation.
set_params(**params) Set the parameters of this estimator.
transform(X) Transform X using specified encoding scheme.
__init__(encoding=’onehot’, categories=’auto’, dtype=<class ‘numpy.float64’>, handle_unknown=’error’)[source]
fit(X, y=None)[source]

Fit the CategoricalEncoder to X.

X : array-like, shape [n_samples, n_features]

The data to determine the categories of each feature.

fit_transform(X, y=None, **fit_params)[source]

Fit to data, then transform it.

Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.

X : numpy array of shape [n_samples, n_features]

Training set.

y : numpy array of shape [n_samples]

Target values.

X_new : numpy array of shape [n_samples, n_features_new]

Transformed array.


Get parameters for this estimator.

deep : boolean, optional

If True, will return the parameters for this estimator and contained subobjects that are estimators.

params : mapping of string to any

Parameter names mapped to their values.


Convert back the data to the original representation.

In case unknown categories are encountered (all zero’s in the one-hot encoding), None is used to represent this category.

X : array-like or sparse matrix, shape [n_samples, n_encoded_features]

The transformed data.

X_tr : array-like, shape [n_samples, n_features]

Inverse transformed array.


Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as pipelines). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.


Transform X using specified encoding scheme.

X : array-like, shape [n_samples, n_features]

The data to encode.

X_out : sparse matrix or a 2-d array

Transformed input.

Examples using sklearn.preprocessing.CategoricalEncoder