RareLabelEncoder

API Reference

class feature_engine.encoding.RareLabelEncoder(tol=0.05, n_categories=10, max_n_categories=None, variables=None, replace_with='Rare')[source]

The RareLabelCategoricalEncoder() groups rare / 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 (type ‘object’). A list of variables can be passed as an argument. If no variables are passed as argument, the encoder will find and encode all categorical variables (object type).

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

Parameters
tolfloat, 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.

variableslist, default=None

The list of categorical variables to encode. If None, the encoder will find and select all object type variables.

replace_withstring, default=’Rare’

The category name that will be used to replace infrequent categories.

Attributes

encoder_dict_:

Dictionary with the frequent categories, i.e.., those that will be kept, per variable.

Methods

fit:

Find frequent categories.

transform:

Group rare categories

fit_transform:

Fit to data, then transform it.

fit(X, y=None)[source]

Learn the frequent categories for each variable.

Parameters
Xpandas dataframe of shape = [n_samples, n_features]

The training input samples. Can be the entire dataframe, not just selected variables

yNone

y is not required. You can pass y or None.

Returns
self
Raises
TypeError
  • If the input is not a Pandas DataFrame.

  • If any user provided variable is not categorical

ValueError
  • If there are no categorical variables in the df or the df is empty

  • If the variable(s) contain null values

Warning

If the number of categories in any one variable is less than the indicated in n_categories.

inverse_transform(X)[source]

inverse_transform is not implemented for this transformer yet.

transform(X)[source]

Group infrequent categories. Replace infrequent categories by the string ‘Rare’ or any other name provided by the user.

Parameters
Xpandas dataframe of shape = [n_samples, n_features]

The input samples.

Returns
Xpandas dataframe of shape = [n_samples, n_features]

The dataframe where rare categories have been grouped.

rtype

DataFrame ..

Raises
TypeError

If the input is not a Pandas DataFrame

ValueError
  • If the variable(s) contain null values

  • If dataframe is not of same size as that used in fit()

Example

The RareLabelEncoder() groups infrequent categories altogether into one new category called ‘Rare’ or a different string indicated by the user. 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.

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

from feature_engine.encoding import RareLabelEncoder

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 = RareLabelEncoder(tol=0.03, n_categories=2, variables=['cabin', 'pclass', 'embarked'],
                           replace_with='Rare')

# fit the encoder
encoder.fit(X_train)

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

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

You can also specify the maximum number of categories that can be considered frequent using the max_n_categories parameter.

from feature_engine.encoding import RareLabelEncoder
import pandas as pd
data = {'var_A': ['A'] * 10 + ['B'] * 10 + ['C'] * 2 + ['D'] * 1}
data = pd.DataFrame(data)
data['var_A'].value_counts()
A    10
B    10
C     2
D     1
Name: var_A, dtype: int64
rare_encoder = RareLabelEncoder(tol=0.05, n_categories=3)
rare_encoder.fit_transform(data)['var_A'].value_counts()
A       10
B       10
C        2
Rare     1
Name: var_A, dtype: int64
rare_encoder = RareLabelEncoder(tol=0.05, n_categories=3, max_n_categories=2)
Xt = rare_encoder.fit_transform(data)
Xt['var_A'].value_counts()
A       10
B       10
Rare     3
Name: var_A, dtype: int64