Skip to content

LogitEncoder(verbose=0, cols=None, drop_invariant=False, return_df=True, handle_missing='value', handle_unknown='value', encoding='log_odds', model='joint', backend='sklearn', C=1.0, l1_ratio=0.0, cv=5, reference='most_frequent', interactions=None, return_uncertainty=False, max_iter=5000, n_jobs=None, random_state=None, min_group_size=None, min_group_name=None, combine_min_nan_groups=None, composite_cols=None, keep_components=False)

Bases: SupervisedTransformerMixin, BaseEncoder

Encodes categories with values from a logit model of the outcome.

Each categorical column is dummy-coded and a logit model of the outcome is fit on the dummies. Each category is then replaced by one of three values from that model (see encoding):

  • 'coefficient': the level's coefficient, which is the log odds ratio of the outcome for that level against the column's reference level.
  • 'log_odds': the average log odds of the outcome when the column is set to that level. In a univariate model, it is the intercept plus the coefficient.
  • 'marginal_effect': the average change in the probability of the outcome from moving the column from the reference level to that level, holding the other columns as observed (a discrete change, since the level is a dummy).

The model can be one logit with every column's dummies ('joint', the default), whose values are adjusted for the other columns, or a separate logit for each column ('univariate'). Either sklearn or statsmodels can fit it. Both minimize the same penalized log loss, so they agree up to solver tolerances.

An outcome with more than two classes is modeled with a logit for each class against a reference class (the most frequent class), so each categorical column becomes one column per other class, named '_'. With two classes, the first (in sorted order) is the reference class and each column stays one column.

interactions adds a column for each listed combination of columns, encoded like any other categorical column, and return_uncertainty adds each value's standard error ('_se') and each category's number of training rows ('_count'), so that a model can trust the values of rare categories less.

Encoding training rows with a model fit on those same rows leaks the outcome into the features. So, like sklearn's TargetEncoder, fit_transform (and transform given y) cross-fits: each training row is encoded by a model fit on the other folds. transform without y uses the model fit on all of the training data. Set cv to None to turn cross-fitting off.

