
    0Ph4                    &   d dl Z d dlZd dl mZ d dlZd dlmZ ddlmZm	Z	m
Z
mZ ddlmZmZ ddlmZmZmZmZ ddlmZ dd	lmZ dd
lmZmZmZ ddlmZ ddlmZm Z m!Z!m"Z" ddgZ# G d de
e          Z$ G d de$          Z% G d de	e$          Z&dS )    N)Integral)sparse   )BaseEstimatorOneToOneFeatureMixinTransformerMixin_fit_context)_safe_indexingcheck_array)_check_unknown_encode_get_counts_unique)	_get_mask)is_scalar_nan)Interval
RealNotInt
StrOptions)_get_output_config)_check_feature_names_check_feature_names_in_check_n_featurescheck_is_fittedOneHotEncoderOrdinalEncoderc                   x     e Zd ZdZddZ	 	 	 	 ddZ	 	 	 	 ddZed	             Zd
 Z	d Z
d Zd Z fdZ xZS )_BaseEncoderzm
    Base class for encoders that includes the code to categorize and
    transform the input features.

    Tc                    t          |d          rt          |dd          dk    sct          |d|          }t          |d          s<t          j        |j        t          j                  rt          |t          |          }n|}d}n|}|j        \  }}g }t          |          D ]<}t          ||d	
          }	t          |	dd|          }	|                    |	           =|||fS )a  
        Perform custom check_array:
        - convert list of strings to object dtype
        - check for missing values for object dtype data (check_array does
          not do that)
        - return list of features (arrays): this list of features is
          constructed feature by feature to preserve the data types
          of pandas DataFrame columns, as otherwise information is lost
          and cannot be used, e.g. for the `categories_` attribute.

        ilocndimr   r   N)dtypeensure_all_finiter!   F   )indicesaxis)	ensure_2dr!   r"   )hasattrgetattrr   np
issubdtyper!   str_objectshaperanger
   append)
selfXr"   X_tempneeds_validation	n_samples
n_features	X_columnsiXis
             _/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/preprocessing/_encoders.py_check_Xz_BaseEncoder._check_X#   s    6"" 	1wq&!'<'<'A'A $BSTTTF1g&& 2=rw+O+O CTUUU$  1 !	:	z"" 	! 	!A11555Be4CS  B R    )Z//    errorFc                    |                                   t          | |d           t          | |d           |                     ||          \  }}}|| _        | j        dk    r't          | j                  |k    rt          d          g | _        g }	|p| j	        }
t          |          D ]h}||         }| j        dk    r3t          ||
          }|
r|\  }}|	                    |           n	|}nt          j        |j        t          j                  rt"          }n|j        }t          j        | j        |         |          }|j        t"          k    r[t'          |d         t(                    r@|j        j        d	k    r0d
| dt-          |d                   j         d}t          |          |d d         D ]&}t1          |          rt          d| d|           '|j        t          t          |                    k    rd
| d}t          |          |j        j        dvrkt          j        |          }d}t          j        |d                   rdnd }t          j        |d |         |d |         k              rt          |          |dk    r7t;          ||          }|r%d                    ||          }t          |          |
r#|	                    t?          ||                     | j                            |           jd|i}|r|	|d<   i }|rAtA          | j                  D ]'\  }}t1          |d                   r|j        dz
  ||<   (||d<   | j	        r| !                    ||	|           |S )NTresetr"   autozOShape mismatch: if categories is an array, it has to be of shape (n_features,).)return_countsr!   r   Sz
In column zY, the predefined categories have type 'bytes' which is incompatible with values of type 'z'.zKNan should be the last element in user provided categories, see categories z in column #z7, the predefined categories contain duplicate elements.OUSz>Unsorted categories are not supported for numerical categoriesr<   z5Found unknown categories {0} in column {1} during fitr4   category_countsr#   missing_indices)"_check_infrequent_enabledr   r   r:   n_features_in_
categorieslen
ValueErrorcategories__infrequent_enabledr.   r   r/   r)   r*   r!   r+   r,   array
isinstancebyteskindtype__name__r   sizesortisnananyr   formatr   	enumerate _fit_infrequent_category_mapping)r0   r1   handle_unknownr"   rB   (return_and_ignore_missing_for_infrequentX_listr4   r5   rG   compute_countsr7   r8   resultcatscountsXi_dtypemsgcategorysorted_cats	error_msgstop_idxdiffoutputrH   feature_idxcategories_for_idxs                              r9   _fitz_BaseEncoder._fitH   sE    	&&((($....T1D1111(,!2 )6 )
 )
%	: )?f$$4?##z11 <  
 &B$*Bz"" E	* E	*AB&(( >BBB! "#)LD&#**62222!DD=2733 (  &HH!xHx 2(CCCJ&(("47E22 ),,6Q 6 6!"Q%[[16 6 6 
 %S//) !%SbS	  H$X.. (/DH/ /+,/ /   9GDMM 2 2227Q 7 7 7  %S//)8=--"$'$--KX  &(Xk"o%>%>HrrDHvk)8)4YhYGHH 4(333!W,,)"d33D .**0&q//  )oo-! B#**;r4+@+@AAA##D))))y) 	8(7F$%3 	83<T=M3N3N O O// !3B!788 O3E3JQ3NOK0(7F$%# 	11  
 r;   Nc                 z   |                      ||          \  }}}t          | |d           t          | |d           t          j        ||ft
                    }	t          j        ||ft                    }
g }t          |          D ]u}||         }t          || j
        |         d          \  }}t          j        |          s|dk    r%d                    ||          }t          |          |r|                    |           ||
d d |f<   | j
        |         j        j        d	v rA| j
        |         j        |j        k    r&|                    | j
        |         j                  }nU| j
        |         j        j        d
k    r&|j        j        dk    r|                    d
          }n|                                }| j
        |         d         || <   t)          || j
        |         d          |	d d |f<   w|rt+          j        d| dt.                     |                     |	|
|           |	|
fS )Nr@   Fr>   rC   T)return_maskr<   z;Found unknown categories {0} in column {1} during transform)UrD   Orq   r   )uniquescheck_unknownz$Found unknown categories in columns zH during transform. These unknown categories will be encoded as all zeros)r:   r   r   r)   zerosintonesboolr.   r   rN   allrZ   rM   r/   r!   rS   itemsizeastypecopyr   warningswarnUserWarning_map_infrequent_categories)r0   r1   r]   r"   warn_on_unknownignore_category_indicesr_   r4   r5   X_intX_maskcolumns_with_unknownr7   r8   rj   
valid_maskre   s                    r9   
_transformz_BaseEncoder._transform   s    )-!2 )6 )
 )
