a
    ;Za%                     @   s   d dl Z d dlZd dlmZ d dlZddlmZmZ ddl	m
Z
mZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZmZ ddgZG dd deeZG dd deZG dd deZdS )    N)sparse   )BaseEstimatorTransformerMixin)check_arrayis_scalar_nan)
deprecated)check_is_fitted)_check_feature_names_in)	_get_mask)_encode_check_unknown_uniqueOneHotEncoderOrdinalEncoderc                   @   s>   e Zd ZdZdddZdd Zddd	ZdddZdd ZdS )_BaseEncoderzm
    Base class for encoders that includes the code to categorize and
    transform the input features.

    Tc           
      C   s   t |drt|dddks\t|d|d}t |dsRt|jtjrRt|t|d}n|}d}n|}|j\}}g }t	|D ],}| j
||d	}	t|	dd|d
}	||	 qv|||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force_all_finiter   F)feature_idx)Z	ensure_2dr   r   )hasattrgetattrr   npZ
issubdtyper   Zstr_objectshaperange_get_featureappend)
selfXr   ZX_tempZneeds_validation	n_samples
n_featuresZ	X_columnsiXi r%   >lib/python3.9/site-packages/sklearn/preprocessing/_encoders.py_check_X   s     
z_BaseEncoder._check_Xc                 C   s,   t |dr|jd d |f S |d d |f S )Nr   )r   r   )r   r    r   r%   r%   r&   r   C   s    
z_BaseEncoder._get_featureerrorc                 C   sT  | j |dd | j|dd | j||d\}}}|| _| jdkrVt| j|krVtdg | _t|D ]}|| }| jdkrt	|}	nt
j| j| |jd}	|jjdvrt
|	}
d}t
|
d	 rd	nd }t
|
d | |	d | kst
|
d	 rt
|
d	 st||d
krBt||	}|rBd||}t|| j|	 qdd S )NTresetr   autozOShape mismatch: if categories is an array, it has to be of shape (n_features,).r   ZOUSz>Unsorted categories are not supported for numerical categoriesr(   z5Found unknown categories {0} in column {1} during fit)_check_n_features_check_feature_namesr'   Zn_features_in_
categorieslen
ValueErrorcategories_r   r   r   arrayr   kindsortZisnananyr   formatr   )r   r    handle_unknownr   X_listr!   r"   r#   r$   catsZsorted_catsZ	error_msgZstop_idxdiffmsgr%   r%   r&   _fitJ   sJ    



 

z_BaseEncoder._fitFc                 C   s  | j |dd | j|dd | j||d\}}}tj||ftd}tj||ftd}	g }
t|D ]}|| }t	|| j
| dd\}}t|sT|dkrd||}t|n|r|
| ||	d d |f< | j
| jjd	v r
| j
| j|jkr
|| j
| j}n6| j
| jjd
kr8|jjdkr8|d
}n| }| j
| d || < t|| j
| dd|d d |f< q`|
rtd|
 dt ||	fS )NFr)   r+   r-   T)Zreturn_maskr(   z;Found unknown categories {0} in column {1} during transform)USOr@   r   )ZuniquesZcheck_unknownz$Found unknown categories in columns zH during transform. These unknown categories will be encoded as all zeros)r0   r/   r'   r   zerosintonesboolr   r   r4   allr9   r3   r   r   r6   itemsizeastypecopyr   warningswarnUserWarning)r   r    r:   r   warn_on_unknownr;   r!   r"   X_intX_maskZcolumns_with_unknownr#   r$   r=   Z
valid_maskr>   r%   r%   r&   
_transformw   sN    

""z_BaseEncoder._transformc                 C   s
   ddgiS )NZX_typesZcategoricalr%   )r   r%   r%   r&   
_more_tags   s    z_BaseEncoder._more_tagsN)T)r(   T)r(   TF)	__name__
__module____qualname____doc__r'   r   r?   rQ   rR   r%   r%   r%   r&   r      s   
%
. 
<r   c                       s   e Zd ZdZdddejddddZd	d
 Zdd ZdddZ	d fdd	Z
dd Zdd ZeddddZdddZ  ZS )r   ui  
    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``
    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>`.

    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 a neural network or an unregularized regression.

        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.

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

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

    sparse : bool, default=True
        Will return sparse matrix if set True else will return an array.

    dtype : number type, default=float
        Desired dtype of output.

    handle_unknown : {'error', 'ignore'}, default='error'
        Whether to raise an error or ignore if an unknown categorical feature
        is present during transform (default is to raise). When this parameter
        is set to 'ignore' and 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.

    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.

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

    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

    See Also
    --------
    OrdinalEncoder : Performs an ordinal (integer)
      encoding of the categorical features.
    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.]])
    r,   NTr(   )r1   dropr   r   r:   c                C   s"   || _ || _|| _|| _|| _d S N)r1   r   r   r:   rW   )r   r1   rW   r   r   r:   r%   r%   r&   __init__[  s
    	zOneHotEncoder.__init__c                 C   s"   | j dvrd| j }t|d S )N)r(   ignorez=handle_unknown should be either 'error' or 'ignore', got {0}.)r:   r9   r3   )r   r>   r%   r%   r&   _validate_keywordsj  s    
