U
    3d*                     @   s<  d Z ddlmZ ddlmZ ddlZddlmZ ddl	m
Z
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 ddlmZ ddlmZ ddl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#m$Z$ dddgZ%dZ&G dd deeZ'dd Z(dd Z)dd Z*dddd d!d"d#dZ+G d$d dZ,dS )%z
The :mod:`sklearn.compose._column_transformer` module implements utilities
to work with heterogeneous data and to apply different transformers to
different columns.
    )chain)CounterN)sparse   )cloneTransformerMixin)_VisualBlock)_fit_transform_one_transform_one_name_estimators)FunctionTransformer)Bunch)_safe_indexing)_get_column_indices)_get_output_config_safe_set_output)check_pandas_support)_BaseComposition)check_arraycheck_is_fitted_check_feature_names_in)delayedParallelColumnTransformermake_column_transformermake_column_selectorz1D data passed to a transformer that expects 2D data. Try to specify the column selection as a list of one item instead of a scalar.c                       s  e Zd ZdZdgZdddddddd	d
Zedd Zejdd Zdd fdd
Z	d9ddZ
dd Zd:ddZdd Zdd Zdd Zedd Zdd  Zd;d!d"Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd<d-d.Zd=d/d0Zd>d1d2Zd3d4 Zd5d6 Zd7d8 Z  ZS )?r   aa   Applies transformers to columns of an array or pandas DataFrame.

    This estimator allows different columns or column subsets of the input
    to be transformed separately and the features generated by each transformer
    will be concatenated to form a single feature space.
    This is useful for heterogeneous or columnar data, to combine several
    feature extraction mechanisms or transformations into a single transformer.

    Read more in the :ref:`User Guide <column_transformer>`.

    .. versionadded:: 0.20

    Parameters
    ----------
    transformers : list of tuples
        List of (name, transformer, columns) tuples specifying the
        transformer objects to be applied to subsets of the data.

        name : str
            Like in Pipeline and FeatureUnion, this allows the transformer and
            its parameters to be set using ``set_params`` and searched in grid
            search.
        transformer : {'drop', 'passthrough'} or estimator
            Estimator must support :term:`fit` and :term:`transform`.
            Special-cased strings 'drop' and 'passthrough' are accepted as
            well, to indicate to drop the columns or to pass them through
            untransformed, respectively.
        columns :  str, array-like of str, int, array-like of int,                 array-like of bool, slice or callable
            Indexes the data on its second axis. Integers are interpreted as
            positional columns, while strings can reference DataFrame columns
            by name.  A scalar string or int should be used where
            ``transformer`` expects X to be a 1d array-like (vector),
            otherwise a 2d array will be passed to the transformer.
            A callable is passed the input data `X` and can return any of the
            above. To select multiple columns by name or dtype, you can use
            :obj:`make_column_selector`.

    remainder : {'drop', 'passthrough'} or estimator, default='drop'
        By default, only the specified columns in `transformers` are
        transformed and combined in the output, and the non-specified
        columns are dropped. (default of ``'drop'``).
        By specifying ``remainder='passthrough'``, all remaining columns that
        were not specified in `transformers`, but present in the data passed
        to `fit` will be automatically passed through. This subset of columns
        is concatenated with the output of the transformers. For dataframes,
        extra columns not seen during `fit` will be excluded from the output
        of `transform`.
        By setting ``remainder`` to be an estimator, the remaining
        non-specified columns will use the ``remainder`` estimator. The
        estimator must support :term:`fit` and :term:`transform`.
        Note that using this feature requires that the DataFrame columns
        input at :term:`fit` and :term:`transform` have identical order.

    sparse_threshold : float, default=0.3
        If the output of the different transformers contains sparse matrices,
        these will be stacked as a sparse matrix if the overall density is
        lower than this value. Use ``sparse_threshold=0`` to always return
        dense.  When the transformed output consists of all dense data, the
        stacked result will be dense, and this keyword will be ignored.

    n_jobs : int, default=None
        Number of jobs to run in parallel.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    transformer_weights : dict, default=None
        Multiplicative weights for features per transformer. The output of the
        transformer is multiplied by these weights. Keys are transformer names,
        values the weights.

    verbose : bool, default=False
        If True, the time elapsed while fitting each transformer will be
        printed as it is completed.

    verbose_feature_names_out : bool, default=True
        If True, :meth:`get_feature_names_out` will prefix all feature names
        with the name of the transformer that generated that feature.
        If False, :meth:`get_feature_names_out` will not prefix any feature
        names and will error if feature names are not unique.

        .. versionadded:: 1.0

    Attributes
    ----------
    transformers_ : list
        The collection of fitted transformers as tuples of
        (name, fitted_transformer, column). `fitted_transformer` can be an
        estimator, 'drop', or 'passthrough'. In case there were no columns
        selected, this will be the unfitted transformer.
        If there are remaining columns, the final element is a tuple of the
        form:
        ('remainder', transformer, remaining_columns) corresponding to the
        ``remainder`` parameter. If there are remaining columns, then
        ``len(transformers_)==len(transformers)+1``, otherwise
        ``len(transformers_)==len(transformers)``.

    named_transformers_ : :class:`~sklearn.utils.Bunch`
        Read-only attribute to access any transformer by given name.
        Keys are transformer names and values are the fitted transformer
        objects.

    sparse_output_ : bool
        Boolean flag indicating whether the output of ``transform`` is a
        sparse matrix or a dense numpy array, which depends on the output
        of the individual transformers and the `sparse_threshold` keyword.

    output_indices_ : dict
        A dictionary from each transformer name to a slice, where the slice
        corresponds to indices in the transformed output. This is useful to
        inspect which transformer is responsible for which transformed
        feature(s).

        .. versionadded:: 1.0

    n_features_in_ : int
        Number of features seen during :term:`fit`. Only defined if the
        underlying transformers expose such an attribute when fit.

        .. versionadded:: 0.24

    See Also
    --------
    make_column_transformer : Convenience function for
        combining the outputs of multiple transformer objects applied to
        column subsets of the original feature space.
    make_column_selector : Convenience function for selecting
        columns based on datatype or the columns name with a regex pattern.

    Notes
    -----
    The order of the columns in the transformed feature matrix follows the
    order of how the columns are specified in the `transformers` list.
    Columns of the original feature matrix that are not specified are
    dropped from the resulting transformed feature matrix, unless specified
    in the `passthrough` keyword. Those columns specified with `passthrough`
    are added at the right to the output of the transformers.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.compose import ColumnTransformer
    >>> from sklearn.preprocessing import Normalizer
    >>> ct = ColumnTransformer(
    ...     [("norm1", Normalizer(norm='l1'), [0, 1]),
    ...      ("norm2", Normalizer(norm='l1'), slice(2, 4))])
    >>> X = np.array([[0., 1., 2., 2.],
    ...               [1., 1., 0., 1.]])
    >>> # Normalizer scales each row of X to unit norm. A separate scaling
    >>> # is applied for the two first and two last elements of each
    >>> # row independently.
    >>> ct.fit_transform(X)
    array([[0. , 1. , 0.5, 0.5],
           [0.5, 0.5, 0. , 1. ]])

    :class:`ColumnTransformer` can be configured with a transformer that requires
    a 1d array by setting the column to a string:

    >>> from sklearn.feature_extraction import FeatureHasher
    >>> from sklearn.preprocessing import MinMaxScaler
    >>> import pandas as pd   # doctest: +SKIP
    >>> X = pd.DataFrame({
    ...     "documents": ["First item", "second one here", "Is this the last?"],
    ...     "width": [3, 4, 5],
    ... })  # doctest: +SKIP
    >>> # "documents" is a string which configures ColumnTransformer to
    >>> # pass the documents column as a 1d array to the FeatureHasher
    >>> ct = ColumnTransformer(
    ...     [("text_preprocess", FeatureHasher(input_type="string"), "documents"),
    ...      ("num_preprocess", MinMaxScaler(), ["width"])])
    >>> X_trans = ct.fit_transform(X)  # doctest: +SKIP
    transformersdrop333333?NFT)	remaindersparse_thresholdn_jobstransformer_weightsverboseverbose_feature_names_outc                C   s.   || _ || _|| _|| _|| _|| _|| _d S N)r   r   r    r!   r"   r#   r$   )selfr   r   r    r!   r"   r#   r$    r'   G/tmp/pip-unpacked-wheel-zrfo1fqw/sklearn/compose/_column_transformer.py__init__   s    zColumnTransformer.__init__c              	   C   s6   zdd | j D W S  ttfk