%	: 	T1E2222$////)Z0<<<)Z0===!z"" $	X $	XAB-b$2B12ESWXXXD*6*%% =!W,,,,2F4OO  %S//)& 7,33A666 $.F111a4L (+16*DD ,Q/82;FFYYt'7':'@AA)!,273>>28=TWCWCW  YYs^^WWYY&*&6q&9!&<B
{O ""d.>q.AQVWWWE!!!Q$KK 	MF+F F F    	''v7NOOOf}r;   c                 N    | j         }d t          | j        |          D             S )z'Infrequent categories for each feature.c                 ,    g | ]\  }}|d n||         S N ).0rf   r$   s      r9   
<listcomp>z7_BaseEncoder.infrequent_categories_.<locals>.<listcomp>  s9     
 
 
!' ODD'):
 
 
r;   )_infrequent_indicesziprN   )r0   infrequent_indicess     r9   infrequent_categories_z#_BaseEncoder.infrequent_categories_  s<     "5
 
%()9;M%N%N
 
 
 	
r;   c                 p    t          | dd          }t          | dd          }|duo|dk    p|du| _        dS )z
        This functions checks whether _infrequent_enabled is True or False.
        This has to be called after parameter validation in the fit function.
        max_categoriesNmin_frequencyr#   )r(   rO   )r0   r   r   s      r9   rI   z&_BaseEncoder._check_infrequent_enabled  sT    
 !'7>>ot<<$&>>Q+>$'$& 	   r;   c                 $   t          | j        t          j                  r|| j        k     }nVt          | j        t          j                  r|| j        z  }||k     }n&t          j        |j        d         t                    }|j	        |
                                z
  dz   }| j        G| j        |k     r<| j        dz
  }|dk    rd|dd<   n$t          j        |d          d|          }d||<   t          j        |          }	|	j	        dk    r|	ndS )a  Compute the infrequent indices.

        Parameters
        ----------
        category_count : ndarray of shape (n_cardinality,)
            Category counts.

        n_samples : int
            Number of samples.

        col_idx : int
            Index of the current category. Only used for the error message.

        Returns
        -------
        output : ndarray of shape (n_infrequent_categories,) or None
            If there are infrequent categories, indices of infrequent
            categories. Otherwise None.
        r   rC   r#   NT	mergesort)rS   )rQ   r   numbersr   Realr)   ru   r-   rx   rV   sumr   argsortflatnonzero)
r0   category_countr4   col_idxinfrequent_maskmin_frequency_absn_current_featuresfrequent_category_countsmallest_levelsrk   s
             r9   _identify_infrequentz!_BaseEncoder._identify_infrequent  s1   ( d('*:;; 	L,t/AAOO*GL99 	L )D,> >,/@@OO h~';A'>dKKKO+0?3F3F3H3HH1L*t/BEW/W/W&*&9A&=#&!++%)"" #%*^+"N"N"N----# 48000qvvd2r;   c                     |r`g }t          |          D ]M\  }}||v r/|                    t          j        |||                              8|                    |           Nn|} fdt          |          D              _        g  _        t           j                  D ]\  }} j        |         }| j                            d           /t          |          }	||v r|	dz  }	t          j        |	t          j	                  }
|j
        }|	|z
  }||
|<   t          j        t          j        |	          |          }t          j        |          |
|<    j                            |
           dS )ah  Fit infrequent categories.

        Defines the private attribute: `_default_to_infrequent_mappings`. For
        feature `i`, `_default_to_infrequent_mappings[i]` defines the mapping
        from the integer encoding returned by `super().transform()` into
        infrequent categories. If `_default_to_infrequent_mappings[i]` is None,
        there were no infrequent categories in the training set.

        For example if categories 0, 2 and 4 were frequent, while categories
        1, 3, 5 were infrequent for feature 7, then these categories are mapped
        to a single output:
        `_default_to_infrequent_mappings[7] = array([0, 3, 1, 3, 2, 3])`

        Defines private attribute: `_infrequent_indices`. `_infrequent_indices[i]`
        is an array of indices such that
        `categories_[i][_infrequent_indices[i]]` are all the infrequent category
        labels. If the feature `i` has no infrequent categories
        `_infrequent_indices[i]` is None.

        .. versionadded:: 1.1

        Parameters
        ----------
        n_samples : int
            Number of samples in training set.
        category_counts: list of ndarray
            `category_counts[i]` is the category counts corresponding to
            `self.categories_[i]`.
        missing_indices : dict
            Dict mapping from feature_idx to category index with a missing value.
        c                 D    g | ]\  }}                     ||          S r   )r   )r   r   r   r4   r0   s      r9   r   zA_BaseEncoder._fit_infrequent_category_mapping.<locals>.<listcomp>s  s?     $
 $
 $
' %%niII$
 $
 $
r;   Nr#   rC   )r[   r/   r)   deleter   _default_to_infrequent_mappingsrN   rL   emptyint64rV   	setdiff1darange)r0   r4   rG   rH   category_counts_rl   count
infreq_idxrb   n_catsmappingn_infrequent_catsn_frequent_catsfrequent_indicess   ``            r9   r\   z-_BaseEncoder._fit_infrequent_category_mappingD  s   F  
	/!&/&@&@ 3 3"U/11$++	%)EFF    %++E22223  /$
 $
 $
 $
 $
+45E+F+F$
 $
 $
  02,'01I'J'J 	A 	A#K#K0D!4;;DAAAYYFo-- ! hvRX666G * %'88O"1GJ!|BIf,=,=zJJ(*	/(B(BG$%077@@@@3	A 	Ar;   c                    | j         sdS |pi }t          |j        d                   D ]>}| j        |         }||d         ||dd|f          |f<   | j        dk    r	d|dd|f<   ?t          | j                  D ]T\  }}|||v r|dd|f         ||         k    }nt          d          }t          j	        ||||f                   |||f<   UdS )a  Map infrequent categories to integer representing the infrequent category.

        This modifies X_int in-place. Values that were invalid based on `X_mask`
        are mapped to the infrequent category if there was an infrequent
        category for that feature.

        Parameters
        ----------
        X_int: ndarray of shape (n_samples, n_features)
            Integer encoded categories.

        X_mask: ndarray of shape (n_samples, n_features)
            Bool mask for valid values in `X_int`.

        ignore_category_indices : dict
            Dictionary mapping from feature_idx to category index to ignore.
            Ignored indexes will not be grouped and the original ordinal encoding
            will remain.
        Nr#   r   infrequent_if_existT)
rO   r.   r-   r   r]   r[   r   slicer)   take)	r0   r   r   r   r   infrequent_idxr7   r   rows_to_updates	            r9   r   z'_BaseEncoder._map_infrequent_categories  s-   ( ' 	F"9"?RU[^,, 	* 	*G!5g>N%2@2CE6!!!W*%%w./"&;;;
 &*qqq'z" $D$HII 
	R 
	RJAw+++!&qqq!t0G0J!J!&t')wwna>O8P'Q'QE.!#$$
	R 
	Rr;   c                 x    t                                                      }d|j        _        d|j        _        |S )NT)super__sklearn_tags__
