U
    f/eY                  
   @  s  d Z ddlmZ ddlmZ ddlmZmZmZm	Z	m
Z
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 dd
lmZ ddlmZmZ ddlm  mZ  ddl!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z' ddl(m  m)  m*Z+ ddl,m-Z- erddl.m/Z/m0Z0 ddl1m2Z2 ed*ddddddddddZ3ed+ddddddddddZ3eddgdd,dddddddd dZ3G d!d" d"Z4d#d$d%d&Z5d-d'd$d(d)Z6dS ).z
Concat routines.
    )annotations)abc)TYPE_CHECKINGHashableIterableMappingcastoverloadN)FrameOrSeriesUnion)cache_readonlydeprecate_nonkeyword_arguments)concat_compat)ABCDataFrame	ABCSeries)isna)factorize_from_iterablefactorize_from_iterables)Index
MultiIndexall_indexes_sameensure_indexget_objs_combined_axisget_unanimous_names)concatenate_managers)	DataFrameSeries)NDFrameouterFTz2Iterable[DataFrame] | Mapping[Hashable, DataFrame]strboolr   )objsjoinignore_indexverify_integritysortcopyreturnc
           
      C  s   d S N 
r    axisr!   r"   keyslevelsnamesr#   r$   r%   r(   r(   >/tmp/pip-unpacked-wheel-tiezk1ph/pandas/core/reshape/concat.pyconcat:   s    r/   .Iterable[NDFrame] | Mapping[Hashable, NDFrame]r
   c
           
      C  s   d S r'   r(   r)   r(   r(   r.   r/   J   s    r    )versionZallowed_args)r    r"   r#   r$   r%   r&   c
                 C  s$   t | ||||||||	|d
}
|
 S )a  
    Concatenate pandas objects along a particular axis with optional set logic
    along the other axes.

    Can also add a layer of hierarchical indexing on the concatenation axis,
    which may be useful if the labels are the same (or overlapping) on
    the passed axis number.

    Parameters
    ----------
    objs : a sequence or mapping of Series or DataFrame objects
        If a mapping is passed, the sorted keys will be used as the `keys`
        argument, unless it is passed, in which case the values will be
        selected (see below). Any None objects will be dropped silently unless
        they are all None in which case a ValueError will be raised.
    axis : {0/'index', 1/'columns'}, default 0
        The axis to concatenate along.
    join : {'inner', 'outer'}, default 'outer'
        How to handle indexes on other axis (or axes).
    ignore_index : bool, default False
        If True, do not use the index values along the concatenation axis. The
        resulting axis will be labeled 0, ..., n - 1. This is useful if you are
        concatenating objects where the concatenation axis does not have
        meaningful indexing information. Note the index values on the other
        axes are still respected in the join.
    keys : sequence, default None
        If multiple levels passed, should contain tuples. Construct
        hierarchical index using the passed keys as the outermost level.
    levels : list of sequences, default None
        Specific levels (unique values) to use for constructing a
        MultiIndex. Otherwise they will be inferred from the keys.
    names : list, default None
        Names for the levels in the resulting hierarchical index.
    verify_integrity : bool, default False
        Check whether the new concatenated axis contains duplicates. This can
        be very expensive relative to the actual data concatenation.
    sort : bool, default False
        Sort non-concatenation axis if it is not already aligned when `join`
        is 'outer'.
        This has no effect when ``join='inner'``, which already preserves
        the order of the non-concatenation axis.

        .. versionchanged:: 1.0.0

           Changed to not sort by default.

    copy : bool, default True
        If False, do not copy data unnecessarily.

    Returns
    -------
    object, type of objs
        When concatenating all ``Series`` along the index (axis=0), a
        ``Series`` is returned. When ``objs`` contains at least one
        ``DataFrame``, a ``DataFrame`` is returned. When concatenating along
        the columns (axis=1), a ``DataFrame`` is returned.

    See Also
    --------
    Series.append : Concatenate Series.
    DataFrame.append : Concatenate DataFrames.
    DataFrame.join : Join DataFrames using indexes.
    DataFrame.merge : Merge DataFrames by indexes or columns.

    Notes
    -----
    The keys, levels, and names arguments are all optional.

    A walkthrough of how this method fits in with other tools for combining
    pandas objects can be found `here
    <https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html>`__.

    Examples
    --------
    Combine two ``Series``.

    >>> s1 = pd.Series(['a', 'b'])
    >>> s2 = pd.Series(['c', 'd'])
    >>> pd.concat([s1, s2])
    0    a
    1    b
    0    c
    1    d
    dtype: object

    Clear the existing index and reset it in the result
    by setting the ``ignore_index`` option to ``True``.

    >>> pd.concat([s1, s2], ignore_index=True)
    0    a
    1    b
    2    c
    3    d
    dtype: object

    Add a hierarchical index at the outermost level of
    the data with the ``keys`` option.

    >>> pd.concat([s1, s2], keys=['s1', 's2'])
    s1  0    a
        1    b
    s2  0    c
        1    d
    dtype: object

    Label the index keys you create with the ``names`` option.

    >>> pd.concat([s1, s2], keys=['s1', 's2'],
    ...           names=['Series name', 'Row ID'])
    Series name  Row ID
    s1           0         a
                 1         b
    s2           0         c
                 1         d
    dtype: object

    Combine two ``DataFrame`` objects with identical columns.

    >>> df1 = pd.DataFrame([['a', 1], ['b', 2]],
    ...                    columns=['letter', 'number'])
    >>> df1
      letter  number
    0      a       1
    1      b       2
    >>> df2 = pd.DataFrame([['c', 3], ['d', 4]],
    ...                    columns=['letter', 'number'])
    >>> df2
      letter  number
    0      c       3
    1      d       4
    >>> pd.concat([df1, df2])
      letter  number
    0      a       1
    1      b       2
    0      c       3
    1      d       4

    Combine ``DataFrame`` objects with overlapping columns
    and return everything. Columns outside the intersection will
    be filled with ``NaN`` values.

    >>> df3 = pd.DataFrame([['c', 3, 'cat'], ['d', 4, 'dog']],
    ...                    columns=['letter', 'number', 'animal'])
    >>> df3
      letter  number animal
    0      c       3    cat
    1      d       4    dog
    >>> pd.concat([df1, df3], sort=False)
      letter  number animal
    0      a       1    NaN
    1      b       2    NaN
    0      c       3    cat
    1      d       4    dog

    Combine ``DataFrame`` objects with overlapping columns
    and return only those that are shared by passing ``inner`` to
    the ``join`` keyword argument.

    >>> pd.concat([df1, df3], join="inner")
      letter  number
    0      a       1
    1      b       2
    0      c       3
    1      d       4

    Combine ``DataFrame`` objects horizontally along the x axis by
    passing in ``axis=1``.

    >>> df4 = pd.DataFrame([['bird', 'polly'], ['monkey', 'george']],
    ...                    columns=['animal', 'name'])
    >>> pd.concat([df1, df4], axis=1)
      letter  number  animal    name
    0      a       1    bird   polly
    1      b       2  monkey  george

    Prevent the result from including duplicate index values with the
    ``verify_integrity`` option.

    >>> df5 = pd.DataFrame([1], index=['a'])
    >>> df5
       0
    a  1
    >>> df6 = pd.DataFrame([2], index=['a'])
    >>> df6
       0
    a  2
    >>> pd.concat([df5, df6], verify_integrity=True)
    Traceback (most recent call last):
        ...
    ValueError: Indexes have overlapping values: ['a']
    )	r*   r"   r!   r+   r,   r-   r#   r%   r$   )_Concatenator