r0   | j  Y S X dS )z
        Internal list of transformer only containing the name and
        transformers, dropping the columns. This is for the implementation
        of get_params via BaseComposition._get_params which expects lists
        of tuples of len 2.
        c                 S   s   g | ]\}}}||fqS r'   r'   .0nametrans_r'   r'   r(   
<listcomp>   s     3ColumnTransformer._transformers.<locals>.<listcomp>N)r   	TypeError
ValueErrorr&   r'   r'   r(   _transformers   s    zColumnTransformer._transformersc              	   C   s@   zdd t || jD | _W n ttfk
r:   || _Y nX d S )Nc                 S   s$   g | ]\\}}\}}}|||fqS r'   r'   )r+   r,   r-   r.   colr'   r'   r(   r/      s   r0   )zipr   r1   r2   )r&   valuer'   r'   r(   r4      s    
	transformc                   sF   t  j|d dd t| jt| dg D }|D ]}t||d q0| S )au  Set the output container when `"transform"` and `"fit_transform"` are called.

        Calling `set_output` will set the output of all estimators in `transformers`
        and `transformers_`.

        Parameters
        ----------
        transform : {"default", "pandas"}, default=None
            Configure output of `transform` and `fit_transform`.

            - `"default"`: Default output format of a transformer
            - `"pandas"`: DataFrame output
            - `None`: Transform configuration is unchanged

        Returns
        -------
        self : estimator instance
            Estimator instance.
        r8   c                 s   s    | ]\}}}|d kr|V  qdS )>   passthroughr   Nr'   )r+   r.   r-   r'   r'   r(   	<genexpr>  s   z/ColumnTransformer.set_output.<locals>.<genexpr>transformers_)super
