RareLabelEncoder#
- class feature_engine.encoding.RareLabelEncoder(tol=0.05, n_categories=10, max_n_categories=None, replace_with='Rare', variables=None, missing_values='raise', ignore_format=False)[source]#
The RareLabelEncoder() groups rare or infrequent categories in a new category called “Rare”, or any other name entered by the user.
For example in the variable colour, if the percentage of observations for the categories magenta, cyan and burgundy are < 5 %, all those categories will be replaced by the new label “Rare”.
Note
Infrequent labels can also be grouped under a user defined name, for example ‘Other’. The name to replace infrequent categories is defined with the parameter
replace_with
.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 finds the frequent labels for each variable (fit). The encoder then groups the infrequent labels under the new label ‘Rare’ or by another user defined string (transform).
More details in the User Guide.
- Parameters
- tol: float, default=0.05
The minimum frequency a label should have to be considered frequent. Categories with frequencies lower than tol will be grouped.
- n_categories: int, default=10
The minimum number of categories a variable should have for the encoder to find frequent labels. If the variable contains less categories, all of them will be considered frequent.
- max_n_categories: int, default=None
The maximum number of categories that should be considered frequent. If None, all categories with frequency above the tolerance (tol) will be considered frequent. If you enter 5, only the 5 most frequent categories will be retained and the rest grouped.
- replace_with: string, intege or float, default=’Rare’
The value that will be used to replace infrequent categories.
- 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.
- Attributes
- encoder_dict_:
Dictionary with the frequent categories, i.e., those that will be kept, 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.
Examples
>>> import pandas as pd >>> from feature_engine.encoding import RareLabelEncoder >>> X = pd.DataFrame(dict(x1 = [1,2,3,4,5,6], x2 = ["b", "b", "b", "b", "b", "a"])) >>> rle = RareLabelEncoder(n_categories = 1, tol=0.2) >>> rle.fit(X) >>> rle.transform(X) x1 x2 0 1 b 1 2 b 2 3 b 3 4 b 4 5 b 5 6 Rare
Methods
fit:
Find frequent categories.
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.
transform:
Group rare categories
- fit(X, y=None)[source]#
Learn the frequent categories for each variable.
- Parameters
- X: pandas dataframe of shape = [n_samples, n_features]
The training input samples. Can be the entire dataframe, not just selected variables
- y: None
y is not required. You can pass y or None.
- 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_metadata_routing()[source]#
Get metadata routing of this object.
Please check User Guide on how the routing mechanism works.
- Returns
- routingMetadataRequest
A
MetadataRequest
encapsulating routing information.
- 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.
- 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]#
Group infrequent categories. Replace infrequent categories by the string ‘Rare’ or any other name provided by the user.
- Parameters
- X: pandas dataframe of shape = [n_samples, n_features]
The input samples.
- Returns
- X: pandas dataframe of shape = [n_samples, n_features]
The dataframe where rare categories have been grouped.
- rtype
DataFrame
..