input_tagscategorical	allow_nan)r0   tags	__class__s     r9   r   z_BaseEncoder.__sklearn_tags__  s1    ww''))&*#$(!r;   T)r<   TFF)r<   TFN)rU   
__module____qualname____doc__r:   rn   r   propertyr   rI   r   r\   r   r   __classcell__)r   s   @r9   r   r      s        #0 #0 #0 #0P 16t t t tr  $B B B BH 
 
 X
	' 	' 	'+3 +3 +3ZPA PA PAd2R 2R 2Rh        r;   r   c                   |   e Zd ZU dZ edh          eg eddh          ddgd eh d          g eed	dd
          dg eed	dd
           eedd	d          dgdg edh          e	gdZ
eed<   dddej        ddddddZd Zd Zd!dZd Zd Z ed          d"d            Zd Zd Zd"dZd  ZdS )#r   a.  
    Encode categorical features as a one-hot numeric array.

    The input to this transformer should be an array-like of integers or
    strings, denoting the values taken on by categorical (discrete) features.
    The features are encoded using a one-hot (aka 'one-of-K' or 'dummy')
    encoding scheme. This creates a binary column for each category and
    returns a sparse matrix or dense array (depending on the ``sparse_output``
    parameter).

    By default, the encoder derives the categories based on the unique values
    in each feature. Alternatively, you can also specify the `categories`
    manually.

    This encoding is needed for feeding categorical data to many scikit-learn
    estimators, notably linear models and SVMs with the standard kernels.

    Note: a one-hot encoding of y labels should use a LabelBinarizer
    instead.

    Read more in the :ref:`User Guide <preprocessing_categorical_features>`.
    For a comparison of different encoders, refer to:
    :ref:`sphx_glr_auto_examples_preprocessing_plot_target_encoder.py`.

    Parameters
    ----------
    categories : 'auto' or a list of array-like, default='auto'
        Categories (unique values) per feature:

        - 'auto' : Determine categories automatically from the training data.
        - list : ``categories[i]`` holds the categories expected in the ith
          column. The passed categories should not mix strings and numeric
          values within a single feature, and should be sorted in case of
          numeric values.

        The used categories can be found in the ``categories_`` attribute.

        .. versionadded:: 0.20

    drop : {'first', 'if_binary'} or an array-like of shape (n_features,),             default=None
        Specifies a methodology to use to drop one of the categories per
        feature. This is useful in situations where perfectly collinear
        features cause problems, such as when feeding the resulting data
        into an unregularized linear regression model.

        However, dropping one category breaks the symmetry of the original
        representation and can therefore induce a bias in downstream models,
        for instance for penalized linear classification or regression models.

        - None : retain all features (the default).
        - 'first' : drop the first category in each feature. If only one
          category is present, the feature will be dropped entirely.
        - 'if_binary' : drop the first category in each feature with two
          categories. Features with 1 or more than 2 categories are
          left intact.
        - array : ``drop[i]`` is the category in feature ``X[:, i]`` that
          should be dropped.

        When `max_categories` or `min_frequency` is configured to group
        infrequent categories, the dropping behavior is handled after the
        grouping.

        .. versionadded:: 0.21
           The parameter `drop` was added in 0.21.

        .. versionchanged:: 0.23
           The option `drop='if_binary'` was added in 0.23.

        .. versionchanged:: 1.1
            Support for dropping infrequent categories.

    sparse_output : bool, default=True
        When ``True``, it returns a :class:`scipy.sparse.csr_matrix`,
        i.e. a sparse matrix in "Compressed Sparse Row" (CSR) format.

        .. versionadded:: 1.2
           `sparse` was renamed to `sparse_output`

    dtype : number type, default=np.float64
        Desired dtype of output.

    handle_unknown : {'error', 'ignore', 'infrequent_if_exist', 'warn'},                      default='error'
        Specifies the way unknown categories are handled during :meth:`transform`.

        - 'error' : Raise an error if an unknown category is present during transform.
        - 'ignore' : When an unknown category is encountered during
          transform, the resulting one-hot encoded columns for this feature
          will be all zeros. In the inverse transform, an unknown category
          will be denoted as None.
        - 'infrequent_if_exist' : When an unknown category is encountered
          during transform, the resulting one-hot encoded columns for this
          feature will map to the infrequent category if it exists. The
          infrequent category will be mapped to the last position in the
          encoding. During inverse transform, an unknown category will be
          mapped to the category denoted `'infrequent'` if it exists. If the
          `'infrequent'` category does not exist, then :meth:`transform` and
          :meth:`inverse_transform` will handle an unknown category as with
          `handle_unknown='ignore'`. Infrequent categories exist based on
          `min_frequency` and `max_categories`. Read more in the
          :ref:`User Guide <encoder_infrequent_categories>`.
        - 'warn' : When an unknown category is encountered during transform
          a warning is issued, and the encoding then proceeds as described for
          `handle_unknown="infrequent_if_exist"`.

        .. versionchanged:: 1.1
            `'infrequent_if_exist'` was added to automatically handle unknown
            categories and infrequent categories.

        .. versionadded:: 1.6
           The option `"warn"` was added in 1.6.

    min_frequency : int or float, default=None
        Specifies the minimum frequency below which a category will be
        considered infrequent.

        - If `int`, categories with a smaller cardinality will be considered
          infrequent.

        - If `float`, categories with a smaller cardinality than
          `min_frequency * n_samples`  will be considered infrequent.

        .. versionadded:: 1.1
            Read more in the :ref:`User Guide <encoder_infrequent_categories>`.

    max_categories : int, default=None
        Specifies an upper limit to the number of output features for each input
        feature when considering infrequent categories. If there are infrequent
        categories, `max_categories` includes the category representing the
        infrequent categories along with the frequent categories. If `None`,
        there is no limit to the number of output features.

        .. versionadded:: 1.1
            Read more in the :ref:`User Guide <encoder_infrequent_categories>`.

    feature_name_combiner : "concat" or callable, default="concat"
        Callable with signature `def callable(input_feature, category)` that returns a
        string. This is used to create feature names to be returned by
        :meth:`get_feature_names_out`.

        `"concat"` concatenates encoded feature name and category with
        `feature + "_" + str(category)`.E.g. feature X with values 1, 6, 7 create
        feature names `X_1, X_6, X_7`.

        .. versionadded:: 1.3

    Attributes
    ----------
    categories_ : list of arrays
        The categories of each feature determined during fitting
        (in order of the features in X and corresponding with the output
        of ``transform``). This includes the category specified in ``drop``
        (if any).

    drop_idx_ : array of shape (n_features,)
        - ``drop_idx_[i]`` is the index in ``categories_[i]`` of the category
          to be dropped for each feature.
        - ``drop_idx_[i] = None`` if no category is to be dropped from the
          feature with index ``i``, e.g. when `drop='if_binary'` and the
          feature isn't binary.
        - ``drop_idx_ = None`` if all the transformed features will be
          retained.

        If infrequent categories are enabled by setting `min_frequency` or
        `max_categories` to a non-default value and `drop_idx[i]` corresponds
        to a infrequent category, then the entire infrequent category is
        dropped.

        .. versionchanged:: 0.23
           Added the possibility to contain `None` values.

    infrequent_categories_ : list of ndarray
        Defined only if infrequent categories are enabled by setting
        `min_frequency` or `max_categories` to a non-default value.
        `infrequent_categories_[i]` are the infrequent categories for feature
        `i`. If the feature `i` has no infrequent categories
        `infrequent_categories_[i]` is None.

        .. versionadded:: 1.1

    n_features_in_ : int
        Number of features seen during :term:`fit`.

        .. versionadded:: 1.0

    feature_names_in_ : ndarray of shape (`n_features_in_`,)
        Names of features seen during :term:`fit`. Defined only when `X`
        has feature names that are all strings.

        .. versionadded:: 1.0

    feature_name_combiner : callable or None
        Callable with signature `def callable(input_feature, category)` that returns a
        string. This is used to create feature names to be returned by
        :meth:`get_feature_names_out`.

        .. versionadded:: 1.3

    See Also
    --------
    OrdinalEncoder : Performs an ordinal (integer)
      encoding of the categorical features.
    TargetEncoder : Encodes categorical features using the target.
    sklearn.feature_extraction.DictVectorizer : Performs a one-hot encoding of
      dictionary items (also handles string-valued features).
    sklearn.feature_extraction.FeatureHasher : Performs an approximate one-hot
      encoding of dictionary items or strings.
    LabelBinarizer : Binarizes labels in a one-vs-all
      fashion.
    MultiLabelBinarizer : Transforms between iterable of
      iterables and a multilabel format, e.g. a (samples x classes) binary
      matrix indicating the presence of a class label.

    Examples
    --------
    Given a dataset with two features, we let the encoder find the unique
    values per feature and transform the data to a binary one-hot encoding.

    >>> from sklearn.preprocessing import OneHotEncoder

    One can discard categories not seen during `fit`:

    >>> enc = OneHotEncoder(handle_unknown='ignore')
    >>> X = [['Male', 1], ['Female', 3], ['Female', 2]]
    >>> enc.fit(X)
    OneHotEncoder(handle_unknown='ignore')
    >>> enc.categories_
    [array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)]
    >>> enc.transform([['Female', 1], ['Male', 4]]).toarray()
    array([[1., 0., 1., 0., 0.],
           [0., 1., 0., 0., 0.]])
    >>> enc.inverse_transform([[0, 1, 1, 0, 0], [0, 0, 0, 1, 0]])
    array([['Male', 1],
           [None, 2]], dtype=object)
    >>> enc.get_feature_names_out(['gender', 'group'])
    array(['gender_Female', 'gender_Male', 'group_1', 'group_2', 'group_3'], ...)

    One can always drop the first column for each feature:

    >>> drop_enc = OneHotEncoder(drop='first').fit(X)
    >>> drop_enc.categories_
    [array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)]
    >>> drop_enc.transform([['Female', 1], ['Male', 2]]).toarray()
    array([[0., 0., 0.],
           [1., 1., 0.]])

    Or drop a column for feature only having 2 categories:

    >>> drop_binary_enc = OneHotEncoder(drop='if_binary').fit(X)
    >>> drop_binary_enc.transform([['Female', 1], ['Male', 2]]).toarray()
    array([[0., 1., 0., 0.],
           [1., 0., 1., 0.]])

    One can change the way feature names are created.

    >>> def custom_combiner(feature, category):
    ...     return str(feature) + "_" + type(category).__name__ + "_" + str(category)
    >>> custom_fnames_enc = OneHotEncoder(feature_name_combiner=custom_combiner).fit(X)
    >>> custom_fnames_enc.get_feature_names_out()
    array(['x0_str_Female', 'x0_str_Male', 'x1_int_1', 'x1_int_2', 'x1_int_3'],
          dtype=object)

    Infrequent categories are enabled by setting `max_categories` or `min_frequency`.

    >>> import numpy as np
    >>> X = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3], dtype=object).T
    >>> ohe = OneHotEncoder(max_categories=3, sparse_output=False).fit(X)
    >>> ohe.infrequent_categories_
    [array(['a', 'd'], dtype=object)]
    >>> ohe.transform([["a"], ["b"]])
    array([[0., 0., 1.],
           [1., 0., 0.]])
    rA   first	if_binaryz