set_outputr   r   getattrr   )r&   r9   r   r-   	__class__r'   r(   r>     s     
zColumnTransformer.set_outputc                 C   s   | j d|dS )a  Get parameters for this estimator.

        Returns the parameters given in the constructor as well as the
        estimators contained within the `transformers` of the
        `ColumnTransformer`.

        Parameters
        ----------
        deep : bool, default=True
            If True, will return the parameters for this estimator and
            contained subobjects that are estimators.

        Returns
        -------
        params : dict
            Parameter names mapped to their values.
        r4   )deep)Z_get_params)r&   rB   r'   r'   r(   
get_params#  s    zColumnTransformer.get_paramsc                 K   s   | j d| | S )a  Set the parameters of this estimator.

        Valid parameter keys can be listed with ``get_params()``. Note that you
        can directly set the parameters of the estimators contained in
        `transformers` of `ColumnTransformer`.

        Parameters
        ----------
        **kwargs : dict
            Estimator parameters.

        Returns
        -------
        self : ColumnTransformer
            This estimator.
        r4   )r4   )Z_set_params)r&   kwargsr'   r'   r(   
set_params7  s    zColumnTransformer.set_paramsc                 #   s
  |r2|r*fdd  fddj D }qbj }n0dd tjjD }jd rbt|jg}jpji j}td}|D ]\}}}	|r|dkrt	d	d
ddj
|d d}n|dkrq|n
t|	rq||rt|	}
j| }j| }	|
r|	d }	|||	||fV  q|dS )a  
        Generate (name, trans, column, weight) tuples.

        If fitted=True, use the fitted transformers, else use the
        user specified transformers updated with converted column names
        and potentially appended with transformer for remainder.

        c                    s$   |  j kr| ||fS |  j |  |fS r%   )_name_to_fitted_passthrough)r,   r-   columnsr3   r'   r(   replace_passthroughX  s    

z4ColumnTransformer._iter.<locals>.replace_passthroughc                    s   g | ]} | qS r'   r'   )r+   r-   )rH   r'   r(   r/   ]  s    z+ColumnTransformer._iter.<locals>.<listcomp>c                 S   s    g | ]\\}}}}|||fqS r'   r'   )r+   r,   r-   r.   columnr'   r'   r(   r/   d  s   r   r9   r:   TFz
one-to-one)accept_sparseZcheck_inversefeature_names_outdenser8   r   r   N)r<   r6   r   _columns
_remainderr   r"   getr   r   r>   _is_empty_column_selectionnpZisscalar_transformer_to_input_indicesfeature_names_in_)r&   fittedreplace_stringscolumn_as_stringsr   Z
get_weightZoutput_configr,   r-   rG   Zcolumns_is_scalarindicesr'   )rH   r&   r(   _iterK  sF    	





