ArbitraryDiscretiser¶
API Reference¶
- class feature_engine.discretisation.ArbitraryDiscretiser(binning_dict, return_object=False, return_boundaries=False)[source]¶
The ArbitraryDiscretiser() divides continuous numerical variables into contiguous intervals which limits are determined arbitrarily by the user.
You need to enter a dictionary with variable names as keys, and a list of the limits of the intervals as values. For example
{'var1':[0, 10, 100, 1000], 'var2':[5, 10, 15, 20]}
.ArbitraryDiscretiser() will then sort var1 values into the intervals 0-10, 10-100 100-1000, and var2 into 5-10, 10-15 and 15-20. Similar to
pandas.cut
.The ArbitraryDiscretiser() works only with numerical variables. The discretiser will check if the dictionary entered by the user contains variables present in the training set, and if these variables are numerical, before doing any transformation.
Then it transforms the variables, that is, it sorts the values into the intervals.
- Parameters
- binning_dict: dict
The dictionary with the variable to interval limits pairs. A valid dictionary looks like this:
binning_dict = {'var1':[0, 10, 100, 1000], 'var2':[5, 10, 15, 20]}
- return_object: bool, default=False
Whether the the discrete variable should be returned casted as numeric or as object. If you would like to proceed with the engineering of the variable as if it was categorical, use True. Alternatively, keep the default to False.
Categorical encoders in Feature-engine work only with variables of type object, thus, if you wish to encode the returned bins, set return_object to True.
- return_boundaries: bool, default=False
Whether the output, that is the bin names / values, should be the interval boundaries. If True, it returns the interval boundaries. If False, it returns integers.
Attributes
binner_dict_:
Dictionary with the interval limits per variable.
variables_:
The variables to discretise.
n_features_in_:
The number of features in the train set used in fit.
See also
Methods
fit:
This transformer does not learn any parameter.
transform:
Sort continuous variable values into the intervals.
fit_transform:
Fit to the data, then transform it.
- fit(X, y=None)[source]¶
This transformer does not learn any parameter.
Check dataframe and variables. Checks that the user entered variables are in the train set and cast as numerical.
- Parameters
- X: pandas dataframe of shape = [n_samples, n_features]
The training dataset. Can be the entire dataframe, not just the variables to be transformed.
- y: None
y is not needed in this transformer. You can pass y or None.
- Returns
- self
- Raises
- TypeError
If the input is not a Pandas DataFrame
If any of the user provided variables are not numerical
- ValueError
If there are no numerical variables in the df or the df is empty
If the variable(s) contain null values
- transform(X)[source]¶
Sort the variable values into the intervals.
- Parameters
- X: pandas dataframe of shape = [n_samples, n_features]
The dataframe to be transformed.
- Returns
- X: pandas dataframe of shape = [n_samples, n_features]
The transformed data with the discrete variables.
- rtype
DataFrame
..
- Raises
- TypeError
If the input is not a Pandas DataFrame
- ValueError
If the variable(s) contain null values
If the dataframe is not of the same size as the one used in fit()
Example¶
The ArbitraryDiscretiser() sorts the variable values into contiguous intervals which limits are arbitrarily defined by the user.
The user must provide a dictionary of variable:list of limits pair when setting up the discretiser.
The ArbitraryDiscretiser() works only with numerical variables. The discretiser will check that the variables entered by the user are present in the train set and cast as numerical.
First, let’s load a dataset and plot a histogram of a continuous variable.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
from feature_engine.discretisation import ArbitraryDiscretiser
boston_dataset = load_boston()
data = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)
data['LSTAT'].hist(bins=20)
plt.xlabel('LSTAT')
plt.ylabel('Number of observations')
plt.title('Histogram of LSTAT')
plt.show()

Now, let’s discretise the variable into arbitrarily determined intervals. We want the interval names as integers, so we set return_boundaries to False.
user_dict = {'LSTAT': [0, 10, 20, 30, np.Inf]}
transformer = ArbitraryDiscretiser(
binning_dict=user_dict, return_object=False, return_boundaries=False)
X = transformer.fit_transform(data)
X['LSTAT'].value_counts().plot.bar()
plt.xlabel('LSTAT - bins')
plt.ylabel('Number of observations')
plt.title('Discretised LSTAT')
plt.show()

Alternatively, we can return the interval limits in the discretised variable by setting return_boundaries to True.
transformer = ArbitraryDiscretiser(
binning_dict=user_dict, return_object=False, return_boundaries=True)
X = transformer.fit_transform(data)
X['LSTAT'].value_counts().plot.bar(rot=0)
plt.xlabel('LSTAT - bins')
plt.ylabel('Number of observations')
plt.title('Discretised LSTAT')
plt.show()