array-likeNno_validation>   r~   r<   ignorer   r#   leftclosedr   neitherbooleanconcat)rK   dropr!   r]   r   r   sparse_outputfeature_name_combiner_parameter_constraintsTr<   )rK   r   r   r!   r]   r   r   r   c                v    || _         || _        || _        || _        || _        || _        || _        || _        d S r   )rK   r   r!   r]   r   r   r   r   )	r0   rK   r   r   r!   r]   r   r   r   s	            r9   __init__zOneHotEncoder.__init__  sG     %*
,	*,%:"""r;   c                     | j         s|S | j        |         }||S | j        |         }|?||v r;| j        |         }t	          d||                                         d| d          ||         S )zConvert `drop_idx` into the index for infrequent categories.

        If there are no infrequent categories, then `drop_idx` is
        returned. This method is called in `_set_drop_idx` when the `drop`
        parameter is an array-like.
        NzUnable to drop category z from feature z because it is infrequent)rO   r   r   rN   rM   item)r0   rl   drop_idxdefault_to_infrequentr   rK   s         r9   _map_drop_idx_to_infrequentz)OneHotEncoder._map_drop_idx_to_infrequent  s     ' 	O $ D[ Q (O "5kB)h:L.L.L)+6JC:h+?+D+D+F+F C C'C C C   %X..r;   c                    | j         d}nt          | j         t                    r| j         dk    r/t          j        t          | j                  t                    }nq| j         dk    rrd | j        D             }| j        r5t          | j
                  D ] \  }}|||xx         |j        dz
  z  cc<   !t          j        d |D             t                    }nt          j        | j         t                    }t          |          }|t          | j                  k    r7d}t          |                    t          | j                  |                    g }g }	t          t!          || j                            D ]\  }
\  }}t#          |          smt          j        ||k              d	         }|j        r0|	                    |                     |
|d	                              n|                    |
|f           t#          |d
                   r2|	                    |                     |
|j        dz
                       |                    |
|f           t+          |          rAd                    d                    d |D                                 }t          |          t          j        |	t                    }|| _        | j        r|| j        | _        dS g }t          |          D ]L\  }
}| j        |
         }|||}nt          j        ||k              d	         }|                    |           Mt          j        |t                    | _        dS )a  Compute the drop indices associated with `self.categories_`.

        If `self.drop` is:
        - `None`, No categories have been dropped.
        - `'first'`, All zeros to drop the first category.
        - `'if_binary'`, All zeros if the category is binary and `None`
          otherwise.
        - array-like, The indices of the categories that match the
          categories in `self.drop`. If the dropped category is an infrequent
          category, then the index for the infrequent category is used. This
          means that the entire infrequent category is dropped.

        This methods defines a public `drop_idx_` and a private
        `_drop_idx_after_grouping`.

        - `drop_idx_`: Public facing API that references the drop category in
          `self.categories_`.
        - `_drop_idx_after_grouping`: Used internally to drop categories *after* the
          infrequent categories are grouped together.

        If there are no infrequent categories or drop is `None`, then
        `drop_idx_=_drop_idx_after_grouping`.
        Nr   rC   r   c                 ,    g | ]}t          |          S r   rL   r   cats     r9   r   z/OneHotEncoder._set_drop_idx.<locals>.<listcomp>A  s    )O)O)Os#c(()O)O)Or;   r#   c                 "    g | ]}|d k    rdndS )r   r   Nr   )r   n_features_outs     r9   r   z/OneHotEncoder._set_drop_idx.<locals>.<listcomp>I  s6       * ,q00d  r;   zF`drop` should have length equal to the number of features ({}), got {}r   rE   zaThe following categories were supposed to be dropped, but were not found in the training data.
{}
c                 @    g | ]\  }}d                      ||          S )zCategory: {}, Feature: {})rZ   )r   cvs      r9   r   z/OneHotEncoder._set_drop_idx.<locals>.<listcomp>w  s<       $(Aq !< B B1a H H  r;   )r   rQ   strr)   ru   rL   rN   r,   rO   r[   r   rV   rP   asarrayrM   rZ   r   r   wherer/   r   rY   join_drop_idx_after_grouping	drop_idx_r   r   )r0   drop_idx_after_groupingn_features_out_no_dropr7   r   
drop_arraydroplenre   missing_dropsdrop_indicesrl   drop_valcat_listr   r   r   orig_drop_idxs                    r9   _set_drop_idxzOneHotEncoder._set_drop_idx#  s   0 9&*##	3'' B	KyG##*,(3t7G3H3HPV*W*W*W''k)))O)Od>N)O)O)O&+ I)243K)L)L I I:%-$.q111Z_q5HH1111*,( .D   !+ + +' DIV<<<J*ooG#d./////  !C0@,A,A7!K!KLLLML5>J 0116 6 B B11h %X.. !xH(<==a@H} F$++ <<[(ST+VV    &,,k8-DEEE !".. B ''88hmVWFWXX    "((+x)@AAAA=!! &  &		 ,9   ! !  !oo%&(h|6&J&J&J#
 )@%' 	A+B+J!:DNNNI)23J)K)K 	0 	0%X(,(L)% #'<'D$,MM$&N3HH3T$U$UVW$XM  ////Z	@@@DNNNr;   c                    | j         |         }| j        r_| j        |         }|P||                                k     }d}t	          j        ||         t	          j        |gt                    f          }|r|                     ||          }|S )zCompute the transformed categories used for column `i`.

        1. If there are infrequent categories, the category is named
        'infrequent_sklearn'.
        2. Dropped columns are removed when remove_dropped=True.
        Ninfrequent_sklearnrC   )	rN   rO   r   maxr)   concatenaterP   r,   _remove_dropped_categories)r0   r7   remove_droppedrb   
infreq_mapfrequent_maskinfrequent_cats          r9   _compute_transformed_categoriesz-OneHotEncoder._compute_transformed_categories  s     "# 	=a@J% *Z^^-=-= =!5~-("(N3C6*R*R*RS   	<224;;Dr;   c                 n    | j         -| j         |          t          j        || j         |                   S |S )zRemove dropped categories.)r   r)   r   )r0   rK   r7   s      r9   r   z(OneHotEncoder._remove_dropped_categories  s;     )5-a0<9Z)Fq)IJJJr;   c                 
   d | j         D             }| j        ,t          | j                  D ]\  }}|||xx         dz  cc<   | j        s|S t          | j                  D ] \  }}|||xx         |j        dz
  z  cc<   !|S )z2Compute the n_features_out for each input feature.c                 ,    g | ]}t          |          S r   r   )r   rb   s     r9   r   z:OneHotEncoder._compute_n_features_outs.<locals>.<listcomp>  s    999#d))999r;   Nr#   )rN   r   r[   rO   r   rV   )r0   rk   r7   r   r   s        r9   _compute_n_features_outsz&OneHotEncoder._compute_n_features_outs  s    99(8999(4()FGG # #8'1IIINIII' 	M 't'?@@ 	- 	-MAz!1III1,,IIIIr;   prefer_skip_nested_validationc                     |                      || j        d           |                                  |                                 | _        | S )a  
        Fit OneHotEncoder to X.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            The data to determine the categories of each feature.

        y : None
            Ignored. This parameter exists only for compatibility with
            :class:`~sklearn.pipeline.Pipeline`.

        Returns
        -------
        self
            Fitted encoder.
        	allow-nan)r]   r"   )rn   r]   r   r  _n_features_outs)r0   r1   ys      r9   fitzOneHotEncoder.fit  sX    & 			.) 	 	
 	
 	

 	 $ = = ? ?r;   c                    t          |            t          d|           d         }|dk    r3| j        r,|                                }t	          | d| d| d          | j        dk    rd	\  }}n| j        d
uo| j        dv }| j        }|                     ||d|          \  }}|j        \  }}	| j	        | j	        
                                }
||
k    }t          | j                  D ]\  }}|
|         t          |          |
|<    |
                    dd          }
|||
k    xx         dz  cc<   ||z  }|                                }t!          j        dg| j        z             }||d
d         z                                   |         }t!          j        |dz   t(                    }d|d<   t!          j        |d|dd
         |j                   t!          j        |dd
         |dd
                    t!          j        |d                   }t1          j        |||f||d         f| j                  }| j        s|                                S |S )a  
        Transform X using one-hot encoding.

        If `sparse_output=True` (default), it returns an instance of
        :class:`scipy.sparse._csr.csr_matrix` (CSR format).

        If there are infrequent categories for a feature, set by specifying
        `max_categories` or `min_frequency`, the infrequent categories are
        grouped into a single category.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            The data to encode.

        Returns
        -------
        X_out : {ndarray, sparse matrix} of shape                 (n_samples, n_encoded_features)
            Transformed input. If `sparse_output=True`, a sparse matrix will be
            returned.
        	transform)	estimatordensedefaultzH output does not support sparse data. Set sparse_output=False to output z dataframes or disable z1 output via` ohe.set_output(transform="default").r~   )Tr   N>   r   r   r
  )r]   r"   r   r#   rE   r   rC   )r%   outr!   )r  )r-   r!   )r   r   r   
capitalizerM   r]   r   r   r-   r   r|   r[   rN   rL   reshaperavelr)   cumsumr  r   rv   r   r!   rw   r   
csr_matrixtoarray)r0   r1   transform_outputcapitalize_transform_outputr   r]   r   r   r4   r5   to_drop
keep_cellsr7   rb   maskfeature_indicesr$   indptrdatar  s                       r9   r  zOneHotEncoder.transform  s   . 	-kTJJJ7Sy((T-?(*:*E*E*G*G'. 9 96F9 979 9 9   &((.I+O^^"it3 8K P 9O "0N))+	 ( 
 
v !&	:(4388::G ')J$T%566 + +41:%!$TGAJooa,,G%'/"""a'"""j F||~~)QC$*?$?@@?3B3//6688>)a-s333q	
vA6!"":V\BBBB
	&*&*----wvbz""7F#ob12*
 
 

 ! 	;;== Jr;   c                     t                      t          |d          }|j        \  }}t           j                  }t          j         j                  }d}|j        d         |k    r.t          |	                    ||j        d                              fdt           j                  D             }t          j        d |D              }t          j        ||f|          }	d}