z OneHotEncoder._validate_keywordsc              	   C   s  | j d u rd S t| j trx| j dkr8tjt| jtdS | j dkr\tjdd | jD tdS d}t	|
t| j nVztj| j td}t|}W n, t	tfy   d}t	|
t|Y n0 |t| jkrd}t	|
t| j|g }g }tt|| jD ]\}\}}t|sTt||kd }	|	jrB||	d  n|||f qt|D ]$\}
}t|r\||
  qq\|||f qt|rd	
d
dd |D }t	|tj|tdS d S )Nfirstr-   Z	if_binaryc                 S   s    g | ]}t |d krdndqS )r   r   Nr2   .0r<   r%   r%   r&   
<listcomp>{      z3OneHotEncoder._compute_drop_idx.<locals>.<listcomp>zaWrong input for parameter `drop`. Expected 'first', 'if_binary', None or array of objects, got {}zF`drop` should have length equal to the number of features ({}), got {}r   zaThe following categories were supposed to be dropped, but were not found in the training data.
{}
c                 S   s   g | ]\}}d  ||qS )zCategory: {}, Feature: {})r9   )r_   cvr%   r%   r&   r`     s   )rW   
isinstancestrr   rC   r2   r4   r   r5   r3   r9   typeasarray	TypeError	enumeratezipr   wheresizer   r8   join)r   r>   Z
drop_arrayZdroplenZmissing_dropsZdrop_indicesZcol_idxvalZcat_listZdrop_idxcat_idxcatr%   r%   r&   _compute_drop_idxs  sf    








zOneHotEncoder._compute_drop_idxc                 C   s(   |    | j|| jd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   )r[   r?   r:   rr   	drop_idx_r   r    yr%   r%   r&   fit  s    
zOneHotEncoder.fitc                    s   |    t ||S )af  
        Fit OneHotEncoder to X, then transform X.

        Equivalent to fit(X).transform(X) but more convenient.

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

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

        Returns
        -------
        X_out : {ndarray, sparse matrix} of shape                 (n_samples, n_encoded_features)
            Transformed input. If `sparse=True`, a sparse matrix will be
            returned.
        )r[   superfit_transformrv   	__class__r%   r&   rz     s    zOneHotEncoder.fit_transformc                 C   s  t |  | jdko| jdu}| j|| jd|d\}}|j\}}| jdur| j }||k}g }	t| jD ]>\}
}t	|}||
 du r|||
< |	
| qh|	
|d  qh|dd}|||k  d8  < ||M }ndd | jD }	| }td	g|	 }||dd   | }tj|d td
}d	|d	< tj|d|dd |jd tj|dd |dd d t|d }tj|||f||d f| jd}| js| S |S dS )a  
        Transform X using one-hot encoding.

        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=True`, a sparse matrix will be
            returned.
        rZ   Nrs   )r:   r   rN      r.   c                 S   s   g | ]}t |qS r%   r]   r^   r%   r%   r&   r`     ra   z+OneHotEncoder.transform.<locals>.<listcomp>r   r-   )axisoutr   )r   )r   r   )r	   r:   rW   rQ   r   ru   rJ   rj   r4   r2   r   ZreshapeZravelr   ZcumsumemptyrD   sumr   rE   r   Z
csr_matrixZtoarray)r   r    rN   rO   rP   r!   r"   to_dropZ
keep_cellsZn_valuesr#   r<   Zn_catsmaskZfeature_indicesindicesZindptrdatar   r%   r%   r&   	transform  sN    





zOneHotEncoder.transformc                 C   s  t |  t|dd}|j\}}t| j}| jdu rHtdd | jD }ntdd t| j| jD }d}|jd |krt|	||jd t
d	d
 | jD g }t
j||f|d}d}	i }
t|D ]}| jdu s| j| du r| j| }nt
| j| | j| }t|}|dkrD| j| | j|  |dd|f< |	|7 }	q|dd|	|	| f }t
|jdd }|| |dd|f< | jdkrt
|jdddk }| r`| jdu s| j| du r||
|< n| j| | j|  |||f< nft
|jdddk }| r`| jdu rDt
|}td| d| j| | j|  |||f< |	|7 }	q|
r|jtkr|t}|
 D ]\}}d|||f< q|S )aw  
        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.

        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.
        Zcsr)Zaccept_sparseNc                 s   s   | ]}t |V  qd S rX   r]   r^   r%   r%   r&   	<genexpr>K  ra   z2OneHotEncoder.inverse_transform.<locals>.<genexpr>c                 s   s.   | ]&\}}|d urt |d nt |V  qd S )Nr}   r]   )r_   r<   r   r%   r%   r&   r   M  s   IShape of the passed X data is not correct. Expected {0} columns, got {1}.r}   c                 S   s   g | ]
}|j qS r%   r-   r_   rq   r%   r%   r&   r`   Z  ra   z3OneHotEncoder.inverse_transform.<locals>.<listcomp>r-   r   )r~   rZ   zSamples z] can not be inverted when drop=None and handle_unknown='error' because they contain all zeros)r	   r   r   r2   r4   ru   r   rk   r3   r9   r   find_common_typer   r   deleterh   ZargmaxZflattenr:   r8   Zflatnonzeror   r   rI   items)r   r    r!   _r"   Zn_transformed_featuresr>   dtX_trjfound_unknownr#   r<   Zn_categoriessublabelsunknownZdroppedZall_zero_samplesidxr   r%   r%   r&   inverse_transform1  sd    



 