get_result)r    r*   r!   r"   r+   r,   r-   r#   r$   r%   opr(   r(   r.   r/   Z   s     Mc                	   @  s|   e Zd ZdZdddd	d	d	d
ddZdd ZddddZddddZdddddZe	ddddZ
ddddZdS ) r2   zB
    Orchestrates a concatenation operation for BlockManagers
    r   r   NFTr0   r   r   )r    r!   r"   r#   r%   c                   s  t  tttfr&tdt j d|dkr6d| _n|dkrFd| _ntdt  t	j
r|d krnt  } fdd	|D  nt  t d
krtd|d krttj   nxg }g }t| D ]&\}}|d krq|| || q| t |trt|j||jd}nt|dd }t||d}t d
krDtdt } D ]:}t |ttfszdt| d}t|||j qNd }t|dkrt|} D ]*}|j|krt|jr|} q qnJdd	  D }t|r |d kr |d kr |d kr | js |  d
 }|d kr2 d
 } | _t |trR|j |}n
| |}t |t| _!| j!rz|"|}t |t| _#d
|  kr|jksn t$d|j d| t|dkrvd
}|j}g | j | _  D ]}|j}||krnn||d krtdnVt|dd }|s,|d kr8|}|d7 }| j!rN|dkrNd
}t%d|}|&||i}| j| q|| _'| j!rd| j' nd
| _(|| _|pt|dd | _|| _)|
| _*|| _+|| _,|	| _-| . | _/d S )NzTfirst argument must be an iterable of pandas objects, you passed an object of type ""r   FinnerTz?Only can inner (intersect) or outer (union) join the other axisc                   s   g | ]} | qS r(   r(   ).0kr    r(   r.   
<listcomp>Z  s     z*_Concatenator.__init__.<locals>.<listcomp>r   zNo objects to concatenate)r-   name)r;   zAll objects passed were Nonez#cannot concatenate object of type 'z+'; only Series and DataFrame objs are valid   c                 S  s(   g | ] }t |jd ks t|tr|qS )r   )sumshape
isinstancer   )r7   objr(   r(   r.   r:     s     
 zaxis must be between 0 and z, input was z>cannot concatenate unaligned mixed dimensional NDFrame objectsr
   r-   )0r?   r   r   r   	TypeErrortype__name__	intersect
ValueErrorr   r   listr+   lencomZnot_nonezipappendr   from_tuplesr-   getattrr   setaddndimmaxnpr=   r>   r    _constructor_expanddimZ_get_axis_numberZ	_is_frame_get_block_manager_axis
_is_seriesAssertionErrorr   _constructorbm_axisr*   r,   r$   r"   r#   r%   _get_new_axesnew_axes)selfr    r*   r!   r+   r,   r-   r"   r#   r%   r$   Z
clean_keysZ
clean_objsr8   vr;   Zndimsr@   msgsampleZmax_ndimZnon_emptiesZcurrent_columnrO   r(   r9   r.   __init__;  s    






z_Concatenator.__init__c                 C  s~  | j rtd| jd }| jdkrtt| j}|j}dd | jD }t|dd}||| jd ||j	d}|j
| ddS tttt| j| j}|j}| j\}}	|||d	}
|	|
_|
j
| ddS ntd
| jd }g }| jD ]`}i }t| jD ]<\}}|| jkrq|jd|  }||s||||< q||j|f qt|| j| j| jd}| jsb|  |j}||j
| ddS d S )Nr   r   c                 S  s   g | ]
}|j qS r(   )Z_values)r7   Zserr(   r(   r.   r:     s     z,_Concatenator.get_result.<locals>.<listcomp>)r*   )indexr;   dtyper/   )methodr_   r   r<   )concat_axisr%   )rT   r   r    rW   rH   Zconsensus_name_attrrV   r   rY   r`   Z__finalize__dictrI   rangerG   rR   columns	enumerateaxesequalsget_indexerrJ   Z_mgrr   r%   Z_consolidate_inplace)rZ   r]   r;   ZconsZarrsresresultdatar_   rf   ZdfZmgrs_indexersr@   ZindexersZaxZ
new_labelsZ
obj_labelsZnew_datar(   r(   r.   r3     sH    



   z_Concatenator.get_resultintr&   c                 C  s$   | j r| jdkrdS | jd jS d S )Nr<      r   )rT   rW   r    rO   rZ   r(   r(   r.   _get_result_dim  s    z_Concatenator._get_result_dimzlist[Index]c                   s      } fddt|D S )Nc                   s&   g | ]}| j kr jn |qS r(   )rW   _get_concat_axis_get_comb_axisr7   irq   r(   r.   r:   %  s   z/_Concatenator._get_new_axes.<locals>.<listcomp>)rr   re   )rZ   rO   r(   rq   r.   rX   #  s    
z_Concatenator._get_new_axesr   )rv   r&   c                 C  s*   | j d |}t| j || j| j| jdS )Nr   )r*   rD   r$   r%   )r    rS   r   rD   r$   r%   )rZ   rv   Z	data_axisr(   r(   r.   rt   *  s    z_Concatenator._get_comb_axisc           	        s^   j r jdkr"dd  jD }nʈ jr<tt j}|S  jdkrdgt j }d}d}t jD ]R\}}t	|t
stdt|j d|jdk	r|j||< d}qh|||< |d	7 }qh|rt|S tt jS nt j jS n fd
d jD } jr&ttdd |D }|S  jdkr<t|}nt| j j j} | |S )zC
        Return index to be used along concatenation axis.
        r   c                 S  s   g | ]
}|j qS r(   rb   r7   xr(   r(   r.   r:   ;  s     z2_Concatenator._get_concat_axis.<locals>.<listcomp>NFz6Cannot concatenate type 'Series' with object of type ''Tr<   c                   s   g | ]}|j  j qS r(   )rh   r*   rw   rq   r(   r.   r:   V  s     c                 s  s   | ]}t |V  qd S r'   )rG   ru   r(   r(   r.   	<genexpr>Y  s     z1_Concatenator._get_concat_axis.<locals>.<genexpr>)rT   rW   r    r"   ibaseZdefault_indexrG   r+   rg   r?   r   rA   rB   rC   r;   r   r   Z	set_namesr-   r=   _concat_indexes_make_concat_multiindexr,   _maybe_check_integrity)	rZ   indexesidxr-   numZ	has_namesrv   rx   rc   r(   rq   r.   rs   4  sL    






   
z_Concatenator._get_concat_axis)concat_indexc                 C  s.   | j r*|js*||   }td| d S )Nz!Indexes have overlapping values: )r#   Z	is_uniqueZ
duplicateduniquerE   )rZ   r   overlapr(   r(   r.   r~   g  s    z$_Concatenator._maybe_check_integrity)	r   r   NNNFFTF)rC   
__module____qualname____doc__r^   r3   rr   rX   rt   r   rs   r~   r(   r(   r(   r.   r2   6  s&             '<
2r2   r   ro   c                 C  s   | d  | dd  S )Nr   r<   )rJ   )r   r(   r(   r.   r|   n  s    r|   r   c              	     s  |d krt |d ts*|d k	rrt|dkrrtt| }|d krLd gt| }|d krbt|\}}qdd |D }n6|g}|d krd g}|d krt|g}ndd |D }t| sg }t||D ]\}}g }	t|| D ]f\}
}t|t|
@ ||
kB }|	 st
d|
 d| t|d d }|	t|t| q|t|	 qt| }t |tr~||j ||j n t|\}}|| || t|t|krt|}n4tdd	 | D dkstd