i } j        r j        }nd	g|z  }t          |          D ]}                     ||         |          }|j        d         }|dk    r+ j        |          j        |                  |	d	d	|f<   |
|z  }
]|d	d	|
|
|z   f         }t          j        |                    d
                                                    }||         |	d	d	|f<    j        dk    s j        dv r||         t          j        |                    d
          dk                                              }|                                r= j         j        |         |||<   nĉ j        |          j        |                  |	||f<   nt          j        |                    d
          dk                                              }|                                rN j        't          j        |          }t          d| d           j        |         }||         |         |	||f<   |
|z  }

|rK|	j        t2          k    r|	                    t2                    }	|                                D ]\  }}d	|	||f<   |	S )a  
        Convert the data back to the original representation.

        When unknown categories are encountered (all zeros in the
        one-hot encoding), ``None`` is used to represent this category. If the
        feature with the unknown category has a dropped category, the dropped
        category will be its inverse.

        For a given input feature, if there is an infrequent category,
        'infrequent_sklearn' will be used to represent the infrequent category.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape                 (n_samples, n_encoded_features)
            The transformed data.

        Returns
        -------
        X_tr : ndarray of shape (n_samples, n_features)
            Inverse transformed array.
        csr)accept_sparseIShape of the passed X data is not correct. Expected {0} columns, got {1}.r#   c                 D    g | ]\  }}                     |d           S )F)r   r  r   r7   _r0   s      r9   r   z3OneHotEncoder.inverse_transform.<locals>.<listcomp>e  s@      
  
  