LogitEncoder is a drop-in replacement for the supervised category_encoders encoders: it takes the same parameters (cols, drop_invariant, return_df, handle_missing, handle_unknown, min_group_size, min_group_name, combine_min_nan_groups, composite_cols, and keep_components, in the same order as TargetEncoder's), has the same mapping, ordinal_encoder, invariant_cols, and feature_names_out_ attributes and get_feature_names_out and get_feature_names_in methods, and passes extra DataFrame columns through transform. It is also a full sklearn transformer: it works in pipelines, column transformers, cross-validation, and grid searches, supports set_output, and passes sklearn's check_estimator. The one difference is that cols keeps the value it was given; the columns that were encoded are in cols_.

LogitEncoder is not a dataclass because sklearn reads an estimator's parameters from its __init__ signature and requires that __init__ only store them.

Attributes:

Name Type Description
mapping_

for each encoded column (including interactions and composite columns), the encoded value of each category's ordinal code, fit on all of the training data: a series for a binary outcome, or a DataFrame with a column per modeled class. The codes are in ordinal_encoder_.category_mapping. get_mapping gives the same values by category.

error_mapping_

the standard errors of mapping_'s values, if return_uncertainty is True.

count_mapping_

for each encoded column, the number of training rows with each category's ordinal code, if return_uncertainty is True.

ordinal_encoder_

the fitted category_encoders.OrdinalEncoder that turns categories into ordinal codes.

classes_

the outcome's classes, in sorted order.

reference_class_

the class that the others are compared with.

modeled_classes_

the other classes, which each get a column.

interaction_cols_

the names of the interaction columns.

composite_members_

for each composite column, its member columns.

min_group_lumping_

for each column with categories lumped together by min_group_size, the group that each lumped category joined.

n_iter_

largest number of solver iterations that any of the models fit on all of the training data used.

cols_

the input columns that were encoded on their own.

invariant_cols_

the output columns dropped by drop_invariant.

feature_names_out_

names of the output columns.

n_features_in_

number of columns seen in fitting.

feature_names_in_

names of the columns seen in fitting, if they were all strings.

Examples:

>>> import pandas as pd
>>> from logit_encode import LogitEncoder
>>> X = pd.DataFrame({'color': ['red', 'blue', 'red', 'green'] * 25})
>>> y = pd.Series([1, 0, 0, 1] * 25)
>>> encoder = LogitEncoder(encoding = 'log_odds', cv = None)
>>> encoded = encoder.fit_transform(X, y)
>>> encoded['color'].round(2).abs().unique().tolist()
[0.0, 2.29]
>>> table = encoder.get_mapping('color').round(2) + 0.0
>>> table
           color
category
red         0.00
blue       -2.29
green       2.29
<missing>   0.00
<unknown>   0.00
>>> recovered = encoder.inverse_transform(encoder.transform(X))
>>> recovered['color'][:4].tolist()
['red', 'blue', 'red', 'green']

Stores the parameters without validating them, as sklearn requires.

The parameters are checked when the encoder is fit. They can be passed by position, in the same order as category_encoders' TargetEncoder for the parameters the two share.

Parameters:

Name Type Description Default
verbose int

verbosity of the output. 0 for none.

0
cols list[Any] | str | None

columns to encode. If None, every object, string, and categorical column is encoded, as in category_encoders. If 'all', every column is encoded.

None
drop_invariant bool

whether to drop encoded columns with no variance.

False
return_df bool

whether transform returns a pandas DataFrame (otherwise, a numpy array).

True
handle_missing Any

how to encode missing values: 'value' (treat them as a category, or use the prior if none were seen in fitting), 'return_nan', 'error', a number, or a callable as in category_encoders.

'value'
handle_unknown Any

how to encode categories not seen in fitting: 'value' (the prior), 'return_nan', 'error', a number, or a callable as in category_encoders. The prior is the column's average encoded value over the training rows.

'value'
encoding Encoding

'log_odds', 'coefficient', or 'marginal_effect'.

'log_odds'
model Model

'joint' (one logit model with every column) or 'univariate' (a logit model for each column).

'joint'
backend Backend

'sklearn' or 'statsmodels'. statsmodels builds a dense design matrix, so sklearn is much faster for columns with many categories.

'sklearn'
C float | None

inverse strength of the penalty on the coefficients, as in sklearn.linear_model.LogisticRegression. Smaller values shrink rare categories more toward the reference level. None fits an unpenalized model, whose coefficients for categories with only one outcome grow without bound.

1.0
l1_ratio float

share of the penalty that is L1 (lasso) rather than L2 (ridge), from 0 to 1.

0.0
cv int | None

number of folds for cross-fitting the training rows, or None to encode them with the model fit on all of them.

5
reference Reference

how to choose each column's reference level, which has a coefficient of 0: 'most_frequent', 'first' (the first category seen), or None (no reference level, so every category gets a dummy and coefficients are relative to the intercept).

'most_frequent'
interactions list[tuple[Any, ...]] | None

combinations of columns (any columns of X) to encode as one more categorical column each, such as [('state', 'county')], keeping their member columns. Each is named by joining its columns' names with '|', and a row with a missing value in any of them has a missing value in the combination.

None
return_uncertainty bool

whether to add each encoded value's standard error ('_se') and each category's number of training rows ('_count'). The standard errors are exact (up to the L1 part of the penalty) for univariate models and ignore the information that columns share in joint models.

False
max_iter int

largest number of solver iterations.

5000
n_jobs int | None

number of parallel jobs for fitting the univariate models and the cross-fitting folds, as in joblib. None means 1 unless in a joblib.parallel_config context.

None
random_state int | RandomState | None

seed for shuffling the cross-fitting folds.

None
min_group_size float | None

as in category_encoders, the smallest number (an int) or share of the rows (a float) that a category needs to be encoded on its own. Smaller categories are lumped into one group before fitting. None turns lumping off.

None
min_group_name str | None

name of the lumped group. If None, the lumped categories' names are joined (in sorted order) with '_'.

None
combine_min_nan_groups bool | str | None

whether missing values join the lumped group: True (if they are themselves too few, the default for None), 'force' (always), or False (never).

None
composite_cols list[tuple[Any, ...]] | None

as in category_encoders, combinations of columns to encode as one column each, named by joining their names with '|'. Unlike interactions, their member columns are dropped from the output unless keep_components is True.

None
keep_components bool

whether the members of composite_cols are also encoded on their own and kept in the output.

False
Source code in src/logit_encode/logit_encoder.py
def __init__(  # noqa: PLR0917
    self,
    verbose: int = 0,
    cols: list[Any] | str | None = None,
    drop_invariant: bool = False,
    return_df: bool = True,
    handle_missing: Any = 'value',
    handle_unknown: Any = 'value',
    encoding: _logit_models.Encoding = 'log_odds',
    model: _logit_models.Model = 'joint',
    backend: _logit_models.Backend = 'sklearn',
    C: float | None = 1.0,
    l1_ratio: float = 0.0,
    cv: int | None = 5,
    reference: _logit_models.Reference = 'most_frequent',
    interactions: list[tuple[Any, ...]] | None = None,
    return_uncertainty: bool = False,
    max_iter: int = 5000,
    n_jobs: int | None = None,
    random_state: int | np.random.RandomState | None = None,
    min_group_size: float | None = None,
    min_group_name: str | None = None,
    combine_min_nan_groups: bool | str | None = None,
    composite_cols: list[tuple[Any, ...]] | None = None,
    keep_components: bool = False) -> None:
    """Stores the parameters without validating them, as sklearn requires.

    The parameters are checked when the encoder is fit. They can be
    passed by position, in the same order as `category_encoders`'
    `TargetEncoder` for the parameters the two share.

    Args:
        verbose: verbosity of the output. 0 for none.
        cols: columns to encode. If None, every object, string, and
            categorical column is encoded, as in `category_encoders`. If
            'all', every column is encoded.
        drop_invariant: whether to drop encoded columns with no variance.
        return_df: whether `transform` returns a pandas DataFrame
            (otherwise, a numpy array).
        handle_missing: how to encode missing values: 'value' (treat them
            as a category, or use the prior if none were seen in
            fitting), 'return_nan', 'error', a number, or a callable as
            in `category_encoders`.
        handle_unknown: how to encode categories not seen in fitting:
            'value' (the prior), 'return_nan', 'error', a number, or a
            callable as in `category_encoders`. The prior is the column's
            average encoded value over the training rows.
        encoding: 'log_odds', 'coefficient', or 'marginal_effect'.
        model: 'joint' (one logit model with every column) or
            'univariate' (a logit model for each column).
        backend: 'sklearn' or 'statsmodels'. statsmodels builds a dense
            design matrix, so sklearn is much faster for columns with
            many categories.
        C: inverse strength of the penalty on the coefficients, as in
            `sklearn.linear_model.LogisticRegression`. Smaller values
            shrink rare categories more toward the reference level. None
            fits an unpenalized model, whose coefficients for categories
            with only one outcome grow without bound.
        l1_ratio: share of the penalty that is L1 (lasso) rather than L2
            (ridge), from 0 to 1.
        cv: number of folds for cross-fitting the training rows, or None
            to encode them with the model fit on all of them.
        reference: how to choose each column's reference level, which has
            a coefficient of 0: 'most_frequent', 'first' (the first
            category seen), or None (no reference level, so every
            category gets a dummy and coefficients are relative to the
            intercept).
        interactions: combinations of columns (any columns of X) to
            encode as one more categorical column each, such as
            [('state', 'county')], keeping their member columns. Each is
            named by joining its columns' names with '|', and a row with
            a missing value in any of them has a missing value in the
            combination.
        return_uncertainty: whether to add each encoded value's standard
            error ('<column>_se') and each category's number of training
            rows ('<column>_count'). The standard errors are exact (up to
            the L1 part of the penalty) for univariate models and ignore
            the information that columns share in joint models.
        max_iter: largest number of solver iterations.
        n_jobs: number of parallel jobs for fitting the univariate models
            and the cross-fitting folds, as in joblib. None means 1
            unless in a `joblib.parallel_config` context.
        random_state: seed for shuffling the cross-fitting folds.
        min_group_size: as in `category_encoders`, the smallest number
            (an int) or share of the rows (a float) that a category needs
            to be encoded on its own. Smaller categories are lumped into
            one group before fitting. None turns lumping off.
        min_group_name: name of the lumped group. If None, the lumped
            categories' names are joined (in sorted order) with '_'.
        combine_min_nan_groups: whether missing values join the lumped
            group: True (if they are themselves too few, the default for
            None), 'force' (always), or False (never).
        composite_cols: as in `category_encoders`, combinations of
            columns to encode as one column each, named by joining their
            names with '|'. Unlike `interactions`, their member columns
            are dropped from the output unless `keep_components` is True.
        keep_components: whether the members of `composite_cols` are also
            encoded on their own and kept in the output.

    """
    super().__init__(
        verbose = verbose,
        cols = cols,
        drop_invariant = drop_invariant,
        return_df = return_df,
        handle_missing = handle_missing,
        handle_unknown = handle_unknown)
    self.encoding = encoding
    self.model = model
    self.backend = backend
    self.C = C
    self.l1_ratio = l1_ratio
    self.cv = cv
    self.reference = reference
    self.interactions = interactions
    self.return_uncertainty = return_uncertainty
    self.max_iter = max_iter
    self.n_jobs = n_jobs
    self.random_state = random_state
    self.min_group_size = min_group_size
    self.min_group_name = min_group_name
    self.combine_min_nan_groups = combine_min_nan_groups
    self.composite_cols = composite_cols
    self.keep_components = keep_components

invariant_cols property

Returns invariant_cols_, under category_encoders' name.

Returns:

Type Description
list[Any]

The output columns dropped by drop_invariant.

mapping property

Returns mapping_, under category_encoders' name.

Returns:

Type Description
dict[Any, Series | DataFrame]

The fitted mapping from ordinal codes to encoded values.

ordinal_encoder property

Returns ordinal_encoder_, under category_encoders' name.

Returns:

Type Description
OrdinalEncoder

The fitted ordinal encoder.

fit(X, y=None, **fit_params)

Fits the encoder.

Parameters:

Name Type Description Default
X Any

training data, as a DataFrame or a two-dimensional array.

required
y Any

training outcome.

None
**fit_params Any

unused; accepted for sklearn compatibility.

{}

Raises:

Type Description
ValueError

if the inputs are invalid.

Returns:

Type Description
BaseEncoder

The fitted encoder.

Source code in src/logit_encode/utils.py
def fit(self, X: Any, y: Any = None, **fit_params: Any) -> BaseEncoder:
    """Fits the encoder.

    Args:
        X: training data, as a DataFrame or a two-dimensional array.
        y: training outcome.
        **fit_params: unused; accepted for sklearn compatibility.

    Raises:
        ValueError: if the inputs are invalid.

    Returns:
        The fitted encoder.

    """
    y_series = self._validate_fit_target(y)
    X_frame = self._validate_input(X, reset = True)
    y_series = self._align_target(y_series, X_frame)
    self._validate_handle_strategies()
    self.cols_ = self._select_columns(X_frame)
    self._check_missing(X_frame)
    self._fit(X_frame, y_series)
    self._output_spec = self._output_columns()
    labels = pd.Index([column.label for column in self._output_spec])
    if labels.has_duplicates:
        duplicates = sorted(set(labels[labels.duplicated()]), key = str)
        raise ValueError(
            f'The output would have duplicate columns {duplicates}. '
            'Rename the input columns (or outcome classes) that make '
            'them.')
    self.invariant_cols_: list[Any] = []
    if self.drop_invariant:
        encoded = self._encode(X_frame.copy())
        self.invariant_cols_ = [
            column.label for column in self._output_spec
            if column.encoded
            and len(pd.unique(encoded[column.label])) <= 1]
    self.feature_names_out_ = self.get_feature_names_out()
    return self

fit_transform(X, y=None, **fit_params)

Fits the encoder and encodes the training data with its outcome.

Parameters:

Name Type Description Default
X Any

training data.

required
y Any

training outcome.

None
**fit_params Any

passed to fit.

{}

Raises:

Type Description
ValueError

if y is None.

Returns:

Type Description
DataFrame | ndarray

The encoded training data.

Source code in src/logit_encode/utils.py
def fit_transform(
    self,
    X: Any,
    y: Any = None,
    **fit_params: Any) -> pd.DataFrame | np.ndarray:
    """Fits the encoder and encodes the training data with its outcome.

    Args:
        X: training data.
        y: training outcome.
        **fit_params: passed to `fit`.

    Raises:
        ValueError: if `y` is None.

    Returns:
        The encoded training data.

    """
    if y is None:
        raise ValueError(
            f'{type(self).__name__} requires y to be passed, but the '
            'target y is None.')
    encoder = cast('BaseEncoder', self)
    encoder.fit(X, y, **fit_params)
    return self.transform(X, y)

get_feature_names()

Returns the output column names (deprecated, as in sklearn).

Kept for code written for category_encoders, which also deprecates it.

Returns:

Type Description
ndarray

The same names as get_feature_names_out.

Source code in src/logit_encode/utils.py
def get_feature_names(self) -> np.ndarray:
    """Returns the output column names (deprecated, as in sklearn).

    Kept for code written for `category_encoders`, which also deprecates
    it.

    Returns:
        The same names as `get_feature_names_out`.

    """
    warnings.warn(
        '`get_feature_names` is deprecated in all of sklearn. Use '
        '`get_feature_names_out` instead.',
        FutureWarning,
        stacklevel = 2)
    return self.get_feature_names_out()

get_feature_names_in()

Returns the names of the columns seen in fitting.

As in category_encoders, these are the DataFrame's column labels, or 0, 1, ... for an array.

Returns:

Type Description
ndarray

The input columns' labels.

Source code in src/logit_encode/utils.py
def get_feature_names_in(self) -> np.ndarray:
    """Returns the names of the columns seen in fitting.

    As in `category_encoders`, these are the DataFrame's column labels,
    or 0, 1, ... for an array.

    Returns:
        The input columns' labels.

    """
    check_is_fitted(self, 'cols_')
    return np.asarray(self._columns, dtype = object)

get_feature_names_out(input_features=None)

Returns the names of the transformed columns.

Parameters:

Name Type Description Default
input_features Any

names of the input columns, or None to use the output's column labels, as category_encoders does (the input's column names, or 0, 1, ... for an array).

