OrdinalEncoder
- class sklearn.preprocessing.OrdinalEncoder(*, categories='auto', dtype=<class 'numpy.float64'>, handle_unknown='error', unknown_value=None, encoded_missing_value=nan, min_frequency,
Encode categorical features as an integer 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 are converted to ordinal integers. This results in a single column of integers (0 to n_categories - 1) per feature.
Read more in the User Guide. For a comparison of different encoders, refer to: Comparing Target Encoder with Other Encoders.
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 should not mix strings and numeric
values, and should be sorted in case of numeric values.
The used categories can be found in the categories_ attribute.
Desired dtype of output.
When set to ‘error’ an error will be raised in case an unknown
categorical feature is present during transform. When set to
‘use_encoded_value’, the encoded value of unknown categories will be
set to the value given for the parameter unknown_value. In
inverse_transform, an unknown category will be denoted as None.
When the parameter handle_unknown is set to ‘use_encoded_value’, this
parameter is required and will set the encoded value of unknown
categories. It has to be distinct from the values used to encode any of
the categories in fit. If set to np.nan, the dtype parameter must
be a float dtype.
Encoded value of missing categories. If set to np.nan, then the dtype
parameter must be a float dtype.
Specifies the minimum frequency below which a category will be considered infrequent.
If int, categories with a smaller cardinality will be considered
infrequent.
If float, categories with a smaller cardinality than
min_frequency * n_samples will be considered infrequent.
Specifies an upper limit to the number of output categories for each input
feature when considering infrequent categories. If there are infrequent
categories, max_categories includes the category representing the
infrequent categories along with the frequent categories. If None,
there is no limit to the number of output features.
max_categories do not take into account missing or unknown
categories. Setting unknown_value or encoded_missing_value to an
integer will increase the number of unique integer codes by one each.
This can result in up to max_categories + 2 integer codes.
The categories of each feature determined during fit (in order of
the features in X and corresponding with the output of transform).
This does not include categories that weren’t seen during fit.
Number of features seen during fit.
,)Given a dataset with two features, we let the encoder find the unique values per feature and transform the data to an ordinal encoding.
>>> from sklearn.preprocessing import OrdinalEncoder
>>> enc = OrdinalEncoder()
>>> X = [['Male', 1], ['Female', 3], ['Female', 2]]
>>> enc.fit(X)
>>> enc.inverse_transform([[1, 0], [0, 1]])
array([['Male', 1],
['Female', 2]], dtype=object)
By default, OrdinalEncoder is lenient towards missing values by
propagating them.
>>> import numpy as np
>>> X = [['Male', 1], ['Female', 3], ['Female', np.nan]]
>>> enc.fit_transform(X)
array([[ 1., 0.],
[ 0., 1.],
[ 0., nan]])
You can use the parameter encoded_missing_value to encode missing values.
>>> enc.set_params(encoded_missing_value=-1).fit_transform(X)
array([[ 1., 0.],
[ 0., 1.],
[ 0., -1.]])
Infrequent categories are enabled by setting max_categories or min_frequency.
In the following example, “a” and “d” are considered infrequent and grouped
together into a single category, “b” and “c” are their own categories, unknown
values are encoded as 3 and missing values are encoded as 4.
>>> X_train = np.array(
... [["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3 + [np.nan]],
Fit the OrdinalEncoder to X.
The data to determine the categories of each feature.
Ignored. This parameter exists only for compatibility with
Pipeline.
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params
and returns a transformed version of X.
Get output feature names for transformation.
Input features.
If input_features is None, then feature_names_in_ is
used as feature names in. If is not defined,
then the following input feature names are generated:
.
Get metadata routing of this object.
Please check User Guide on how the routing mechanism works.
A MetadataRequest encapsulating
routing information.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Convert the data back to the original representation.
The transformed data.
Inverse transformed array.
Set output container.
Refer to the user guide for more details and Introducing the set_output API for an example on how to use the API.
Configure output of transform and .
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects
(such as Pipeline). The latter have
parameters of the form <component>__<parameter> so that it’s
possible to update each component of a nested object.
Estimator parameters.
Transform X to ordinal codes.
The data to encode.
Transformed input.
Partial Dependence and Individual Conditional Expectation Plots
Permutation Importance vs Random Forest Feature Importance (MDI)
Names of features seen during fit. Defined only when X
has feature names that are all strings.
infrequent_categories_ : list of ndarrayInfrequent categories for each feature.
Fitted encoder.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Pass only if the estimator accepts additional params in its fit method.
Transformed array.
["x0", "x1", ..., "x(n_features_in_ - 1)"]If input_features is an array-like, then input_features must
match feature_names_in_ if feature_names_in_ is defined.
Same as input features.
"default": Default output format of a transformer
"pandas": DataFrame output
"polars": Polars output
None: Transform configuration is unchanged
Estimator instance.
Estimator instance.