1 0050II 
  
  
r;   c                     g | ]	}|j         
S r   rC   r   s     r9   r   z3OneHotEncoder.inverse_transform.<locals>.<listcomp>k  s    HHHCciHHHr;   rC   r   N)r%   r   )r   r~   zSamples z] can not be inverted when drop=None and handle_unknown='error' because they contain all zeros)r   r   r-   rL   rN   r)   r   r  rM   rZ   r[   result_typer   rO   r   r.   r   r   r   argmaxflattenr]   rY   r   r!   r,   r{   items)r0   r1   r4   r)  r5   r   re   transformed_featuresdtX_trjfound_unknownr   r7   cats_wo_droppedn_categoriessublabelsunknowndroppedall_zero_samplesr   idxr  s   `                       r9   inverse_transformzOneHotEncoder.inverse_transform?  s   . 	///w	1)**
 566 X 	 71:''SZZ
CCDDD 
  
  
  
!$"233 
  
  
 ^HH3GHHHIxJ/r:::# 	5!%!9"&*!4z"" 3	 3	A"==$Q' O +03L
 q  !-a01Nq1QRQQQT
\!AAAq1|+++,CZ


 2 233;;==F(0DAJ"h..#'FFF&q)1*SWW!W__%9::BBDD;;==  5=8;C+2a((+/+;A+> 9!<,WaZ( *SWW!W__%9::BBDD;;== I4<+->'+B+B((='7 = = =    $<Q?H';A'>x'HD!$AA  	'zV##{{6***0022 ' '	T"&T3Yr;   c                 ~    t                      t                      fdt           j                  D             }                                 g }t          t          |                    D ]-fd|         D             }|                    |           .t          j	        |t                    S )a  Get output feature names for transformation.

        Parameters
        ----------
        input_features : array-like of str or None, default=None
            Input features.

            - If `input_features` is `None`, then `feature_names_in_` is
              used as feature names in. If `feature_names_in_` is not defined,
              then the following input feature names are generated:
              `["x0", "x1", ..., "x(n_features_in_ - 1)"]`.
            - If `input_features` is an array-like, then `input_features` must
              match `feature_names_in_` if `feature_names_in_` is defined.

        Returns
        -------
        feature_names_out : ndarray of str objects
            Transformed feature names.
        c                 @    g | ]\  }}                     |          S r   r'  r(  s      r9   r   z7OneHotEncoder.get_feature_names_out.<locals>.<listcomp>  s;     
 
 
1 0033
 
 
r;   c                 4    g | ]}          |          S r   r   )r   tr7   input_featuresname_combiners     r9   r   z7OneHotEncoder.get_feature_names_out.<locals>.<listcomp>  s*    JJJQ]]>!#4a88JJJr;   rC   )r   r   r[   rN    _check_get_feature_name_combinerr.   rL   extendr)   rP   r,   )r0   rA  rb   feature_namesnamesr7   rB  s   ``   @@r9   get_feature_names_outz#OneHotEncoder.get_feature_names_out  s    ( 	0~FF
 
 
 
!$"233
 
 

 ==??s4yy!! 	( 	(AJJJJJJ$q'JJJE  ''''xV4444r;   c                     | j         dk    rd S |                      dd          }t          |t                    s t          dt	          |           d          | j         S )Nr   c                 ,    | dz   t          |          z   S )Nr)  )r   )featurerf   s     r9   <lambda>z@OneHotEncoder._check_get_feature_name_combiner.<locals>.<lambda>  s    Ws]S]]-J r;   rJ  rf   zRWhen `feature_name_combiner` is a callable, it should return a Python string. Got z	 instead.)r   rQ   r   	TypeErrorrT   )r0   dry_run_combiners     r9   rC  z.OneHotEncoder._check_get_feature_name_combiner  s    %11JJJ#99)ZPP.44 L*./?*@*@L L L   --r;   r   r   )rU   r   r   r   r   listr   r   r   callabler   dict__annotations__r)   float64r   r   r   r  r   r  r	   r  r  r<  rG  rC  r   r;   r9   r   r     s        Q Qh "z6(++T2Wk233\4H JIIIJJ
 $8HafEEEtLHXq$v666HZAi888

 $",*hZ"8"8(!C$ $D   ( j&; ; ; ; ;*/ / /0rA rA rAh   .    * \555   656U U Unu u un!5 !5 !5 !5F
. 
. 
. 
. 
.r;   c                   `   e Zd ZU dZ edh          egde eej	                  g eddh          ge eej	                  dg e
eddd	          dg e
eddd	           e
ed
dd	          dgdZeed<   dej        ddej	        ddddZ ed          dd            Zd Zd ZdS )r   a  
    Encode categorical features as an integer array.

    The input to this transformer should be an array-like of integers or
    strings, denoting the values taken on by categorical (discrete) features.
    The features are converted to ordinal integers. This results in
    a single column of integers (0 to n_categories - 1) per feature.

    Read more in the :ref:`User Guide <preprocessing_categorical_features>`.
    For a comparison of different encoders, refer to:
    :ref:`sphx_glr_auto_examples_preprocessing_plot_target_encoder.py`.

    .. versionadded:: 0.20

    Parameters
    ----------
    categories : 'auto' or a list of array-like, default='auto'
        Categories (unique values) per feature:

        - 'auto' : Determine categories automatically from the training data.
        - list : ``categories[i]`` holds the categories expected in the ith
          column. The passed categories should not mix strings and numeric
          values, and should be sorted in case of numeric values.

        The used categories can be found in the ``categories_`` attribute.

    dtype : number type, default=np.float64
        Desired dtype of output.

    handle_unknown : {'error', 'use_encoded_value'}, default='error'
        When set to 'error' an error will be raised in case an unknown
        categorical feature is present during transform. When set to
        'use_encoded_value', the encoded value of unknown categories will be
        set to the value given for the parameter `unknown_value`. In
        :meth:`inverse_transform`, an unknown category will be denoted as None.

        .. versionadded:: 0.24

    unknown_value : int or np.nan, default=None
        When the parameter handle_unknown is set to 'use_encoded_value', this
        parameter is required and will set the encoded value of unknown
        categories. It has to be distinct from the values used to encode any of
        the categories in `fit`. If set to np.nan, the `dtype` parameter must
        be a float dtype.

        .. versionadded:: 0.24

    encoded_missing_value : int or np.nan, default=np.nan
        Encoded value of missing categories. If set to `np.nan`, then the `dtype`
        parameter must be a float dtype.

        .. versionadded:: 1.1

    min_frequency : int or float, default=None
        Specifies the minimum frequency below which a category will be
        considered infrequent.

        - If `int`, categories with a smaller cardinality will be considered
          infrequent.

        - If `float`, categories with a smaller cardinality than
          `min_frequency * n_samples`  will be considered infrequent.

        .. versionadded:: 1.3
            Read more in the :ref:`User Guide <encoder_infrequent_categories>`.

    max_categories : int, default=None
        Specifies an upper limit to the number of output categories for each input
        feature when considering infrequent categories. If there are infrequent
        categories, `max_categories` includes the category representing the
        infrequent categories along with the frequent categories. If `None`,
        there is no limit to the number of output features.

        `max_categories` do **not** take into account missing or unknown
        categories. Setting `unknown_value` or `encoded_missing_value` to an
        integer will increase the number of unique integer codes by one each.
        This can result in up to `max_categories + 2` integer codes.

        .. versionadded:: 1.3
            Read more in the :ref:`User Guide <encoder_infrequent_categories>`.

    Attributes
    ----------
    categories_ : list of arrays
        The categories of each feature determined during ``fit`` (in order of
        the features in X and corresponding with the output of ``transform``).
        This does not include categories that weren't seen during ``fit``.

    n_features_in_ : int
        Number of features seen during :term:`fit`.

        .. versionadded:: 1.0

    feature_names_in_ : ndarray of shape (`n_features_in_`,)
        Names of features seen during :term:`fit`. Defined only when `X`
        has feature names that are all strings.

        .. versionadded:: 1.0

    infrequent_categories_ : list of ndarray
        Defined only if infrequent categories are enabled by setting
        `min_frequency` or `max_categories` to a non-default value.
        `infrequent_categories_[i]` are the infrequent categories for feature
        `i`. If the feature `i` has no infrequent categories
        `infrequent_categories_[i]` is None.

        .. versionadded:: 1.3

    See Also
    --------
    OneHotEncoder : Performs a one-hot encoding of categorical features. This encoding
        is suitable for low to medium cardinality categorical variables, both in
        supervised and unsupervised settings.
    TargetEncoder : Encodes categorical features using supervised signal
        in a classification or regression pipeline. This encoding is typically
        suitable for high cardinality categorical variables.
    LabelEncoder : Encodes target labels with values between 0 and
        ``n_classes-1``.

    Notes
    -----
    With a high proportion of `nan` values, inferring categories becomes slow with
    Python versions before 3.10. The handling of `nan` values was improved
    from Python 3.10 onwards, (c.f.
    `bpo-43475 <https://github.com/python/cpython/issues/87641>`_).

    Examples
    --------
    Given a dataset with two features, we let the encoder find the unique
    values per feature and transform the data to an ordinal encoding.

    >>> from sklearn.preprocessing import OrdinalEncoder
    >>> enc = OrdinalEncoder()
    >>> X = [['Male', 1], ['Female', 3], ['Female', 2]]
    >>> enc.fit(X)
    OrdinalEncoder()
    >>> enc.categories_
    [array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)]
    >>> enc.transform([['Female', 3], ['Male', 1]])
    array([[0., 2.],
           [1., 0.]])

    >>> enc.inverse_transform([[1, 0], [0, 1]])
    array([['Male', 1],
           ['Female', 2]], dtype=object)

    By default, :class:`OrdinalEncoder` is lenient towards missing values by
    propagating them.

    >>> import numpy as np
    >>> X = [['Male', 1], ['Female', 3], ['Female', np.nan]]
    >>> enc.fit_transform(X)
    array([[ 1.,  0.],
           [ 0.,  1.],
           [ 0., nan]])

    You can use the parameter `encoded_missing_value` to encode missing values.

    >>> enc.set_params(encoded_missing_value=-1).fit_transform(X)
    array([[ 1.,  0.],
           [ 0.,  1.],
           [ 0., -1.]])

    Infrequent categories are enabled by setting `max_categories` or `min_frequency`.
    In the following example, "a" and "d" are considered infrequent and grouped
    together into a single category, "b" and "c" are their own categories, unknown
    values are encoded as 3 and missing values are encoded as 4.

    >>> X_train = np.array(
    ...     [["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3 + [np.nan]],
    ...     dtype=object).T
    >>> enc = OrdinalEncoder(
    ...     handle_unknown="use_encoded_value", unknown_value=3,
    ...     max_categories=3, encoded_missing_value=4)
    >>> _ = enc.fit(X_train)
    >>> X_test = np.array([["a"], ["b"], ["c"], ["d"], ["e"], [np.nan]], dtype=object)
    >>> enc.transform(X_test)
    array([[2.],
           [0.],
           [1.],
           [2.],
           [3.],
           [4.]])
    rA   r   r<   use_encoded_valueNr#   r   r   r   r   )rK   r!   encoded_missing_valuer]   unknown_valuer   r   r   rK   r!   r]   rV  rU  r   r   c                h    || _         || _        || _        || _        || _        || _        || _        d S r   rW  )r0   rK   r!   r]   rV  rU  r   r   s           r9   r   zOrdinalEncoder.__init__  s@     %
,*%:"*,r;   Tr  c                      j         dk    rt           j                  r;t          j         j                  j        dk    rt          d j         d          nWt           j        t          j	                  st          d j         d          n j        t          d j         d                               | j         dd	
          }|d          _        d  j        D             } j        r9t           j                  D ]$\  }}|||xx         t#          |          z  cc<   %t           j                  D ]*\  }}t          |d                   r||xx         dz  cc<   + j         dk    r2|D ]/}	d j        cxk    r|	k     rn t          d j         d          0 j        rt          j         j                  j        dk    rAt           j                  r-t          dt'           j                   d j         d          t           j                  sT fdt          |          D             }