None

Returns:

Type Description
ndarray

The output column names, without the columns dropped by

ndarray

drop_invariant.

Source code in src/logit_encode/utils.py
def get_feature_names_out(
    self,
    input_features: Any = None) -> np.ndarray:
    """Returns the names of the transformed columns.

    Args:
        input_features: names of the input columns, or None to use the
            output's column labels, as `category_encoders` does (the
            input's column names, or 0, 1, ... for an array).

    Returns:
        The output column names, without the columns dropped by
        `drop_invariant`.

    """
    check_is_fitted(self, 'cols_')
    dropped = set(self.invariant_cols_)
    if input_features is None:
        # As in `category_encoders`, the names are the output's column
        # labels (integers for an array's pass-through columns).
        return np.asarray(
            [column.label for column in self._output_spec
             if column.label not in dropped],
            dtype = object)
    names = dict(zip(
        self._columns,
        _check_feature_names_in(self, input_features),
        strict = True))
    return np.asarray(
        ['|'.join(str(names[source]) for source in column.sources)
         + column.suffix
         for column in self._output_spec if column.label not in dropped],
        dtype = object)

get_mapping(column=None)

Returns tables of each category's encoded values.

Each table is indexed by a column's categories as they appear in the data (a missing value seen in fitting is its own category, NaN, and categories lumped by min_group_size appear as their group). Its columns are the output columns that transform makes from that column, with the same names: one value column per modeled class and, if return_uncertainty is True, their standard errors and the category's number of training rows. Unless handle_unknown or handle_missing is 'error', a row labeled '' gives the encoding of a category not seen in fitting, and a row labeled '' the encoding of a missing value if none were seen in fitting.