zColumnTransformer._iterc                 C   sn   | j s
d S t| j  \}}}| | |D ]@}|dkr6q(t|dsJt|drTt|ds(td|t|f q(d S )Nr   r:   fitfit_transformr9   zxAll estimators should implement fit and transform, or can be 'drop' or 'passthrough' specifiers. '%s' (type %s) doesn't.)r   r6   Z_validate_nameshasattrr1   type)r&   namesr   r.   tr'   r'   r(   _validate_transformers  s     
 
z(ColumnTransformer._validate_transformersc                 C   sR   g }i }| j D ]2\}}}t|r(||}|| t||||< q|| _|| _dS )z:
        Converts callable column specifications.
        N)r   callableappendr   rM   rR   )r&   XZall_columnsZtransformer_to_input_indicesr,   r.   rG   r'   r'   r(   _validate_column_callables  s    
z,ColumnTransformer._validate_column_callablesc                 C   s   t | jdst | jdo"t | jd}| jdkr@|s@td| j |jd | _tt| j  }t	tt
| j| }d| j|f| _|| jd< dS )	zm
        Validates ``remainder`` and defines ``_remainder`` targeting
        the remaining columns.
        rZ   r[   r9   rY   zeThe remainder keyword needs to be one of 'drop', 'passthrough', or estimator. '%s' was passed instead   r   N)r\   r   r2   shapeZ_n_featuressetr   rR   valuessortedrangerN   )r&   rc   Zis_transformercols	remainingr'   r'   r(   _validate_remainder  s    
z%ColumnTransformer._validate_remainderc                 C   s   t f dd | jD S )zAccess the fitted transformer by name.

        Read-only attribute to access any transformer by given name.
        Keys are transformer names and values are the fitted transformer
        objects.
        c                 S   s   i | ]\}}}||qS r'   r'   r*   r'   r'   r(   
<dictcomp>  s      z9ColumnTransformer.named_transformers_.<locals>.<dictcomp>)r   r<   r3   r'   r'   r(   named_transformers_  s    	z%ColumnTransformer.named_transformers_c                 C   sb   | j | }|| }|dks"t|r&dS |dkr2|S t|dsXtd| dt|j d||S )zGets feature names of transformer.

        Used in conjunction with self._iter(fitted=True) in get_feature_names_out.
        r   Nr:   get_feature_names_outzTransformer z (type z)) does not provide get_feature_names_out.)rR   rP   r\   AttributeErrorr]   __name__rp   )r&   r,   r-   rI   Zfeature_names_inZcolumn_indicesr^   r'   r'   r(   %_get_feature_name_out_for_transformer  s    

z7ColumnTransformer._get_feature_name_out_for_transformerc                 C   st   t |  t| |}g }| jddD ]4\}}}}| ||||}|dkrHq"|||f q"|sjtjg tdS | |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.
        T)rT   Ndtype)	r   r   rX   rs   rb   rQ   arrayobject!_add_prefix_for_feature_names_out)r&   Zinput_features"transformer_with_feature_names_outr,   r-   rI   r.   rK   r'   r'   r(   rp     s$    
   z'ColumnTransformer.get_feature_names_outc                 C   s   | j r,ttdd |D }tj|tdS ttdd |D }dd |dD }|	  |rt
|dkrt|dd	 dd
 d }nt|}td| dtdd |D S )a  Add prefix for feature names out that includes the transformer names.

        Parameters
        ----------
        transformer_with_feature_names_out : list of tuples of (str, array-like of str)
            The tuple consistent of the transformer's name and its feature names out.

        Returns
        -------
        feature_names_out : ndarray of shape (n_features,), dtype=str
            Transformed feature names.
        c                 3   s$   | ]\ } fd d|D V  qdS )c                 3   s   | ]}  d | V  qdS )__Nr'   )r+   ir,   r'   r(   r;     s     zPColumnTransformer._add_prefix_for_feature_names_out.<locals>.<genexpr>.<genexpr>Nr'   )r+   rK   r'   r|   r(   r;     s   zFColumnTransformer._add_prefix_for_feature_names_out.<locals>.<genexpr>rt   c                 s   s   | ]\}}|V  qd S r%   r'   )r+   r.   sr'   r'   r(   r;   (  s     c                 S   s   g | ]\}}|d kr|qS )re   r'   )r+   r,   countr'   r'   r(   r/   *  s     zGColumnTransformer._add_prefix_for_feature_names_out.<locals>.<listcomp>   N   z, ...]zOutput feature names: z[ are not unique. Please set verbose_feature_names_out=True to add prefixes to feature namesc                 S   s   g | ]\}}|qS r'   r'   )r+   r.   r,   r'   r'   r(   r/   ;  s     )r$   listr   from_iterablerQ   Zasarrayrw   r   most_commonsortlenstrr2   Zconcatenate)r&   ry   r^   Zfeature_names_countZtop_6_overlapZ