zOneHotEncoder.inverse_transformzlget_feature_names is deprecated in 1.0 and will be removed in 1.2. Please use get_feature_names_out instead.c                    s   t |  | j}du r.dd tt|D n,tt| jkrZtdt| jtg }tt|D ]N  fdd|  D }| jdur| j  dur|| j   || qjt	j
|tdS )a  Return feature names for output features.

        Parameters
        ----------
        input_features : list of str of shape (n_features,)
            String names for input features if available. By default,
            "x0", "x1", ... "xn_features" is used.

        Returns
        -------
        output_feature_names : ndarray of shape (n_output_features,)
            Array of feature names.
        Nc                 S   s   g | ]}d | qS )zx%dr%   )r_   r#   r%   r%   r&   r`     ra   z3OneHotEncoder.get_feature_names.<locals>.<listcomp>zJinput_features should have length equal to number of features ({}), got {}c                    s    g | ]}  d  t | qS r   rf   r_   tr#   input_featuresr%   r&   r`     ra   r-   )r	   r4   r   r2   r3   r9   ru   popextendr   r5   r   r   r   r<   Zfeature_namesnamesr%   r   r&   get_feature_names  s"    zOneHotEncoder.get_feature_namesc                    s   t |  | j}t| g }tt|D ]N  fdd|  D }| jdurl| j  durl|| j   || q(tj	|t