|
r7t)           d          r j        |
         }
t          d j         d|
            S )a  
        Fit the OrdinalEncoder to X.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            The data to determine the categories of each feature.

        y : None
            Ignored. This parameter exists only for compatibility with
            :class:`~sklearn.pipeline.Pipeline`.

        Returns
        -------
        self : object
            Fitted encoder.
        rT  fzOWhen unknown_value is np.nan, the dtype parameter should be a float dtype. Got .z]unknown_value should be an integer or np.nan when handle_unknown is 'use_encoded_value', got NzQunknown_value should only be set when handle_unknown is 'use_encoded_value', got r
  T)r]   r"   r^   rH   c                 ,    g | ]}t          |          S r   r   )r   rK   s     r9   r   z&OrdinalEncoder.fit.<locals>.<listcomp>  s    LLLZZLLLr;   rE   r#   r   z!The used value for unknown_value zD is one of the values already used for encoding the seen categories.z%There are missing values in features z:. For OrdinalEncoder to encode missing values with dtype: zG, set encoded_missing_value to a non-nan value, or set dtype to a floatc                 V    g | ]%\  }}|j         v rd j        cxk    r|k      n n|&S )r   )_missing_indicesrU  )r   cat_idxcardinalityr0   s      r9   r   z&OrdinalEncoder.fit.<locals>.<listcomp>  s]     $ $ $,$"777T7EEEE+EEEEE  FEEr;   feature_names_in_zencoded_missing_value (z:) is already used to encode a known category in features: )r]   r   rV  r)   r!   rS   rM   rQ   r   r   rL  rn   r^  rN   rO   r[   r   rL   rU  rN  r'   ra  )r0   r1   r  fit_resultscardinalitiesrl   
infrequentr_  rm   r`  invalid_featuress   `          r9   r  zOrdinalEncoder.fit  s   & "555T/00 8DJ'',33$<.2j< < <   4   2G4DEE 1  -1 1 1   +-)- - -   ii.)59	   
 
 !,,= >LL4;KLLL# 	B ,5T5P+Q+Q B B'Z)!+...#j//A... ,5T5E+F+F 	, 	,'G'/344 ,g&&&!+&&&"555,  *8888[88888$+-+ + +   9   	x
##(C//M*5 5/ !+D122+ +9=+ + +   !!;<< $ $ $ $09-0H0H$ $ $  $ t%899 T+/+ABR+S($.$2L . .+. .   r;   c                 L   t          | d           |                     || j        d| j                  \  }}|                    | j        d          }| j                                        D ]!\  }}|dd|f         |k    }| j        |||f<   "| j        dk    r| j        || <   |S )a'  
        Transform X to ordinal codes.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            The data to encode.

        Returns
        -------
        X_out : ndarray of shape (n_samples, n_features)
            Transformed input.
        rN   r
  )r]   r"   r   Fr|   NrT  )	r   r   r]   r^  r{   r!   r.  rU  rV  )r0   r1   r   r   X_transr_  missing_idxX_missing_masks           r9   r  zOrdinalEncoder.transform.  s     	m,,,.)$($9	 ( 
 