names_reprr'   r'   r(   rx     s0    

z3ColumnTransformer._add_prefix_for_feature_names_outc           
      C   s   t |}g }i | _|  D ]`\}}}}|dkr4d}n6|dkrTt|}	d}|	| j|< nt|rb|}nt|}||||f qt|rt|| _d S )Nr   r:   )	iterrF   rX   nextrP   rb   r   AssertionErrorr<   )
r&   r   Zfitted_transformersr<   r,   oldrI   r.   r-   Zfunc_transformerr'   r'   r(   _update_fitted_transformers>  s     z-ColumnTransformer._update_fitted_transformersc                 C   sN   dd | j dddD }t||D ]&\}}t|dddks"td|q"d	S )
z
        Ensure that the output of each transformer is 2D. Otherwise
        hstack can raise an error or produce incorrect results.
        c                 S   s   g | ]\}}}}|qS r'   r'   )r+   r,   r.   r'   r'   r(   r/   _  s   
 z6ColumnTransformer._validate_output.<locals>.<listcomp>TrT   rU   ndimr   r   z\The output of the '{0}' transformer should be 2D (scipy matrix, array, or pandas DataFrame).N)rX   r6   r?   r2   format)r&   resultr^   Xsr,   r'   r'   r(   _validate_outputZ  s    z"ColumnTransformer._validate_outputc                 C   s   d}i | _ t| jdddD ]:\}\}}}}|| jd }t||| | j |< ||7 }qdd | jD dg }|D ]}|| j krrtdd| j |< qrdS )	zA
        Record which transformer produced which column.
        r   Tr   re   c                 S   s   g | ]}|d  qS r   r'   r+   r_   r'   r'   r(   r/   z  s     z<ColumnTransformer._record_output_indices.<locals>.<listcomp>r   N)Zoutput_indices_	enumeraterX   rf   slicer   )r&   r   idxZtransformer_idxr,   r.   Z	n_columns	all_namesr'   r'   r(   _record_output_indicesi  s    

z(ColumnTransformer._record_output_indicesc                 C   s   | j s
d S d|||f S )Nz(%d of %d) Processing %s)r#   )r&   r,   r   totalr'   r'   r(   _log_message  s    zColumnTransformer._log_messagec              
      s   t jd|dz0tjd fddtdD W S  tk
r } zdt|krntt|n W 5 d}~X Y nX dS )	z
        Private function to fit and/or transform on demand.

        Return value (transformers and/or transformed X data) depends
        on the passed function.
        ``fitted=True`` ensures the fitted transformers are used.
        T)rT   rU   rV   )r!   c                 3   sV   | ]N\}\}}}}t s$t|n|t |d d|d||tdV  qdS )re   Zaxisr   )Ztransformerrc   yweightZmessage_clsnamemessageN)r   r   r   r   r   )r+   r   r,   r-   rI   r   rc   rT   funcr&   r   r   r'   r(   r;     s   	z3ColumnTransformer._fit_transform.<locals>.<genexpr>re   z'Expected 2D array, got 1D array insteadN)r   rX   r   r!   r   r2   r   _ERR_MSG_1DCOLUMN)r&   rc   r   r   rT   rV   er'   r   r(   _fit_transform  s      	
z ColumnTransformer._fit_transformc                 C   s   | j ||d | S )a  Fit all transformers using X.

        Parameters
        ----------
        X : {array-like, dataframe} of shape (n_samples, n_features)
            Input data, of which specified subsets are used to fit the
            transformers.

        y : array-like of shape (n_samples,...), default=None
            Targets for supervised learning.

        Returns
        -------
        self : ColumnTransformer
            This estimator.
        )r   )r[   )r&   rc   r   r'   r'   r(   rZ     s    zColumnTransformer.fitc           	      C   s   | j |dd t|}| j|dd |   | | | | | ||t}|sp| g  t	
|jd dfS t| \}}tdd |D rtdd |D }tdd |D }|| }|| jk | _nd| _| | | | | | | t|S )	a  Fit all transformers, transform the data and concatenate results.

        Parameters
        ----------
        X : {array-like, dataframe} of shape (n_samples, n_features)
            Input data, of which specified subsets are used to fit the
            transformers.

        y : array-like of shape (n_samples,), default=None
            Targets for supervised learning.

        Returns
        -------
        X_t : {array-like, sparse matrix} of                 shape (n_samples, sum_n_components)
            Horizontally stacked results of transformers. sum_n_components is the
            sum of n_components (output dimension) over transformers. If
            any result is a sparse matrix, everything will be converted to
            sparse matrices.
        Tresetr   c                 s   s   | ]}t |V  qd S r%   )r   issparser+   rc   r'   r'   r(   r;     s     z2ColumnTransformer.fit_transform.<locals>.<genexpr>c                 s   s$   | ]}t |r|jn|jV  qd S r%   )r   r   nnzsizer   r'   r'   r(   r;     s     c                 s   s2   | ]*}t |r$|jd  |jd  n|jV  qdS )r   re   N)r   r   rf   r   r   r'   r'   r(   r;     s    F)Z_check_feature_names_check_X_check_n_featuresr`   rd   rm   r   r	   r   rQ   zerosrf   r6   anysumr    sparse_output_r   r   _hstackr   )	r&   rc   r   r   r   r   r   r   Zdensityr'   r'   r(   r[     s.    





zColumnTransformer.fit_transformc                    s   t  t|}tdo"t|d}|rj  fddj D }tt| }tfdd|D }|t|j }|rt	d| nj
|dd	 j|d
td|d}| |st|jd dfS t|S )al  Transform X separately by each transformer, concatenate results.

        Parameters
        ----------
        X : {array-like, dataframe} of shape (n_samples, n_features)
            The data to be transformed by subset.

        Returns
        -------
        X_t : {array-like, sparse matrix} of                 shape (n_samples, sum_n_components)
            Horizontally stacked results of transformers. sum_n_components is the
            sum of n_components (output dimension) over transformers. If
            any result is a sparse matrix, everything will be converted to
            sparse matrices.
        rS   rG   c                    s6   g | ].\}}| krt  | tr | d kr|qS )r   