Parameters:

Name Type Description Default
column Any

an encoded column (or the name of an interaction or composite column), or None for every one.

None

Raises:

Type Description
KeyError

if column is not an encoded column.

Returns:

Type Description
dict[Any, DataFrame] | DataFrame

The table for column, or a dict of every encoded column's

dict[Any, DataFrame] | DataFrame

table.

Source code in src/logit_encode/logit_encoder.py
def get_mapping(
    self,
    column: Any = None) -> dict[Any, pd.DataFrame] | pd.DataFrame:
    """Returns tables of each category's encoded values.

    Each table is indexed by a column's categories as they appear in the
    data (a missing value seen in fitting is its own category, NaN, and
    categories lumped by `min_group_size` appear as their group). Its
    columns are the output columns that `transform` makes from that
    column, with the same names: one value column per modeled class and,
    if `return_uncertainty` is True, their standard errors and the
    category's number of training rows. Unless `handle_unknown` or
    `handle_missing` is 'error', a row labeled '<unknown>' gives the
    encoding of a category not seen in fitting, and a row labeled
    '<missing>' the encoding of a missing value if none were seen in
    fitting.

    Args:
        column: an encoded column (or the name of an interaction or
            composite column), or None for every one.

    Raises:
        KeyError: if `column` is not an encoded column.

    Returns:
        The table for `column`, or a dict of every encoded column's
        table.

    """
    check_is_fitted(self, 'mapping_')
    if column is None:
        return {
            name: self._lookup_table(name)
            for name in self._encoded_columns}
    if column not in self._encoded_columns:
        raise KeyError(
            f'{column!r} is not an encoded column. The encoded columns '
            f'are {self._encoded_columns}.')
    return self._lookup_table(column)