v ,,tz,66$($9$?$?$A$A 	J 	J G["111g:.+=N/3/IGNG+,, "555#1GVGr;   c                    t          |            t          |d          }|j        \  }}t          | j                  }d}|j        d         |k    r.t          |                    ||j        d                             t          j        d | j        D              }t          j	        ||f|          }i }i }	t          | dd          }
t          |          D ]<}|dd|f         }|| j        v r%t          || j                  }| j        |         ||<   t          d          }| j        |         }|
m|
|         et          |          t          |
|                   z
  }||k    |	|<   |	|          }t          j        |t"                    }d	||
|         <   ||         }| j        d
k    r?t          || j                  }|||<   | }t)          |t          j                  r||z  }n|}||                             dd	          }||         |||f<   >|s|	r|                    t.          d	          }|r!|                                D ]\  }}d|||f<   |	r!|	                                D ]\  }}d|||f<   |S )aP  
        Convert the data back to the original representation.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_encoded_features)
            The transformed data.

        Returns
        -------
        X_tr : ndarray of shape (n_samples, n_features)
            Inverse transformed array.
        r
  r@   r%  r#   c                     g | ]	}|j         
S r   rC   r   s     r9   r   z4OrdinalEncoder.inverse_transform.<locals>.<listcomp>j  s    DDDCciDDDr;   rC   r   NFrT  r   rg  r   )r   r   r-   rL   rN   rM   rZ   r)   r+  r   r(   r.   r^  r   rU  r   	ones_likerx   r]   rV  rQ   ndarrayr{   r,   r.  )r0   r1   r4   r)  r5   re   r0  r1  r3  infrequent_masksr   r7   r7  X_i_maskr   rK   infrequent_encoding_valuefrequent_categories_maskunknown_labelsknown_labels
labels_intr;  r  s                          r9   r<  z OrdinalEncoder.inverse_transformN  s    	[999w	1)**
 X 	 71:##SZZ
AGAJ??@@@ ^DD43CDDDExJ/r:::$T+@$GGz"" "	= "	=Aqqq!tWF D)))$VT-GHH#'#8#;x "4[[N)!,J!-2DQ2G2S,/
OOcBTUVBW>X>X,X)&,0I&I #"21"5!5 ,.<
$+O+O+O(BG();A)>?'(@A
"&999!*643E!F!F#1a  .nbj99 2"l2NN%1N/66wU6KKJ&0&<D"## 	3, 	3;;vE;22D  	'*0022 ' '	T"&T3Y 	7-3355 7 7	T"6T3Yr;   r   )rU   r   r   r   r   rN  r   rT   r)   nanr   r   r   rP  rQ  rR  r   r	   r  r  r<  r   r;   r9   r   r     sp        w wt "z6(++T2 "*DDLL!9%:w0C&DEEF"DDLL$7#8HafEEEtLHXq$v666HZAi888
$ $D   " j f- - - - -& \555j j j 65jX  @T T T T Tr;   )'r   r}   r   numpyr)   scipyr   baser   r   r   r	   utilsr
   r   utils._encoder   r   r   r   utils._maskr   utils._missingr   utils._param_validationr   r   r   utils._set_outputr   utils.validationr   r   r   r   __all__r   r   r   r   r;   r9   <module>r     s                     V V V V V V V V V V V V / / / / / / / / I I I I I I I I I I I I # # # # # # * * * * * * F F F F F F F F F F 2 2 2 2 2 2            ,
-r r r r r#] r r rjR. R. R. R. R.L R. R. R.j| | | | |)< | | | | |r;   