isinstancer   )r+   r,   ind)named_transformersr'   r(   r/     s
   z/ColumnTransformer.transform.<locals>.<listcomp>c                 3   s   | ]} j | V  qd S r%   )rS   )r+   r   r3   r'   r(   r;     s     z.ColumnTransformer.transform.<locals>.<genexpr>zcolumns are missing: Fr   NT)rT   rV   r   )r   r   r\   ro   rR   itemsrg   r   rG   r2   r   r   r
   r   rQ   r   rf   r   r   )r&   rc   Z%fit_dataframe_and_transform_dataframeZnon_dropped_indicesZall_indicesr   Zdiffr   r'   )r   r&   r(   r9     s<     

zColumnTransformer.transformc           
   
   C   s   | j rTzdd |D }W n, tk
rD } ztd|W 5 d}~X Y nX t| S dd |D }td| }|d dkrtd	d
 |D rtd}|j|dd}| j	s|S dd | j
dddD }dd |D }| tt||}	|	|_|S t|S dS )a  Stacks Xs horizontally.

        This allows subclasses to control the stacking behavior, while reusing
        everything else from ColumnTransformer.

        Parameters
        ----------
        Xs : list of {array-like, sparse matrix, dataframe}
        c                 S   s   g | ]}t |d ddqS )TF)rJ   force_all_finite)r   r   r'   r'   r(   r/   >  s   z-ColumnTransformer._hstack.<locals>.<listcomp>zQFor a sparse output, all columns should be a numeric or convertible to a numeric.Nc                 S   s"   g | ]}t |r| n|qS r'   )r   r   Ztoarray)r+   fr'   r'   r(   r/   J  s     r9   rL   Zpandasc                 s   s   | ]}t |d V  qdS )ilocN)r\   r   r'   r'   r(   r;   L  s     z,ColumnTransformer._hstack.<locals>.<genexpr>re   r   c                 S   s   g | ]}|d  qS r   r'   r   r'   r'   r(   r/   X  s    Tr   c                 S   s   g | ]
}|j qS r'   )rG   r   r'   r'   r(   r/   [  s     )r   r2   r   ZhstackZtocsrr   allr   concatr$   rX   rx   r   r6   rG   rQ   )
r&   r   Zconverted_Xsr   configpdoutputZtransformer_namesZfeature_names_outsZ	names_outr'   r'   r(   r   /  s:    


zColumnTransformer._hstackc                 C   s   t | jtr| jdkr| j}npt| drx| jd }t| dr`|r`tdd |D s`| j|  }t	| jd| j|fg}nt	| jd| jdfg}t
| \}}}td	|||d
S )Nr   rN   r   rS   c                 s   s   | ]}t |tV  qd S r%   r   r+   r5   r'   r'   r(   r;   l  s     z6ColumnTransformer._sk_visual_block_.<locals>.<genexpr>r    parallel)r^   name_details)r   r   r   r   r\   rN   r   rS   tolistr   r6   r   )r&   r   Zremainder_columnsr^   r   r'   r'   r(   _sk_visual_block_d  s.    

    z#ColumnTransformer._sk_visual_block_)T)FFF)N)FF)N)N)rr   
__module____qualname____doc__Z_required_parametersr)   propertyr4   setterr>   rC   rE   rX   r`   rd   rm   ro   rs   rp   rx   r   r   r   r   r   rZ   r[   r9   r   r   __classcell__r'   r'   r@   r(   r   '   sH    /

	!

?


)0


8>5c                 C   s&   t | dst| r| S t| dtdS )z@Use check_array only on lists and other non-array-likes / sparseZ	__array__z	allow-nan)r   ru   )r\   r   r   r   rw   )rc   r'   r'   r(   r   {  s    r   c                 C   s^   t | dr$t| jtjr$|   S t | drVt| dkpTtdd | D oTt|  S dS dS )zd
    Return True if the column selection is empty (empty list or all-False
    boolean array).

    ru   __len__r   c                 s   s   | ]}t |tV  qd S r%   )r   boolr   r'   r'   r(   r;     s     z-_is_empty_column_selection.<locals>.<genexpr>FN)r\   rQ   Z
