The RareLabelCategoricalEncoder() groups infrequent categories altogether into one new category called ‘Rare’. We need to specify the minimum percentage of observations a category should show to be preserved and the minimum number of unique categories a variable should have to be re-grouped.

The RareLabelCategoricalEncoder() works only with categorical variables. A list of variables can be indiacated, or the imputer will automatically select all categorical variables in the train set.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split

from feature_engine import categorical_encoders as ce

# Load dataset
def load_titanic():
        data = pd.read_csv('https://www.openml.org/data/get_csv/16826755/phpMYEkMl')
        data = data.replace('?', np.nan)
        data['cabin'] = data['cabin'].astype(str).str[0]
        data['pclass'] = data['pclass'].astype('O')
        data['embarked'].fillna('C', inplace=True)
        return data

data = load_titanic()

# Separate into train and test sets
X_train, X_test, y_train, y_test = train_test_split(
                data.drop(['survived', 'name', 'ticket'], axis=1),
                data['survived'], test_size=0.3, random_state=0)

# set up the encoder
encoder = ce.RareLabelCategoricalEncoder(tol=0.03, n_categories=5,
                                         variables=['cabin', 'pclass', 'embarked'])

# fit the encoder

# transform the data
train_t= encoder.transform(X_train)
test_t= encoder.transform(X_test)

{'cabin': Index(['n', 'C', 'B', 'E', 'D'], dtype='object'),
 'pclass': array([2, 3, 1], dtype=object),
 'embarked': array(['S', 'C', 'Q'], dtype=object)}

API Reference

class feature_engine.categorical_encoders.RareLabelCategoricalEncoder(tol=0.05, n_categories=10, variables=None)[source]

The RareLabelCategoricalEncoder() groups rare / infrequent categories in a new category called “Rare”.

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”.

The Encoder will encode only categorical variables (type ‘object’). A list of variables can be passed as an argument. If no variables are passed as argument, the encoder will only encode categorical variables (object type) and ignore the rest.

The encoder first finds the frequent labels for each variable (fit). The encoder then groups the infrequent labels under the new label ‘Rare’ (transform).

  • tol (float, default=0.05) – the minimum frequency a label should have to be considered frequent and not be removed.
  • n_categories (int, default=10) – the minimum number of categories a variable should have in order for the encoder to find frequent labels. If the variable contains less categories, all of them will be considered frequent.
  • variables (list, default=None) – The list of categorical variables that will be encoded. If None, the encoder will find and select all object type variables.

The dictionary containg the frequent categories (that will be kept) for each variable. Categories not present in this list will be replaced by ‘Rare’.

fit(self, X, y=None)[source]

Learns the frequent categories for each variable.

  • X (pandas dataframe of shape = [n_samples, n_features]) – The training input samples. Can be the entire dataframe, not just seleted variables
  • y (None) – There is no need of a target in a transformer, yet the pipeline API requires this parameter. You can leave y as None, or pass it as an argument.
transform(self, X)[source]

Groups rare labels under separate group ‘Rare’.

Parameters:X (pandas dataframe of shape = [n_samples, n_features]) – The input samples.
Returns:X_transformed – The dataframe where rare categories have been grouped.
Return type:pandas dataframe of shape = [n_samples, n_features]