d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 names are generated: `[x0, x1, ..., x(n_features_in_)]`.
            - 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                    s    g | ]}  d  t | qS r   r   r   r   r%   r&   r`     ra   z7OneHotEncoder.get_feature_names_out.<locals>.<listcomp>Nr-   )r	   r4   r
   r   r2   ru   r   r   r   rh   r   r   r%   r   r&   get_feature_names_out  s    
z#OneHotEncoder.get_feature_names_out)N)N)N)N)rS   rT   rU   rV   r   float64rY   r[   rr   rx   rz   r   r   r   r   r   __classcell__r%   r%   r{   r&   r      s&    '	G
Gf#c                   @   s@   e Zd ZdZdejdddddZddd	Zd
d Zdd Z	dS )r   aO  
    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>`.

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

    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

    See Also
    --------
    OneHotEncoder : Performs a one-hot encoding of categorical features.
    LabelEncoder : Encodes target labels with values between 0 and
        ``n_classes-1``.

    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)
    r,   r(   Nr1   r   r:   unknown_valuec                C   s   || _ || _|| _|| _d S rX   r   )r   r1   r   r:   r   r%   r%   r&   rY   9  s    zOrdinalEncoder.__init__c           	      C   sn  d}| j |vr td| j  d| j dkr|t| jrZt| jjdkrztd| j dqt| jtj	st
d| j dn| jdurt
d	| j d| j|| j d
d | j dkr| jD ]4}d| j  krt|k rn qtd| j dqi | _t| jD ]6\}}t|D ]"\}}t|r|| j|< qqq t| jjdkrj| jrjtdt| 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.
        )r(   use_encoded_valuezDhandle_unknown should be either 'error' or 'use_encoded_value', got .r   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 rs   rt   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 zW. For OrdinalEncoder to passthrough missing values, the dtype parameter must be a float)r:   r3   r   r   r   r   r6   re   numbersZIntegralri   r?   r4   r2   _missing_indicesrj   list)	r   r    rw   Zhandle_unknown_strategiesZfeature_catsrp   Zcategories_for_idxr#   rq   r%   r%   r&   rx   F  sb    







zOrdinalEncoder.fitc                 C   sv   | j || jdd\}}|j| jdd}| j D ]*\}}|dd|f |k}tj|||f< q0| jdkrr| 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.
        rs   rt   FrJ   Nr   )	rQ   r:   rI   r   r   r   r   nanr   )r   r    rO   rP   ZX_transrp   Zmissing_idxZX_missing_maskr%   r%   r&   r     s    

zOrdinalEncoder.transformc                 C   sl  t |  t|dd}|j\}}t| j}d}|jd |krPt|||jd tdd | jD g }tj	||f|d}i }t
|D ]}	|dd|	f jd	d
d}
|	| jv rt|dd|	f tj}| j|	 |
|< | jdkr|
| jk}| j|	 t|d|
 |dd|	f< |||	< q| j|	 |
 |dd|	f< q|rh|jtd
d}| D ]\}}d|||f< qP|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.
        rs   r+   r   r}   c                 S   s   g | ]
}|j qS r%   r-   r   r%   r%   r&   r`     ra   z4OrdinalEncoder.inverse_transform.<locals>.<listcomp>r-   NZint64Fr   r   r   )r	   r   r   r2   r4   r3   r9   r   r   r   r   rI   r   r   r   r:   r   rl   r   r   )r   r    r!   r   r"   r>   r   r   r   r#   r   ZX_i_maskZunknown_labelsr   r   r%   r%   r&   r     s4    



$
z OrdinalEncoder.inverse_transform)N)
rS   rT   rU   rV   r   r   rY   rx   r   r   r%   r%   r%   r&   r     s   ]
N)rK   Znumpyr   Zscipyr   r   baser   r   Zutilsr   r   Zutils.deprecationr   Zutils.validationr	   r
   Zutils._maskr   Zutils._encoder   r   r   __all__r   r   r   r%   r%   r%   r&   <module>   s&    !    +