issubdtyperu   Zbool_r   r   r   )rI   r'   r'   r(   rP     s    

rP   c                 C   s0   t |  \}}t t| \}}tt |||}|S )z;
    Construct (name, trans, column) tuples from list

    )r6   r   r   )Z
estimatorsr   rG   r^   r.   transformer_listr'   r'   r(   _get_transformer_list  s    r   r   r   FT)r   r    r!   r#   r$   c                 G   s   t |}t||| |||dS )a8  Construct a ColumnTransformer from the given transformers.

    This is a shorthand for the ColumnTransformer constructor; it does not
    require, and does not permit, naming the transformers. Instead, they will
    be given names automatically based on their types. It also does not allow
    weighting with ``transformer_weights``.

    Read more in the :ref:`User Guide <make_column_transformer>`.

    Parameters
    ----------
    *transformers : tuples
        Tuples of the form (transformer, columns) specifying the
        transformer objects to be applied to subsets of the data.

        transformer : {'drop', 'passthrough'} or estimator
            Estimator must support :term:`fit` and :term:`transform`.
            Special-cased strings 'drop' and 'passthrough' are accepted as
            well, to indicate to drop the columns or to pass them through
            untransformed, respectively.
        columns : str,  array-like of str, int, array-like of int, slice,                 array-like of bool or callable
            Indexes the data on its second axis. Integers are interpreted as
            positional columns, while strings can reference DataFrame columns
            by name. A scalar string or int should be used where
            ``transformer`` expects X to be a 1d array-like (vector),
            otherwise a 2d array will be passed to the transformer.
            A callable is passed the input data `X` and can return any of the
            above. To select multiple columns by name or dtype, you can use
            :obj:`make_column_selector`.

    remainder : {'drop', 'passthrough'} or estimator, default='drop'
        By default, only the specified columns in `transformers` are
        transformed and combined in the output, and the non-specified
        columns are dropped. (default of ``'drop'``).
        By specifying ``remainder='passthrough'``, all remaining columns that
        were not specified in `transformers` will be automatically passed
        through. This subset of columns is concatenated with the output of
        the transformers.
        By setting ``remainder`` to be an estimator, the remaining
        non-specified columns will use the ``remainder`` estimator. The
        estimator must support :term:`fit` and :term:`transform`.

    sparse_threshold : float, default=0.3
        If the transformed output consists of a mix of sparse and dense data,
        it will be stacked as a sparse matrix if the density is lower than this
        value. Use ``sparse_threshold=0`` to always return dense.
        When the transformed output consists of all sparse or all dense data,
        the stacked result will be sparse or dense, respectively, and this
        keyword will be ignored.

    n_jobs : int, default=None
        Number of jobs to run in parallel.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    verbose : bool, default=False
        If True, the time elapsed while fitting each transformer will be
        printed as it is completed.

    verbose_feature_names_out : bool, default=True
        If True, :meth:`get_feature_names_out` will prefix all feature names
        with the name of the transformer that generated that feature.
        If False, :meth:`get_feature_names_out` will not prefix any feature
        names and will error if feature names are not unique.

        .. versionadded:: 1.0

    Returns
    -------
    ct : ColumnTransformer
        Returns a :class:`ColumnTransformer` object.

    See Also
    --------
    ColumnTransformer : Class that allows combining the
        outputs of multiple transformer objects used on column subsets
        of the data into a single feature space.

    Examples
    --------
    >>> from sklearn.preprocessing import StandardScaler, OneHotEncoder
    >>> from sklearn.compose import make_column_transformer
    >>> make_column_transformer(
    ...     (StandardScaler(), ['numerical_column']),
    ...     (OneHotEncoder(), ['categorical_column']))
    ColumnTransformer(transformers=[('standardscaler', StandardScaler(...),
                                     ['numerical_column']),
                                    ('onehotencoder', OneHotEncoder(...),
                                     ['categorical_column'])])
    )r!   r   r    r#   r$   )r   r   )r   r    r!   r#   r$   r   r   r'   r'   r(   r     s    fc                   @   s*   e Zd ZdZddddddZdd ZdS )	r   a  Create a callable to select columns to be used with
    :class:`ColumnTransformer`.

    :func:`make_column_selector` can select columns based on datatype or the
    columns name with a regex. When using multiple selection criteria, **all**
    criteria must match for a column to be selected.

    Parameters
    ----------
    pattern : str, default=None
        Name of columns containing this regex pattern will be included. If
        None, column selection will not be selected based on pattern.

    dtype_include : column dtype or list of column dtypes, default=None
        A selection of dtypes to include. For more details, see
        :meth:`pandas.DataFrame.select_dtypes`.

    dtype_exclude : column dtype or list of column dtypes, default=None
        A selection of dtypes to exclude. For more details, see
        :meth:`pandas.DataFrame.select_dtypes`.

    Returns
    -------
    selector : callable
        Callable for column selection to be used by a
        :class:`ColumnTransformer`.

    See Also
    --------
    ColumnTransformer : Class that allows combining the
        outputs of multiple transformer objects used on column subsets
        of the data into a single feature space.

    Examples
    --------
    >>> from sklearn.preprocessing import StandardScaler, OneHotEncoder
    >>> from sklearn.compose import make_column_transformer
    >>> from sklearn.compose import make_column_selector
    >>> import numpy as np
    >>> import pandas as pd  # doctest: +SKIP
    >>> X = pd.DataFrame({'city': ['London', 'London', 'Paris', 'Sallisaw'],
    ...                   'rating': [5, 3, 4, 5]})  # doctest: +SKIP
    >>> ct = make_column_transformer(
    ...       (StandardScaler(),
    ...        make_column_selector(dtype_include=np.number)),  # rating
    ...       (OneHotEncoder(),
    ...        make_column_selector(dtype_include=object)))  # city
    >>> ct.fit_transform(X)  # doctest: +SKIP
    array([[ 0.90453403,  1.        ,  0.        ,  0.        ],
           [-1.50755672,  1.        ,  0.        ,  0.        ],
           [-0.30151134,  0.        ,  1.        ,  0.        ],
           [ 0.90453403,  0.        ,  0.        ,  1.        ]])
    N)dtype_includedtype_excludec                C   s   || _ || _|| _d S r%   )patternr   r   )r&   r   r   r   r'   r'   r(   r)   H  s    zmake_column_selector.__init__c                 C   st   t |dstd|jdd }| jdk	s4| jdk	rF|j| j| jd}|j}| jdk	rl||jj	| jdd }|
 S )zCallable for column selection to be used by a
        :class:`ColumnTransformer`.

        Parameters
        ----------
        df : dataframe of shape (n_features, n_samples)
            DataFrame to select columns from.
        r   z=make_column_selector can only be applied to pandas dataframesNre   )includeexcludeT)regex)r\   r2   r   r   r   Zselect_dtypesrG   r   r   containsr   )r&   ZdfZdf_rowrk   r'   r'   r(   __call__M  s    	
 
zmake_column_selector.__call__)N)rr   r   r   r   r)   r   r'   r'   r'   r(   r     s   6)-r   	itertoolsr   collectionsr   ZnumpyrQ   Zscipyr   baser   r   Zutils._estimator_html_reprr   Zpipeliner	   r
   r   Zpreprocessingr   utilsr   r   r   Zutils._set_outputr   r   r   Zutils.metaestimatorsr   Zutils.validationr   r   r   Zutils.parallelr   r   __all__r   r   r   rP   r   r   r   r'   r'   r'   r(   <module>   sH   
      Zq