class_docstr: Class for all standard transformation steps.
class_docstr_tok: ["Class","for","all","standard","transformation","steps","."]
docstr: Encode categorical columns.
docstr_tok: ["Encode","categorical","columns","."]
code: def _encoding(
      self, max_encoding_ohe, encoding_method, rare_to_value, rare_value
  ):
      """Encode categorical columns."""
      if rare_to_value:
          self.logger.info("Set up grouping of rare categories.")
  
          if rare_to_value < 0 or rare_to_value >= 1:
              raise ValueError(
                  "Invalid value for the rare_to_value parameter. "
                  f"The value must lie between 0 and 1, got {rare_to_value}."
              )
  
          rare_estimator = TransformerWrapper(
              transformer=RareCategoryGrouping(
                  rare_to_value, rare_value
              ),
              include=self._fxs["Categorical"],
          )
  
          self.pipeline.steps.append(
              ("rare_category_grouping", rare_estimator)
          )
  
          # To select the encoding type for every column,
          # we first need to run the grouping
          X_transformed = rare_estimator.fit_transform(self.X_train)
      else:
          X_transformed = self.X_train
  
      # Select columns for different encoding types
      ord_cols, one_hot_cols, rest_cols = {}, [], []
      for name, column in X_transformed[
          self._fxs["Categorical"]
      ].items():
          n_unique = column.nunique()
          if n_unique == 2:
              ord_cols[name] = list(sorted(column.dropna().unique()))
          elif max_encoding_ohe < 0 or n_unique <= max_encoding_ohe:
              one_hot_cols.append(name)
          else:
              rest_cols.append(name)
  
      if self._fxs["Ordinal"] or ord_cols:
          self.logger.info("Set up encoding of ordinal features.")
  
          ord_cols = {**ord_cols, **self._fxs["Ordinal"]}
  
          # Check provided features and levels are correct
          mapping = {}
          for key, value in ord_cols.items():
              if self.X[key].nunique() != len(value):
                  self.logger.warning(
                      f"The number of classes passed to feature {key} in the "
                      f"ordinal_features parameter ({len(value)}) don't match "
                      f"with the number of classes in the data ({self.X[key].nunique()})."
                  )
  
              # Encoder always needs mapping of NaN value
              mapping[key] = {v: i for i, v in enumerate(value)}
              mapping[key].setdefault(np.NaN, -1)
  
          ord_estimator = TransformerWrapper(
              transformer=OrdinalEncoder(
                  mapping=[
                      {"col": k, "mapping": val}
                      for k, val in mapping.items()
                  ],
                  cols=list(
                      ord_cols
                  ),  # Specify to not skip bool columns
                  handle_missing="return_nan",
                  handle_unknown="value",
              ),
              include=list(ord_cols),
          )
  
          self.pipeline.steps.append(
              ("ordinal_encoding", ord_estimator)
          )
  
      if self._fxs["Categorical"]:
          self.logger.info("Set up encoding of categorical features.")
  
          if len(one_hot_cols) > 0:
              onehot_estimator = TransformerWrapper(
                  transformer=OneHotEncoder(
                      cols=one_hot_cols,
                      use_cat_names=True,
                      handle_missing="return_nan",
                      handle_unknown="value",
                  ),
                  include=one_hot_cols,
              )
  
              self.pipeline.steps.append(
                  ("onehot_encoding", onehot_estimator)
              )
  
          # Encode the rest of the categorical columns
          if len(rest_cols) > 0:
              if not encoding_method:
                  if self._ml_usecase in (
                      MLUsecase.ANOMALY,
                      MLUsecase.CLUSTERING,
                  ):
                      encoding_method = BaseNEncoder(
                          base=5,
                          handle_missing="return_nan",
                          handle_unknown="value",
                      )
                  else:
                      encoding_method = TargetEncoder(
                          handle_missing="return_nan",
                          handle_unknown="value",
                      )
  
              rest_estimator = TransformerWrapper(
                  transformer=encoding_method,
                  include=rest_cols,
              )
  
              self.pipeline.steps.append(
                  ("rest_encoding", rest_estimator)
              )
  
imports: from copy import deepcopy
  import numpy
  import pandas
  from category_encoders.basen import BaseNEncoder
  from category_encoders.one_hot import OneHotEncoder
  from category_encoders.ordinal import OrdinalEncoder
  from category_encoders.target_encoder import TargetEncoder
  from imblearn.combine import SMOTEENN, SMOTETomek
  from imblearn.over_sampling import ADASYN, SMOTE, SMOTEN, SMOTENC, SVMSMOTE, BorderlineSMOTE, KMeansSMOTE, RandomOverSampler
  from imblearn.under_sampling import AllKNN, CondensedNearestNeighbour, EditedNearestNeighbours, InstanceHardnessThreshold, NearMiss, NeighbourhoodCleaningRule, OneSidedSelection, RandomUnderSampler, RepeatedEditedNearestNeighbours, TomekLinks
  from sklearn.decomposition import PCA, IncrementalPCA, KernelPCA
  from sklearn.feature_selection import SelectFromModel, SelectKBest, SequentialFeatureSelector, VarianceThreshold, f_classif, f_regression
  from sklearn.impute import KNNImputer, SimpleImputer
  from sklearn.model_selection import GroupKFold, KFold, StratifiedKFold, TimeSeriesSplit, train_test_split
  from sklearn.preprocessing import KBinsDiscretizer, LabelEncoder, MaxAbsScaler, MinMaxScaler, PolynomialFeatures, PowerTransformer, QuantileTransformer, RobustScaler, StandardScaler
  from pycaret.containers.models.classification import get_all_model_containers
  from pycaret.containers.models.regression import get_all_model_containers
  from pycaret.internal.preprocess.iterative_imputer import IterativeImputer
  from pycaret.internal.preprocess.transformers import CleanColumnNames, DropImputer, EmbedTextFeatures, ExtractDateTimeFeatures, FixImbalancer, GroupFeatures, RareCategoryGrouping, RemoveMulticollinearity, RemoveOutliers, TargetTransformer, TransformerWrapper, TransformerWrapperWithInverse
  from pycaret.utils.constants import SEQUENCE
  from pycaret.utils.generic import MLUsecase, check_features_exist, df_shrink_dtypes, get_columns_to_stratify_by, normalize_custom_transformers, to_df, to_series
label_desc: Use image node_id 13 for calling the Preprocessor obj's underlying member method code with example usage: obj._encoding(max_encoding_ohe, encoding_method, rare_to_value, rare_value) without return types