OrdinalEncoder#
- class feature_engine.encoding.OrdinalEncoder(encoding_method='ordered', variables=None, missing_values='raise', ignore_format=False, unseen='ignore')[source]#
The OrdinalEncoder() replaces categories by ordinal numbers (0, 1, 2, 3, etc). The numbers can be ordered based on the mean of the target per category, or assigned arbitrarily.
The encoder will encode only categorical variables by default (type ‘object’ or ‘categorical’). You can pass a list of variables to encode. Alternatively, the encoder will find and encode all categorical variables (type ‘object’ or ‘categorical’).
With
ignore_format=True
you have the option to encode numerical variables as well. The procedure is identical, you can either enter the list of variables to encode, or the transformer will automatically select all variables.The encoder first maps the categories to the numbers for each variable (fit). The encoder then transforms the categories to the mapped numbers (transform).
More details in the User Guide.
- Parameters
- encoding_method: str, default=’ordered’
Desired method of encoding.
‘ordered’: the categories are numbered in ascending order according to the target mean value per category.
‘arbitrary’: categories are numbered arbitrarily.
- variables: list, default=None
The list of categorical variables that will be encoded. If None, the encoder will find and transform all variables of type object or categorical by default. You can also make the transformer accept numerical variables, see the parameter
ignore_format
.- missing_values: string, default=’raise’
Indicates if missing values should be ignored or raised. If
'raise'
the transformer will return an error if the the datasets tofit
ortransform
contain missing values. If'ignore'
, missing data will be ignored when learning parameters or performing the transformation.- ignore_format: bool, default=False
This transformer operates only on variables of type object or categorical. To override this behaviour and allow the transformer to transform numerical variables as well, set to
True
.If
ignore_format
isFalse
, the encoder will automatically select variables of type object or categorical, or check that the variables entered by the user are of type object or categorical. IfTrue
, the encoder will select all variables or accept all variables entered by the user, including those cast as numeric.In short, set to
True
when you want to encode numerical variables.- unseen: string, default=’ignore’
Indicates what to do when categories not present in the train set are encountered during transform. If
'raise'
, then unseen categories will raise an error. If'ignore'
, then unseen categories will be encoded as NaN and a warning will be raised instead. If'encode'
, unseen categories will be encoded as -1.
- Attributes
- encoder_dict_:
Dictionary with the ordinal number per category, per variable.
- variables_:
The group of variables that will be transformed.
- feature_names_in_:
List with the names of features seen during
fit
.- n_features_in_:
The number of features in the train set used in fit.
See also
feature_engine.encoding.RareLabelEncoder
category_encoders.ordinal.OrdinalEncoder
Notes
NAN are introduced when encoding categories that were not present in the training dataset. If this happens, try grouping infrequent categories using the RareLabelEncoder().
There is a similar implementation in the the open-source package Category encoders
References
Encoding into integers ordered following target mean was discussed in the following talk at PyData London 2017:
- 1
Galli S. “Machine Learning in Financial Risk Assessment”. https://www.youtube.com/watch?v=KHGGlozsRtA
Examples
>>> import pandas as pd >>> from feature_engine.encoding import OrdinalEncoder >>> X = pd.DataFrame(dict(x1 = [1,2,3,4], x2 = ["c", "a", "b", "c"])) >>> y = pd.Series([0,1,1,0]) >>> od = OrdinalEncoder(encoding_method='arbitrary') >>> od.fit(X) >>> od.transform(X) x1 x2 0 1 0 1 2 1 2 3 2 3 4 0
You can also consider the order of the target variable:
>>> y = pd.Series([1,0,1,1]) >>> od = OrdinalEncoder(encoding_method='ordered') >>> od.fit(X, y) >>> od.transform(X) x1 x2 0 1 2 1 2 0 2 3 1 3 4 2
Methods
fit:
Find the integer to replace each category in each variable.
fit_transform:
Fit to data, then transform it.
get_feature_names_out:
Get output feature names for transformation.
get_params:
Get parameters for this estimator.
set_params:
Set the parameters of this estimator.
inverse_transform:
Convert the data back to the original representation.
transform:
Encode the categories to numbers.
- fit(X, y=None)[source]#
Learn the numbers to be used to replace the categories in each variable.
- Parameters
- X: pandas dataframe of shape = [n_samples, n_features]
The training input samples. Can be the entire dataframe, not just the variables to be encoded.
- y: pandas series, default=None
The Target. Can be None if
encoding_method='arbitrary'
. Otherwise, y needs to be passed when fitting the transformer.
- fit_transform(X, y=None, **fit_params)[source]#
Fit to data, then transform it.
Fits transformer to
X
andy
with optional parametersfit_params
and returns a transformed version ofX
.- Parameters
- Xarray-like of shape (n_samples, n_features)
Input samples.
- yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None
Target values (None for unsupervised transformations).
- **fit_paramsdict
Additional fit parameters.
- Returns
- X_newndarray array of shape (n_samples, n_features_new)
Transformed array.
- get_feature_names_out(input_features=None)[source]#
Get output feature names for transformation. In other words, returns the variable names of transformed dataframe.
- Parameters
- input_featuresarray or list, default=None
This parameter exits only for compatibility with the Scikit-learn pipeline.
If
None
, thenfeature_names_in_
is used as feature names in.If an array or list, then
input_features
must matchfeature_names_in_
.
- Returns
- feature_names_out: list
Transformed feature names.
- get_params(deep=True)[source]#
Get parameters for this estimator.
- Parameters
- deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators.
- Returns
- paramsdict
Parameter names mapped to their values.
- inverse_transform(X)[source]#
Convert the encoded variable back to the original values.
- Parameters
- X: pandas dataframe of shape = [n_samples, n_features].
The transformed dataframe.
- Returns
- X_tr: pandas dataframe of shape = [n_samples, n_features].
The un-transformed dataframe, with the categorical variables containing the original values.
- rtype
DataFrame
..
- set_params(**params)[source]#
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.- Parameters
- **paramsdict
Estimator parameters.
- Returns
- selfestimator instance
Estimator instance.
- transform(X)[source]#
Replace categories with the learned parameters.
- Parameters
- X: pandas dataframe of shape = [n_samples, n_features].
The dataset to transform.
- Returns
- X_new: pandas dataframe of shape = [n_samples, n_features].
The dataframe containing the categories replaced by numbers.
- rtype
DataFrame
..