inverse_transform(X)

Converts encoded data back to its categories.

Each row's encoded values for a column are matched to the category with the same values (see get_mapping). This works for the output of transform without y. It cannot recover training rows encoded by fit_transform (or transform with y), which are cross-fitted and so have values that no category has, nor categories that were unknown in fitting or lumped by min_group_size (which come back as their group). Values that match no category, or more than one, come back missing, with a warning. Columns that composite_cols dropped are recovered from their composite column.

Parameters:

Name Type Description Default
X Any

encoded data, with the columns that transform returns.

required

Raises:

Type Description
ValueError

if X does not have the columns that transform returns, or if drop_invariant dropped an encoded column's values.

Returns:

Type Description
DataFrame | ndarray

The data with its original columns: categories for the encoded

DataFrame | ndarray

columns, and the other columns unchanged.

Source code in src/logit_encode/logit_encoder.py
def inverse_transform(self, X: Any) -> pd.DataFrame | np.ndarray:
    """Converts encoded data back to its categories.

    Each row's encoded values for a column are matched to the category
    with the same values (see `get_mapping`). This works for the output
    of `transform` without `y`. It cannot recover training rows encoded
    by `fit_transform` (or `transform` with `y`), which are cross-fitted
    and so have values that no category has, nor categories that were
    unknown in fitting or lumped by `min_group_size` (which come back as
    their group). Values that match no category, or more than one, come
    back missing, with a warning. Columns that `composite_cols` dropped
    are recovered from their composite column.

    Args:
        X: encoded data, with the columns that `transform` returns.

    Raises:
        ValueError: if `X` does not have the columns that `transform`
            returns, or if `drop_invariant` dropped an encoded column's
            values.

    Returns:
        The data with its original columns: categories for the encoded
        columns, and the other columns unchanged.

    """
    check_is_fitted(self, 'mapping_')
    dropped = set(self.invariant_cols_)
    lost = [
        output.label for output in self._output_spec
        if output.label in dropped and output.role == 'value']
    if lost:
        raise ValueError(
            'inverse_transform cannot recover columns whose values '
            f'drop_invariant dropped: {lost}')
    labels = [
        output.label for output in self._output_spec
        if output.label not in dropped]
    frame = self._inverse_input(X, labels)
    decoded: dict[Any, pd.Series] = {}
    for group in self._groups:
        decoded[group.name] = self._decode(group.name, frame)
    result: dict[Hashable, Any] = {}
    for column in self._columns:
        if column in frame.columns and column not in self.cols_:
            values = frame[column]
        elif column in self.cols_:
            values = self._decode(column, frame)
        else:
            values = self._split_member(column, decoded)
        result[column] = self._restore_dtype(column, values)
    output = pd.DataFrame(result, index = frame.index)
    if self.return_df:
        return output
    return output.to_numpy()