t|tt|   }t|||ddS | d }t|}t|  t|}t|}g }t||D ]R\}}t|}||}|dk}|	 rrt
d|| |t|| q4t |tr||j | fdd|jD  n"|| |tt|  t|t|k r||j t|||ddS )Nr   r<   c                 S  s   g | ]}t |qS r(   r   rw   r(   r(   r.   r:   ~  s     z+_make_concat_multiindex.<locals>.<listcomp>c                 S  s   g | ]}t |qS r(   r   rw   r(   r(   r.   r:     s     zKey z not in level c                 S  s   h | ]
}|j qS r(   )Znlevels)r7   r   r(   r(   r.   	<setcomp>  s     z*_make_concat_multiindex.<locals>.<setcomp>z@Cannot concat indices that do not have the same number of levelsF)r,   codesr-   r#   z"Values not found in passed level: c                   s   g | ]}t | qS r(   )rQ   tile)r7   ZlabZkpiecesr(   r.   r:     s     )r?   tuplerG   rF   rI   r   r   r   r   anyrE   rQ   ZnonzerorJ   repeatZconcatenater|   r   extendr,   r   r   rU   r   rj   r   Zaranger-   )r   r+   r,   r-   Zzipped_Z
codes_listZhlevellevelZ	to_concatkeyr_   maskrv   r   r   
categoriesZ	new_indexnZ	new_namesZ
new_levelsZ	new_codesZmappedr(   r   r.   r}   r  s    





   


   r}   )	r   r   FNNNFFT)	r   r   FNNNFFT)	r   r   FNNNFFT)NN)7r   
__future__r   collectionsr   typingr   r   r   r   r   r	   ZnumpyrQ   Zpandas._typingr
   Zpandas.util._decoratorsr   r   Zpandas.core.dtypes.concatr   Zpandas.core.dtypes.genericr   r   Zpandas.core.dtypes.missingr   Zpandas.core.arrays.categoricalr   r   Zpandas.core.commoncorecommonrH   Zpandas.core.indexes.apir   r   r   r   r   r   Zpandas.core.indexes.baser   baser{   Zpandas.core.internalsr   Zpandasr   r   Zpandas.core.genericr   r/   r2   r|   r}   r(   r(   r(   r.   <module>   sp    	                             \  :