class feature_engine.encoding.MeanEncoder(variables=None, missing_values='raise', ignore_format=False, unseen='ignore', smoothing=0.0)[source]#

The MeanEncoder() replaces categories by the mean value of the target for each category.

For example in the variable colour, if the mean of the target for blue, red and grey is 0.5, 0.8 and 0.1 respectively, blue is replaced by 0.5, red by 0.8 and grey by 0.1.

For rare categories, i.e., those with few observations, the mean target value might be less reliable. To mitigate poor estimates returned for rare categories, the mean target value can be determined as a mixture of the target mean value for the entire data set (also called the prior) and the mean target value for the category (the posterior), weighted by the number of observations:

\[mapping = (w_i) posterior + (1-w_i) prior\]

where the weight is calculated as:

\[w_i = n_i t / (s + n_i t)\]

In the previous equation, t is the target variance in the entire dataset, s is the target variance within the category and n is the number of observations for the category.

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 replaces the categories with those numbers (transform).

More details in the User Guide.

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 to fit or transform 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 is False, 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. If True, 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 with the prior.

smoothing: int, float, str, default=0.0

Smoothing factor. Should be >= 0. If 0 then no smoothing is applied, and the mean target value per category is returned without modification. If ‘auto’ then wi is calculated as described above and the category is encoded as the blended values of the prior and the posterior. If int or float, then the wi is calculated as ni / (ni+smoothing). Higher values lead to stronger smoothing (higher weight of prior).


Dictionary with the target mean value per category per variable.


The group of variables that will be transformed.


List with the names of features seen during fit.


The number of features in the train set used in fit.

See also



NAN are introduced when encoding categories that were not present in the training dataset. If this happens, try grouping infrequent categories using the RareLabelEncoder().

Check also the related transformers in the the open-source package Category encoders



Micci-Barreca D. “A Preprocessing Scheme for High-Cardinality Categorical Attributes in Classification and Prediction Problems”. ACM SIGKDD Explorations Newsletter, 2001.


>>> import pandas as pd
>>> from feature_engine.encoding import MeanEncoder
>>> X = pd.DataFrame(dict(x1 = [1,2,3,4,5], x2 = ["c", "c", "c", "b", "a"]))
>>> y = pd.Series([0,1,1,1,0])
>>> me = MeanEncoder()
>>> me.transform(X)
   x1        x2
0   1  0.666667
1   2  0.666667
2   3  0.666667
3   4  1.000000
4   5  0.000000



Learn the target mean value per category, per variable.


Fit to data, then transform it.


Get output feature names for transformation.


Get parameters for this estimator.


Set the parameters of this estimator.


Convert the data back to the original representation.


Encode the categories to numbers.

fit(X, y)[source]#

Learn the mean value of the target for each category of the variable.

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

The target.

fit_transform(X, y=None, **fit_params)[source]#

Fit to data, then transform it.

Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.

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


Additional fit parameters.

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.


Get output feature names for transformation. In other words, returns the variable names of transformed dataframe.

input_featuresarray or list, default=None

This parameter exits only for compatibility with the Scikit-learn pipeline.

  • If None, then feature_names_in_ is used as feature names in.

  • If an array or list, then input_features must match feature_names_in_.

feature_names_out: list

Transformed feature names.


List[Union[str, int]] ..


Get metadata routing of this object.

Please check User Guide on how the routing mechanism works.


A MetadataRequest encapsulating routing information.


Get parameters for this estimator.

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.


Parameter names mapped to their values.


Convert the encoded variable back to the original values.

Note that if unseen was set to ‘encode’, then this method is not implemented.

X: pandas dataframe of shape = [n_samples, n_features].

The transformed dataframe.

X_tr: pandas dataframe of shape = [n_samples, n_features].

The un-transformed dataframe, with the categorical variables containing the original values.


DataFrame ..


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.


Estimator parameters.

selfestimator instance

Estimator instance.


Replace categories with the learned parameters.

X: pandas dataframe of shape = [n_samples, n_features].

The dataset to transform.

X_new: pandas dataframe of shape = [n_samples, n_features].

The dataframe containing the categories replaced by numbers.


DataFrame ..