transform(X, y=None, override_return_df=False)

Encodes data.

Parameters:

Name Type Description Default
X Any

data to encode.

required
y Any

outcome of X if X is the training data, or None for new data.

None
override_return_df bool

whether to return a DataFrame regardless of return_df.

False

Returns:

Type Description
DataFrame | ndarray

The encoded data.

Source code in src/logit_encode/utils.py
def transform(
    self,
    X: Any,
    y: Any = None,
    override_return_df: bool = False) -> pd.DataFrame | np.ndarray:
    """Encodes data.

    Args:
        X: data to encode.
        y: outcome of `X` if `X` is the training data, or None for new
            data.
        override_return_df: whether to return a DataFrame regardless of
            `return_df`.

    Returns:
        The encoded data.

    """
    # The mixin is only used with `BaseEncoder`, which has these methods.
    encoder = cast('BaseEncoder', self)
    check_is_fitted(encoder, 'cols_')
    X_frame = encoder._validate_input(X, reset = False)
    y_series = None
    if y is not None:
        y_series = encoder._align_target(
            encoder._validate_target(y),
            X_frame)
    encoder._check_missing(X_frame)
    if any(column.encoded for column in encoder._output_spec):
        extras = encoder._extra_columns(X_frame)
        encoded = encoder._encode(X_frame, y_series)
        if extras:
            encoded = encoder._place_extra_columns(
                encoded, X_frame, extras)
        X_frame = encoded
    return encoder._finish(
        X_frame,
        override_return_df = override_return_df)