U
    f/e                    @  s  d dl mZ d dlmZ d dlZd dlmZmZmZm	Z	m
Z
mZmZ d dlZd dlZd dlmZmZ d dlmZ d dlmZmZ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#m$Z$m%Z%m&Z& d dl'm(Z( d dl)m*Z*m+Z+ d dl,m-Z-m.Z. d dl/m0  m1Z2 d dl3m4Z4 d dl5m6Z6 d dl7m8Z8m9Z9 d dl:m;Z; d dl<m=Z=m>Z>m?Z? d dl@mAZAmBZBmCZC d dlDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZM d dlNmOZOmPZP edddZQG dd deAZRG dd dejSeRZSG dd deReBZTdTd d!d"dd#d$d%ZUd&d' ZVdUd(d!d"dd)d*d+ZWdVd,d-d!d.d/d0d1ZXd2d(d!d"d d3d4d5ZYd"d d6d7d8ZZdWd9d"d:d;d<Z[d9d d=d>d?Z\d@dAdBdCZ]dDd dEdFdGZ^d dHd"d dIdJdKZ_dLdLdMdNdOZ`dPd,d"dQdRdSZadS )X    )annotations)defaultdictN)AnyCallableDefaultDictHashableSequenceTypeVarcast)	internalslib)BlockPlacement)	ArrayLikeDtypeDtypeObjShapetype_t)PerformanceWarning)validate_bool_kwarg)infer_dtype_from_scalar)ensure_platform_intis_1d_only_ea_dtypeis_dtype_equalis_list_like)ExtensionDtype)ABCDataFrame	ABCSeries)array_equalsisna)NDArrayBackedExtensionArray)SparseDtype)ensure_wrapped_if_datetimelikeextract_array)maybe_convert_indices)Float64IndexIndexensure_index)DataManagerSingleDataManagerinterleaved_dtype)	BlockCategoricalBlockDatetimeTZBlockExtensionBlockensure_block_shapeextend_blocksget_block_typemaybe_coerce_values	new_block)blockwise_alloperate_blockwiseTBaseBlockManager)boundc                
   @  sn  e Zd ZU dZdZded< ded< ded< ded	< d
ed< ded< ded< dddZedddddddZe	dd Z
e	dd ZddddddZdd d!d"ZeZd
d
d#d$d%Zd
d&d'd(d)d*Ze	dd d+d,Zd'd d-d.Ze	d&d d/d0Zd1d2 Ze	d3d d4d5Zd6d d7d8Zddd:ddd;d<d=Zddd6dd>d?d@ZddddAdBZdddCdDdEZdd
d
ddFdGdHZddddIdJZdd
d
ddKdLdMZddddNdOdPZddddQdRZdddd6ddTdUdVZ ddddddddWdXdYZ!dddddZd[d\Z"ddd]d]dddd^d_d`Z#ddddadbZ$dd dcddZ%d'd dedfZ&e	dd dgdhZ'e	dd didjZ(e	dd dkdlZ)dddddmdndoZ*dddddmdpdqZ+dddddrddsdtduZ,e	d
d dvdwZ-dddddxdyZ.ddddzd{Z/d'd d|d}Z0ddd&d
dddddd~ddZ1e2j3d9fddddddZ4ddddddZ5ddd
dddddZ6dS )r6   a  
    Core internal data structure to implement DataFrame, Series, etc.

    Manage a bunch of labeled 2D mixed-type ndarrays. Essentially it's a
    lightweight blocked set of labeled data to be manipulated by the DataFrame
    public API class

    Attributes
    ----------
    shape
    ndim
    axes
    values
    items

    Methods
    -------
    set_axis(axis, new_labels)
    copy(deep=True)

    get_dtypes

    apply(func, axes, block_filter_fn)

    get_bool_data
    get_numeric_data

    get_slice(slice_like, axis)
    get(label)
    iget(loc)

    take(indexer, axis)
    reindex_axis(new_labels, axis)
    reindex_indexer(new_labels, indexer, axis)

    delete(label)
    insert(loc, label, value)
    set(label, value)

    Parameters
    ----------
    blocks: Sequence of Block
    axes: Sequence of Index
    verify_integrity: bool, default True

    Notes
    -----
    This is *not* a public API class
     
np.ndarray_blknos_blklocstuple[Block, ...]blockslist[Index]axesintndimbool_known_consolidated_is_consolidatedTc                 C  s   t d S NNotImplementedError)selfr=   r?   verify_integrityr8   r8   B/tmp/pip-unpacked-wheel-tiezk1ph/pandas/core/internals/managers.py__init__   s    zBaseBlockManager.__init__z	type_t[T]list[Block]r5   )clsr=   r?   returnc                 C  s   t d S rE   rF   rM   r=   r?   r8   r8   rJ   from_blocks   s    zBaseBlockManager.from_blocksc                 C  s   | j dkr|   | j S )a
  
        Suppose we want to find the array corresponding to our i'th column.

        blknos[i] identifies the block from self.blocks that contains this column.

        blklocs[i] identifies the column of interest within
        self.blocks[self.blknos[i]]
        N)r:   _rebuild_blknos_and_blklocsrH   r8   r8   rJ   blknos   s    

zBaseBlockManager.blknosc                 C  s   | j dkr|   | j S )z$
        See blknos.__doc__
        N)r;   rQ   rR   r8   r8   rJ   blklocs   s    
zBaseBlockManager.blklocsN)rH   rN   c                 C  s   |dkr t g g| jdd  }| jdkrtt| ts8t| jd }|jdd }tt	dd}|j
||d}|g}ng }t| ||S )z9return an empty BlockManager with the items axis of len 0N   r   	placement)r%   r?   rA   
isinstanceSingleBlockManagerAssertionErrorr=   valuesr   slicemake_block_same_classtyperP   )rH   r?   blkarrbpnbr=   r8   r8   rJ   
make_empty   s    

zBaseBlockManager.make_emptyrN   c                 C  s   dS NTr8   rR   r8   r8   rJ   __nonzero__   s    zBaseBlockManager.__nonzero__)axisrN   c                 C  s   | j dkr|dkrdnd}|S )N   r   rU   rA   )rH   rg   r8   r8   rJ   _normalize_axis   s    
z BaseBlockManager._normalize_axisr%   None)rg   
new_labelsrN   c                 C  s   |  || || j|< d S rE   )Z_validate_set_axisr?   )rH   rg   rl   r8   r8   rJ   set_axis   s    zBaseBlockManager.set_axisc                 C  s   t | jdkS NrU   lenr=   rR   r8   r8   rJ   is_single_block   s    z BaseBlockManager.is_single_blockc                 C  s   t j| jd t jd}t j| jd t jd}|d |d t| jD ],\}}|j}|||j< t 	t
|||j< qJ|dk rtd|| _|| _dS )z4
        Update mgr._blknos / mgr._blklocs.
        r   dtypezGaps in blk ref_locsN)npemptyshapeintpfill	enumerater=   mgr_locsindexerarangerp   anyrZ   r:   r;   )rH   
new_blknosZnew_blklocsblknor_   rlr8   r8   rJ   rQ      s    


z,BaseBlockManager._rebuild_blknos_and_blklocsc                 C  s
   | j d S Nr   r?   rR   r8   r8   rJ   items   s    zBaseBlockManager.itemsc                 C  s"   t dd | jD }|| jS )Nc                 S  s   g | ]
}|j qS r8   rr   .0r_   r8   r8   rJ   
<listcomp>   s     z/BaseBlockManager.get_dtypes.<locals>.<listcomp>)ru   arrayr=   takerS   rH   Zdtypesr8   r8   rJ   
get_dtypes   s    zBaseBlockManager.get_dtypeslist[ArrayLike]c                 C  s   dd | j D S )a2  
        Quick access to the backing arrays of the Blocks.

        Only for compatibility with ArrayManager for testing convenience.
        Not to be used in actual code, and return value is not the same as the
        ArrayManager method (list of 1D arrays vs iterator of 2D ndarrays / 1D EAs).
        c                 S  s   g | ]
}|j qS r8   r[   r   r8   r8   rJ   r     s     z+BaseBlockManager.arrays.<locals>.<listcomp>r=   rR   r8   r8   rJ   arrays   s    	zBaseBlockManager.arraysstrc                 C  sh   t | j}t| jD ]4\}}|dkr4|d| 7 }q|d| d| 7 }q| jD ]}|d| 7 }qP|S )Nr   z
Items: z
Axis z: 
)r^   __name__rz   r?   r=   )rH   outputiaxblockr8   r8   rJ   __repr__  s    

zBaseBlockManager.__repr__Fzlist[str] | None)rH   
align_keysignore_failuresrN   c              
     s$  d kst |pg }g } fdd|D }| jD ]}|r| D ]d\}}	t|	ttfr|	jdkrv|	j|jj	 j
 |< q|	jdd|jj	f j
 |< q@|	|jj	  |< q@z,t|r|j|f }
nt||f  }
W n" ttfk
r   |s Y q0Y nX t|
|}q0|r| |S t| || jS )a  
        Iterate over the blocks, collect and create a new BlockManager.

        Parameters
        ----------
        f : str or callable
            Name of the Block method to apply.
        align_keys: List[str] or None, default None
        ignore_failures: bool, default False
        **kwargs
            Keywords to pass to `f`

        Returns
        -------
        BlockManager
        filterc                   s   i | ]}| | qS r8   r8   )r   kkwargsr8   rJ   
<dictcomp>1  s      z*BaseBlockManager.apply.<locals>.<dictcomp>rU   N)rZ   r=   r   rX   r   r   rA   Zilocr{   r|   Z_valuescallableapplygetattr	TypeErrorrG   r/   _combiner^   rP   r?   )rH   fr   r   r   result_blocksZaligned_argsbr   objappliedr8   r   rJ   r     s0    



zBaseBlockManager.apply)rH   alignerrorsrN   c                 C  s4   |rddg}ndg}t |dd}| jd||||dS )NothercondTZextract_numpywhere)r   r   r   r   r"   r   )rH   r   r   r   r   r   r8   r8   rJ   r   S  s    
zBaseBlockManager.wherec                 C  s   | j d||dS )Nsetitem)r|   valuer   )rH   r|   r   r8   r8   rJ   r   b  s    zBaseBlockManager.setitem)r   c                 C  s2   |rddg}ndg}t |dd}| jd|||dS )NnewmaskTr   putmask)r   r   r   r   )rH   r   r   r   r   r8   r8   rJ   r   e  s    
zBaseBlockManager.putmask)rH   nrg   rN   c                 C  s   |  |}| jd||dS )Ndiff)r   rg   )rj   r   )rH   r   rg   r8   r8   rJ   r   t  s    
zBaseBlockManager.diffc                 K  s   | j d|S )Ninterpolate)r   r   rH   r   r8   r8   rJ   r   x  s    zBaseBlockManager.interpolate)rH   periodsrg   rN   c                 C  s   |  |}|tjkrd }|dkr| jdkr| jdkr| jd }|dkrbdg| tt||  }n t|}tt||dg|  }| j	| j
|d|ddd}|S | jd|||d	S )
Nr   rh   rU   rt   TF)rg   
fill_value
allow_dupsconsolidateshift)r   rg   r   )rj   r   
no_defaultrA   nblocksrw   listrangeabsreindex_indexerr   r   )rH   r   rg   r   Zncolsr|   Znperresultr8   r8   rJ   r   {  s&    


zBaseBlockManager.shift)rH   inplacerN   c                 C  s   | j d||||dS )Nfillna)r   limitr   downcastr   )rH   r   r   r   r   r8   r8   rJ   r     s        zBaseBlockManager.fillnac                 C  s
   |  dS )Nr   r   rR   r8   r8   rJ   r     s    zBaseBlockManager.downcastraise)rH   copyr   rN   c                 C  s   | j d|||dS )Nastype)rs   r   r   r   )rH   rs   r   r   r8   r8   rJ   r     s    zBaseBlockManager.astype)rH   r   datetimenumeric	timedeltarN   c                 C  s   | j d||||dS )Nconvert)r   r   r   r   r   )rH   r   r   r   r   r8   r8   rJ   r     s    zBaseBlockManager.convert)rH   r   regexrN   c                 C  s*   t |dkst|| jd||||dS )Nr   replace)
to_replacer   r   r   )ru   rA   rZ   r   )rH   r   r   r   r   r8   r8   rJ   r     s        zBaseBlockManager.replacez	list[Any])rH   src_list	dest_listr   r   rN   c                 C  s*   t |d}| jd||||d}|  |S )zdo a list replacer   Z_replace_list)r   r   r   r   )r   r   _consolidate_inplace)rH   r   r   r   r   bmr8   r8   rJ   replace_list  s    
zBaseBlockManager.replace_listc                 K  s   | j d|S )z}
        Convert values to native types (strings / python objects) that are used
        in formatting (repr / csv).
        to_native_types)r   r   r   r8   r8   rJ   r     s    z BaseBlockManager.to_native_typesc                 C  s   | j s|   | jS )zH
        Return True if more than one block with the same dtype
        )rC   _consolidate_checkrD   rR   r8   r8   rJ   is_consolidated  s    z BaseBlockManager.is_consolidatedc                 C  s0   dd | j D }t|tt|k| _d| _d S )Nc                 S  s   g | ]}|j r|jqS r8   )_can_consolidaters   r   r8   r8   rJ   r     s      z7BaseBlockManager._consolidate_check.<locals>.<listcomp>T)r=   rp   setrD   rC   r   r8   r8   rJ   r     s    z#BaseBlockManager._consolidate_checkc                 C  s   t dd | jD S )Nc                 s  s   | ]}|j V  qd S rE   Z
is_numericr   r   r8   r8   rJ   	<genexpr>  s     z9BaseBlockManager.is_numeric_mixed_type.<locals>.<genexpr>)allr=   rR   r8   r8   rJ   is_numeric_mixed_type  s    z&BaseBlockManager.is_numeric_mixed_typec                 C  s   t dd | jD S )z>Whether any of the blocks in this manager are extension blocksc                 s  s   | ]}|j V  qd S rE   )is_extensionr   r8   r8   rJ   r     s     z7BaseBlockManager.any_extension_types.<locals>.<genexpr>)r~   r=   rR   r8   r8   rJ   any_extension_types  s    z$BaseBlockManager.any_extension_typesc                 C  s   t | jdkr| jd jS dS )z8return a boolean if we are a single block and are a viewrU   r   F)rp   r=   is_viewrR   r8   r8   rJ   r     s    	zBaseBlockManager.is_view)rH   r   rN   c                 C  sZ   g }| j D ]B}|jtkr$|| q
|jr
| }|D ]}|jr6|| q6q
| ||S )z
        Select blocks that are bool-dtype and columns from object-dtype blocks
        that are all-bool.

        Parameters
        ----------
        copy : bool, default False
            Whether to copy the blocks
        )r=   rs   rB   append	is_object_splitZis_boolr   )rH   r   
new_blocksr_   nbsrb   r8   r8   rJ   get_bool_data  s    

zBaseBlockManager.get_bool_datac                 C  s   |  dd | jD |S )zy
        Parameters
        ----------
        copy : bool, default False
            Whether to copy the blocks
        c                 S  s   g | ]}|j r|qS r8   r   r   r   r8   r8   rJ   r     s      z5BaseBlockManager.get_numeric_data.<locals>.<listcomp>)r   r=   )rH   r   r8   r8   rJ   get_numeric_data  s    z!BaseBlockManager.get_numeric_datazIndex | None)rH   r=   r   indexrN   c           	      C  s   t |dkrb| jdkrZ|dk	r2| jdd |g}n| jdd g| jdd  }| |S |  S ttdd |D }t	|| j
d }g }|D ],}|j|d}t||jj |_|| qt| j}|dk	r||d< | j||d< t| ||S )	z$return a new manager with the blocksr   rh   NrU   c                 S  s   g | ]}|j jqS r8   r{   as_arrayr   r8   r8   rJ   r   &  s     z-BaseBlockManager._combine.<locals>.<listcomp>deeprt   )rp   rA   r   r?   rc   ru   sortconcatenater   Zget_reverse_indexerrw   r   r   r{   r|   r   r   r   r^   rP   )	rH   r=   r   r   r?   r|   Zinv_indexerr   r   r8   r8   rJ   r     s&    


zBaseBlockManager._combinec                 C  s
   t | jS rE   ro   rR   r8   r8   rJ   r   6  s    zBaseBlockManager.nblocksc                   sH   r&fdd  fdd| j D }n
t| j }| jdd}||_ |S )a>  
        Make deep or shallow copy of BlockManager

        Parameters
        ----------
        deep : bool or string, default True
            If False, return shallow copy (do not copy data)
            If 'all', copy data and a deep copy of the index

        Returns
        -------
        BlockManager
        c                   s    dkr| j ddS |  S )Nr   Tr   )r   view)r   r   r8   rJ   	copy_funcL  s    z(BaseBlockManager.copy.<locals>.copy_funcc                   s   g | ]} |qS r8   r8   r   r   )r   r8   rJ   r   O  s     z)BaseBlockManager.copy.<locals>.<listcomp>r   r   )r?   r   r   )rH   r   new_axesresr8   )r   r   rJ   r   :  s    
zBaseBlockManager.copyc                 C  s4   |   r| S t| | j| jdd}d|_|  |S )zr
        Join together blocks having same dtype

        Returns
        -------
        y : BlockManager
        FrI   )r   r^   r=   r?   rD   r   )rH   r   r8   r8   rJ   r   W  s    zBaseBlockManager.consolidatec                 C  s0   |   s,tt| j| _d| _d| _|   d S re   )r   tuple_consolidater=   rD   rC   rQ   rR   r8   r8   rJ   r   g  s
    z%BaseBlockManager._consolidate_inplace)rH   new_axisrg   r   r   r   
only_slicerN   c	                   s   dkrD|| j | kr|s| S | j|d}	t| j |	_ ||	j |< |	S |rP|   |sd| j |  || jkrvtd|dkr| j |d}
n fdd| jD }
t| j }|||< t	| 
|
|S )a  
        Parameters
        ----------
        new_axis : Index
        indexer : ndarray of int64 or None
        axis : int
        fill_value : object, default None
        allow_dups : bool, default False
        copy : bool, default True
        consolidate: bool, default True
            Whether to consolidate inplace before reindexing.
        only_slice : bool, default False
            Whether to take views, not copies, along columns.

        pandas-indexer with -1's only.
        Nr   #Requested axis not found in managerr   )r   r   c                   s*   g | ]"}|j d  dk	r n|jdqS )rU   N)rg   r   )take_ndr   r   r   r|   r8   rJ   r     s   z4BaseBlockManager.reindex_indexer.<locals>.<listcomp>)r?   r   r   r   Z_validate_can_reindexrA   
IndexError_slice_take_blocks_ax0r=   r^   rP   )rH   r   r|   rg   r   r   r   r   r   r   r   r   r8   r  rJ   r   n  s2    

  
z BaseBlockManager.reindex_indexerslice | np.ndarray)slice_or_indexerr   rN   c                   sl  |t jk	}t|| jd |d\}}}| jr| jd  |dkrf|dkrHg S ttd|} j||dgS |rt| j	dkr|r|dkr j
}|s|r fddt|D }	|	S ttd|} j|d||d	gS |dkr| j| }
| j| }n(tj| j|d
|d}
tj| j|d
|d}g }	| }tj|
|dD ]<\}}|d
krT|	| j||d q(| j|   js js|D ]0} jdd}tt||d |_|	| qrn||j }tt|| d }|rt ||}t|tr j||d}|	| nf|rJt||D ]8\}}t||d }t|} j||d}|	| qn j|d|d}|	| q(|	S )a  
        Slice/take blocks along axis=0.

        Overloaded for SingleBlock

        Parameters
        ----------
        slice_or_indexer : slice or np.ndarray[int64]
        fill_value : scalar, default lib.no_default
        only_slice : bool, default False
            If True, we always return views on existing arrays, never copies.
            This is used when called from ops.blockwise.operate_blockwise.

        Returns
        -------
        new_blocks : list of Block
        r   )
allow_fillr\   new_mgr_locsrU   Nc                   s,   g | ]$\}} j t||d  t|dqS )rU   r  )getitem_block_columnsr\   r   )r   r   mlr_   r8   rJ   r     s
    z;BaseBlockManager._slice_take_blocks_ax0.<locals>.<listcomp>)rg   r  r   rt   )r   r  group)rW   r   Fr   )rg   r  )r   r   _preprocess_slice_or_indexerrw   rq   r=   r   r\   r	  rA   r   rz   r   rS   rT   algoslibinternalsget_blkno_placementsr   _make_na_blockr   Z_validate_ndimr   r{   r|   maxrp   Zmaybe_indices_to_slicerX   zip)rH   r  r   r   r  Zsl_typeslobjZsllenra   r=   rS   rT   r  r   r{   mgr_locZnewblktakermax_lenrb   r   r
  Zslcr8   r  rJ   r    s    
  

	
      


z'BaseBlockManager._slice_take_blocks_ax0r   r*   )rW   rN   c                 C  sX   |d krt j}t| j}t||d< t|\}}t j||d}|| t|||j	dS )Nr   rr   rW   rA   )
ru   nanr   rw   rp   r   rv   ry   r2   rA   )rH   rW   r   block_shapers   block_valuesr8   r8   rJ   r  1  s    

zBaseBlockManager._make_na_blockrU   )rH   rg   verifyrN   c                 C  sl   t |tr"tj|j|j|jddntj|dd}| j| }t	|||d}| j
| |}| j|||dddS )ac  
        Take items along any axis.

        indexer : np.ndarray or slice
        axis : int, default 1
        verify : bool, default True
            Check that all entries are between 0 and len(self) - 1, inclusive.
            Pass verify=False if this check has been done by the caller.

        Returns
        -------
        BlockManager
        Zint64rr   )r  TF)r   r|   rg   r   r   )rX   r\   ru   r}   startstopstepZ
asanyarrayrw   r#   r?   r   r   )rH   r|   rg   r  r   rl   r8   r8   rJ   r   A  s    
zBaseBlockManager.take)T)N)NF)T)Fr   )TTTT)FF)F)F)TN)T)NFTTF)N)rU   T)7r   
__module____qualname____doc__	__slots____annotations__rK   classmethodrP   propertyrS   rT   rc   rf   __bool__rj   rm   rq   rQ   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r   r8   r8   r8   rJ   r6   Y   s   
2




  ?    
  
        F c                   @  s  e Zd ZdZdZdOdddddd	Zd
dddZeddd dddZdddddZ	dddddZ
dddddZedddd Zd!dd"d#d$Zdd%dd
d&d'd(Zd dd)d*ZdPd,d-dd,d.d/d0ZdQd,d-dd1d.d2d3Zd d d4d5d6Zd d dd7d8d9Zd:d;d<d,d=dd,d>d?d@Zd ddAdBZdRddCdDdEZd+dFd+ejfddGddHdIdJdKZdFejfdGdHdLdMdNZdFS )SBlockManagerz0
    BaseBlockManager that holds 2D blocks.
    rh   TzSequence[Block]zSequence[Index]rB   )r=   r?   rI   c              	   C  s   |rt dd |D st|D ]t}| j|jkrHtd|j d| j dt|tr|jjdkrt|j| j|_z|j  W q t	k
r   Y qX q| 
  d S )Nc                 s  s   | ]}t |tV  qd S rE   rX   r%   r   xr8   r8   rJ   r   u  s     z(BlockManager.__init__.<locals>.<genexpr>zNumber of Block dimensions (z) must equal number of axes ()rU   )r   rZ   rA   rX   r,   r[   r.   _cacheclearAttributeError_verify_integrity)rH   r=   r?   rI   r   r8   r8   rJ   rK   m  s"     zBlockManager.__init__rk   rd   c                 C  s   | j }tdd | jD }| jD ]6}|j dd  |dd  kr t||j dd  | jq t| j|krtdt| j d| d S )Nc                 s  s   | ]}t |jV  qd S rE   )rp   r{   r+  r8   r8   rJ   r     s     z1BlockManager._verify_integrity.<locals>.<genexpr>rU   zINumber of manager items must equal union of block items
# manager items: z, # tot_items: )rw   sumr=   construction_errorr?   rp   r   rZ   )rH   Z	mgr_shape	tot_itemsr   r8   r8   rJ   r1    s    
zBlockManager._verify_integrityrL   r>   r=   r?   rN   c                 C  s   | ||ddS )Z
        Constructor for BlockManager and SingleBlockManager with same signature.
        Fr   r8   rO   r8   r8   rJ   rP     s    zBlockManager.from_blocksr@   r   )locrN   c                 C  s   t | jdkr&| jd td|fS tdd | jD }t | }t|tr\tj|t	d}ntj||d}t
|}| jD ]*}t|jD ]\}}|||f||< qqxt|tr| j||d}|S )z
        Return the array corresponding to `frame.iloc[loc]`.

        Parameters
        ----------
        loc : int

        Returns
        -------
        np.ndarray or ExtensionArray
        rU   r   Nc                 S  s   g | ]
}|j qS r8   rr   r   r8   r8   rJ   r     s     z(BlockManager.fast_xs.<locals>.<listcomp>rr   )rp   r=   igetr\   r)   rX   r   ru   rv   objectr!   rz   r{   Zconstruct_array_typeZ_from_sequence)rH   r7  rs   r   r   r_   r   r   r8   r8   rJ   fast_xs  s    


zBlockManager.fast_xsrY   )r   rN   c                 C  s\   | j | j|  }|| j| }ttdt|}t|}t|||dd}t	|| j
d S )z:
        Return the data as a SingleBlockManager.
        r   rU   r  )r=   rS   r8  rT   r   r\   rp   r1   r^   rY   r?   )rH   r   r   r[   ra   rb   r8   r8   rJ   r8    s    zBlockManager.igetc                 C  s$   | j | j|  }|| j| }|S )zY
        Return the data for column i as the values (ndarray or ExtensionArray).
        )r=   rS   r8  rT   )rH   r   r   r[   r8   r8   rJ   iget_values  s    zBlockManager.iget_valueszlist[np.ndarray]c                 C  sb   dd | j D }g }tt| jD ]:}|| j|  }|jdkrN|| j|  }n|}|| q"|S )z
        Used in the JSON C code to access column arrays.
        This optimizes compared to using `iget_values` by converting each
        block.values to a np.ndarray only once up front
        c                 S  s*   g | ]"}t |tr|jjn
t|jqS r8   )rX   r,   r[   Z_ndarrayru   asarrayr   r8   r8   rJ   r     s   
z.BlockManager.column_arrays.<locals>.<listcomp>rh   )r=   r   rp   r   rS   rA   rT   r   )rH   r   r   r   r`   r[   r8   r8   rJ   column_arrays  s    
zBlockManager.column_arrayszint | slice | np.ndarray)r7  r   c                   s  t ddjdkr(jdkr(  tdd}t|}|rNfdd}nNjdkr`jntdd	fd
d}jdd jdd krt	dt
|r|g}j| }j|  }g }g }	g  tj|ddD ]\}
}j|
 }||j }|r|||| q||jj|  |	| t|t|jkrT |
 q|| tt|j|jj< qt rtjjtjd}d| < tjjtj d}|!d tjt  || < |j" _"t# fddt$jD _|	rt%|}t|}g }|r^|&fdd|D  t|tj j"|< dj|< nP|	d |	dd }|t'||j|d tjj"|< t|j|<  jt#|7  _d_(dS )z
        Set new item in-place. Does not consolidate. Adds new Block if not
        contained in the current set of items
        Tr   NrU   rs   c                   s    S rE   r8   rV   r   r8   rJ   value_getitem	  s    z(BlockManager.iset.<locals>.value_getitemrh   ri   c                   s
    | j  S rE   )r|   rV   r>  r8   rJ   r?    s    z9Shape of new values must be compatible with manager shaper  rr   rt   c                 3  s"   | ]\}}|t  kr|V  qd S rE   )r   )r   r   r_   )removed_blknosr8   rJ   r   D  s     z$BlockManager.iset.<locals>.<genexpr>c                 3  s(   | ] }t  jt||d  dV  qdS )rU   r[   rA   rW   N)r2   rA   r\   )r   r  )rH   r   r8   rJ   r   Q  s   r   rA  F))r"   r;   rA   rQ   r   r   r5   r.   rw   rZ   r   
is_integerrS   rT   r   r  r  r=   r|   Zshould_storeZset_inplacer   r{   r   rp   deleteru   r}   zerosr   bool_rv   rx   ry   r:   r   rz   r   extendr2   rC   )rH   r7  r   ZvdtypeZvalue_is_extension_typer?  rS   rT   Zunfit_mgr_locsZunfit_val_locsr   Zval_locsr_   Zblk_locs
is_deletedr   Zunfit_countr   Zunfit_val_itemsr8   )r@  rH   r   rJ   iset  s    










	zBlockManager.isetr   )r7  itemr   rN   c           
      C  s\  | j ||}|jdkr |j}nt|| jd}t|| jt||d d}t| j|d D ]Z\}}| j	| }|t
|jkr|jd|_qZ|jj }	|	|	|k  d7  < t|	|_qZ|| jjd krt| jd| _t| jt
| j	| _n*t| j|d| _t| j|t
| j	| _|| jd< |  j	|f7  _	d| _t
| j	dkrXtjd	td
d dS )z
        Insert item at selected position.

        Parameters
        ----------
        loc : int
        item : hashable
        value : np.ndarray or ExtensionArray
        rh   ri   rU   rA  Nr   Fd   zDataFrame is highly fragmented.  This is usually the result of calling `frame.insert` many times, which has poor performance.  Consider using pd.concat instead.  To get a de-fragmented frame, use `newframe = frame.copy()`   
stacklevel)r   insertrA   r5   r.   r2   r\   _fast_count_smallintsrS   r=   rp   r{   addr   r   r   rT   rw   ru   r   r;   r:   r?   rC   warningswarnr   )
rH   r7  rI  r   r   r   r   countr_   r  r8   r8   rJ   rN  q  s4    


zBlockManager.insertc                 C  sf   t j| jd t jd}d||< |  d }| j|dd}| j|  }|| jd g}t| t	||S )zJ
        Delete selected locations, returning a new BlockManager.
        r   rr   T)r   rU   )
ru   rD  rw   rE  nonzeror  r   r?   r^   r   )rH   r|   rG  r  r   new_columnsr?   r8   r8   rJ   idelete  s    zBlockManager.ideleteFr5   r   )rH   funcr   rN   c                 C  s   g }| j D ]}|jr`| D ]@}z||}W n" ttfk
rP   |sH Y qY nX t||}qq
z||}W n" ttfk
r   |s Y q
Y nX t||}q
t|dkrtdg}ntt	|d j
jd }|r| j|d|dS t| || jd |gS )aP  
        Apply grouped reduction function blockwise, returning a new BlockManager.

        Parameters
        ----------
        func : grouped reduction function
        ignore_failures : bool, default False
            Whether to drop blocks where func raises TypeError.

        Returns
        -------
        BlockManager
        r   Nrt   Fr   r   )r=   r   r   r   r   rG   r/   rp   r%   r   r[   rw   r   r^   rP   r?   )rH   rW  r   r   r_   Zsbr   r   r8   r8   rJ   grouped_reduce  s0    


zBlockManager.grouped_reduceztuple[T, np.ndarray]c           	      C  s   | j dkstg }| jD ]}|||}|| qtdg}|r|rltdd |D }| j|d|d}qg }t	| 
g | jdd |g}n&t| jd }t	| 
|| j|g}||fS )a  
        Apply reduction function blockwise, returning a single-row BlockManager.

        Parameters
        ----------
        func : reduction function
        ignore_failures : bool, default False
            Whether to drop blocks where func raises TypeError.

        Returns
        -------
        BlockManager
        np.ndarray
            Indexer of mgr_locs that are retained.
        rh   Nc                 S  s   g | ]}|j jqS r8   r   r   r8   r8   rJ   r     s     z'BlockManager.reduce.<locals>.<listcomp>FrX  r   )rA   rZ   r=   reducerF  r%   ru   r   r   r^   rP   r   r}   rw   )	rH   rW  r   Z
res_blocksr_   r   r   r|   Znew_mgrr8   r8   rJ   rZ    s    

 zBlockManager.reduce)r   rN   c                 C  s   t | ||S )zO
        Apply array_op blockwise with another (aligned) BlockManager.
        )r4   )rH   r   Zarray_opr8   r8   rJ   r4     s    zBlockManager.operate_blockwiserH   r   rN   c                 C  s   t | |tS )
        Used in .equals defined in base class. Only check the column values
        assuming shape and indexes have already been checked.
        )r3   r   )rH   r   r8   r8   rJ   _equal_values  s    zBlockManager._equal_valuesr   Zlinear)rg   interpolationr$   )rH   qsrg   rN   c                  sb   | j dksttst dks&tt| j}t|d<  fdd| jD }t| ||S )a  
        Iterate over blocks applying quantile reduction.
        This routine is intended for reduction type operations and
        will do inference on the generated blocks.

        Parameters
        ----------
        axis: reduction axis, default 0
        consolidate: bool, default True. Join together blocks having same
            dtype
        interpolation : type of interpolation, default 'linear'
        qs : list of the quantiles to be computed

        Returns
        -------
        BlockManager
        rh   rU   c                   s   g | ]}|j  d qS ))rg   r_  r^  )quantiler   rg   r^  r_  r8   rJ   r   :  s   z)BlockManager.quantile.<locals>.<listcomp>)rA   rZ   r   r   r?   r$   r=   r^   )rH   r_  rg   r^  r   r=   r8   ra  rJ   r`    s    
zBlockManager.quantilec                 C  s   | | j}|j}g }g }| jD ]N}| j|jj }| |}	||	}
|j|||
d\}}|| || q || }t	|||g}|S )a(  
        Return a BlockManager with all blocks unstacked..

        Parameters
        ----------
        unstacker : reshape._Unstacker
        fill_value : Any
            fill_value for newly introduced missing values.

        Returns
        -------
        unstacked : BlockManager
        )new_placement)
Zget_new_columnsr   	new_indexr=   r{   r|   Zget_indexerZ_unstackrF  r)  )rH   Z	unstackerr   rU  rc  r   Zcolumns_maskr_   Zblk_colsZ	new_itemsrb  r=   r   r   r8   r8   rJ   unstackC  s$    


  

zBlockManager.unstackr   c                   s@   i }j D ]}|t|jg | q
 fdd| D S )z
        Return a dict of str(dtype) -> BlockManager

        Parameters
        ----------
        copy : bool, default True

        Returns
        -------
        values : a dict of dtype -> BlockManager
        c                   s    i | ]\}}|j | d qS )re  )r   )r   rs   r=   r   rH   r8   rJ   r   z  s      z(BlockManager.to_dict.<locals>.<dictcomp>)r=   
setdefaultr   rs   r   r   )rH   r   Zbdr   r8   rf  rJ   to_dicth  s    
zBlockManager.to_dictNzDtype | Noner9   )	transposers   r   rN   c                 C  s   t | jdkr.tj| jtd}|r*| S |S |p:|tjk	}| j	r| jd }|j
rl|jj||d|j}qt| }|r|j|dd}n| j||d}d}|r| }|tjk	r||t|< |r| S |S )a|  
        Convert the blockmanager data into an numpy array.

        Parameters
        ----------
        transpose : bool, default False
            If True, transpose the return array.
        dtype : object, default None
            Data type of the return array.
        copy : bool, default False
            If True then guarantee that a copy is returned. A value of
            False does not guarantee that the underlying data is not
            copied.
        na_value : object, default lib.no_default
            Value to be used as the missing value sentinel.

        Returns
        -------
        arr : ndarray
        r   rr   rs   na_valueFre  )rp   r=   ru   rv   rw   floatri  r   r   rq   r   r[   to_numpyZreshaper<  
get_valuesr   _interleaver   r   )rH   ri  rs   r   rk  r`   r_   r8   r8   rJ   r   |  s.    
 
zBlockManager.as_arrayrs   rN   c                 C  s   |st dd | jD }t|tr*|j}n*t|tr@td}nt|t	rTtd}tj
| j|d}t| jd }| jD ]@}|j}|jr|jj||d}n
||}|||j< d||j< qz| std|S )	zt
        Return ndarray from blocks with specified item order
        Items must be contained in the blocks
        c                 S  s   g | ]
}|j qS r8   rr   r   r8   r8   rJ   r     s     z,BlockManager._interleave.<locals>.<listcomp>r9  rr   r   rj  rU   z'Some items were not contained in blocks)r)   r=   rX   r    subtyper   ru   rs   r   r   rv   rw   rD  r{   r   r[   rm  rn  r|   r   rZ   )rH   rs   rk  r   Zitemmaskr_   r   r`   r8   r8   rJ   ro    s.    




 

zBlockManager._interleave)T)F)F)T)r   r!  r"  r#  rA   rK   r1  r&  rP   r:  r8  r;  r'  r=  rH  rN  rV  rY  rZ  r4   r]  r`  rd  rh  r   r   r   ro  r8   r8   r8   rJ   r)  c  sB   	  	&z50 '*%D r)  c                   @  s~  e Zd ZdZdZdZdZdZdZde	j
fdddd	d
dZeddd dddZeddd dddZdd Zdd Zdd ZeddddZedd Zed d! Zd dd"d#ZdLd%d&d d'd(d)Zeddd*d+Zed,dd-d.Zd/dd0d1Zd2d3 Zd4d5 Zd6d7 Zeddd8d9Zddd:d;Zd<d= Z d>d? Z!d dd@dAZ"dBdC Z#ddDdEdFZ$dGdGddHdIdJZ%dKS )MrY   zmanage a single block withrU   Tr8   Fr*   r%   rB   )r   rg   rI   c                 C  sZ   t |tstt|t |ts,tt||tjk	rFtjdt	dd |g| _
|f| _d S )NzMThe `fastpath` keyword is deprecated and will be removed in a future version.rh   rL  )rX   r*   rZ   r^   r%   r   r   rQ  rR  FutureWarningr?   r=   )rH   r   rg   rI   Zfastpathr8   r8   rJ   rK     s    
zSingleBlockManager.__init__rL   r>   r5  c                 C  s6   t |dkstt |dks t| |d |d ddS )r6  rU   r   Fr   )rp   rZ   rO   r8   r8   rJ   rP     s    zSingleBlockManager.from_blocksr   )r   r   rN   c                 C  s"   t |tdt|dd}| ||S )zN
        Constructor for if we have an array that is not yet a Block.
        r   rU   r  )r2   r\   rp   )rM   r   r   r   r8   r8   rJ   
from_array  s    zSingleBlockManager.from_arrayc                   sT   dd  j D } fdd j D }t j}d|dd  j D di}||||fS )Nc                 S  s   g | ]
}|j qS r8   r   r   r8   r8   rJ   r   #  s     z3SingleBlockManager.__getstate__.<locals>.<listcomp>c                   s   g | ]} j |jj qS r8   )r   r{   r|   r   rR   r8   rJ   r   $  s     0.14.1c                 S  s   g | ]}|j |jjd qS ))r[   r{   )r[   r{   r|   r   r8   r8   rJ   r   *  s   )r?   r=   )r=   r   r?   )rH   r  Zblock_itemsZ
axes_arrayZextra_stater8   rR   rJ   __getstate__"  s    
zSingleBlockManager.__getstate__c                   s   dddddt |tr|t|dkr|d|d kr||d d }d	d
 |d D | _t| j t fdd|d D | _ntd|   d S )Nr@   r*   )rA   rN   c                 S  s   t | dd} t| ||dS )NTr   r  )r"   r2   )r[   r{   rA   r8   r8   rJ   unpickle_block6  s    z7SingleBlockManager.__setstate__.<locals>.unpickle_block   rt     c                 S  s   g | ]}t |qS r8   )r&   r   r8   r8   rJ   r   >  s     z3SingleBlockManager.__setstate__.<locals>.<listcomp>r?   c                 3  s$   | ]}|d  |d  dV  qdS )r[   r{   ri   Nr8   r   rA   rv  r8   rJ   r   @  s   z2SingleBlockManager.__setstate__.<locals>.<genexpr>r=   z*pre-0.14.1 pickles are no longer supported)rX   r   rp   r?   r=   rG   _post_setstate)rH   stater8   ry  rJ   __setstate__5  s    "
zSingleBlockManager.__setstate__c                 C  s   d S rE   r8   rR   r8   r8   rJ   rz  I  s    z!SingleBlockManager._post_setstaterd   c                 C  s
   | j d S r   r   rR   r8   r8   rJ   _blockL  s    zSingleBlockManager._blockc                 C  s   dS zcompat with BlockManagerNr8   rR   r8   r8   rJ   r:   P  s    zSingleBlockManager._blknosc                 C  s   dS r~  r8   rR   r8   r8   rJ   r;   U  s    zSingleBlockManager._blklocsc                 C  sZ   | j }||}|jdkr"tdttdt|}|j||d}| j| }t	| ||S )NrU   z(dimension-expanding indexing not allowedr   rV   )
r}  _slicerA   
ValueErrorr   r\   rp   r]   r   r^   )rH   r|   r_   r   ra   r   Znew_idxr8   r8   rJ   getitem_mgrZ  s    


zSingleBlockManager.getitem_mgrr   r\   r@   )r  rg   rN   c                 C  sr   t |tstt||| jkr(td| j}||}ttdt	|}|j
||d}| j|}t| ||S )Nr   r   rV   )rX   r\   rZ   r^   rA   r  r}  r  r   rp   r]   r   Z_getitem_slice)rH   r  rg   r_   r   ra   r   rc  r8   r8   rJ   	get_sliceh  s    

zSingleBlockManager.get_slicec                 C  s
   | j d S r   r   rR   r8   r8   rJ   r   t  s    zSingleBlockManager.indexr   c                 C  s   | j jS rE   )r}  rs   rR   r8   r8   rJ   rs   x  s    zSingleBlockManager.dtyper9   c                 C  s   t | jjgS rE   )ru   r   r}  rs   rR   r8   r8   rJ   r   |  s    zSingleBlockManager.get_dtypesc                 C  s
   | j  S )z$The array that Series.values returns)r}  external_valuesrR   r8   r8   rJ   r    s    z"SingleBlockManager.external_valuesc                 C  s   | j jS )z%The array that Series._values returns)r}  r[   rR   r8   r8   rJ   internal_values  s    z"SingleBlockManager.internal_valuesc                 C  s   | j jS )z#The array that Series.array returns)r}  array_valuesrR   r8   r8   rJ   r    s    zSingleBlockManager.array_valuesc                 C  s   | j jS rE   )r}  _can_hold_narR   r8   r8   rJ   r    s    zSingleBlockManager._can_hold_nac                 C  s   dS re   r8   rR   r8   r8   rJ   r     s    z"SingleBlockManager.is_consolidatedc                 C  s   d S rE   r8   rR   r8   r8   rJ   r     s    z%SingleBlockManager._consolidate_checkc                 C  s   d S rE   r8   rR   r8   r8   rJ   r     s    z'SingleBlockManager._consolidate_inplacec                 C  s&   | j | | jd || jd< | S )zy
        Delete single location from SingleBlockManager.

        Ensures that self.blocks doesn't become empty.
        r   )r}  rC  r?   )rH   r|   r8   r8   rJ   rV    s    zSingleBlockManager.ideletec                 C  s   t ddS )zY
        fast path for getting a cross-section
        return a view of the data
        zUse series._values[loc] insteadNrF   )rH   r7  r8   r8   rJ   r:    s    zSingleBlockManager.fast_xsr   c                 C  s(   || j d _ttt|| j d _dS )z
        Set the values of the single block in place.

        Use at your own risk! This does not check if the passed values are
        valid for the current Block/SingleBlockManager (length, dtype, etc).
        r   N)r=   r[   r   r\   rp   Z	_mgr_locs)rH   r[   r8   r8   rJ   
set_values  s    zSingleBlockManager.set_valuesr5   r[  c                 C  s0   |j dkrdS | jd j}|jd j}t||S )r\  rU   Fr   )rA   r=   r[   r   )rH   r   leftrightr8   r8   rJ   r]    s
    
z SingleBlockManager._equal_valuesN)r   )&r   r!  r"  r#  rA   rD   rC   r$  rq   r   r   rK   r&  rP   rs  ru  r|  rz  r'  r}  r:   r;   r  r  r   rs   r   r  r  r  r  r   r   r   rV  r:  r  r]  r8   r8   r8   rJ   rY     sR   



rY   TrL   r>   rB   )r=   r?   r   rN   c              
   C  s~   zt | |}W n^ tk
rl } z@dd | D }tdd |D }t||d jdd  ||W 5 d }~X Y nX |rz|  |S )Nc                 S  s   g | ]
}|j qS r8   r   r   r8   r8   rJ   r     s     z4create_block_manager_from_blocks.<locals>.<listcomp>c                 s  s   | ]}|j d  V  qdS )r   N)rw   )r   r`   r8   r8   rJ   r     s     z3create_block_manager_from_blocks.<locals>.<genexpr>r   rU   )r)  r  r2  r3  rw   r   )r=   r?   r   mgrerrr   r4  r8   r8   rJ    create_block_manager_from_blocks  s    .r  c                 C  s   t | ddS )NTr   )r"   )r   r8   r8   rJ   _extract_array  s    r  r%   )namesr?   r   rN   c              
   C  s   t |tstt |tsttdd |D s2tdd | D } zt| |||}t||}W n: tk
r } ztt	| | d j
||W 5 d }~X Y nX |r|  |S )Nc                 s  s   | ]}t |tV  qd S rE   r*  r+  r8   r8   rJ   r     s     z3create_block_manager_from_arrays.<locals>.<genexpr>c                 S  s   g | ]}t |qS r8   )r  r+  r8   r8   rJ   r     s     z4create_block_manager_from_arrays.<locals>.<listcomp>r   )rX   r%   rZ   r   r   _form_blocksr)  r  r3  rp   rw   r   )r   r  r?   r   r=   r  er8   r8   rJ    create_block_manager_from_arrays  s    *r  r@   r   zValueError | None)r4  r  r?   r  c                 C  s   t tt| gt| }t|dkr2|ddd }t dd |D }t|dkr^|ddd }||krr|dk	rr|S |d dkrtdS td| d	| S )
z.raise a helpful message about our constructionrh   Nrt   c                 s  s   | ]}t |V  qd S rE   rp   r   r8   r8   rJ   r     s     z%construction_error.<locals>.<genexpr>r   z)Empty data passed with indices specified.zShape of passed values is z, indices imply )r   mapr@   r   rp   r  )r4  r  r?   r  ZpassedZimpliedr8   r8   rJ   r3    s    r3  r   )r   r  r?   r   rN   c                 C  s   t t}g }|}||d r.tt|}n"||d jsBt|	|d }t
|D ]@\}}	|	dkrt|| qX| |	 }
t|
}||j ||
f qXg }t|d rt|d |d}|| t|d rt|d |d}|| t|d rdd |d D }|| t|d	 dkrDt|d	 tj|d}|| t|d
 dkrrdd |d
 D }|| t|d rdd |d D }|| t|rt|ftdd |dd  D  }tj|td}|tj t||dd}|| |S )Nr   rt   ZNumericBlock)r   ZDatetimeLikeBlockr,   c                 S  s*   g | ]"\}}t tt|d t|d dqS rh   )klassrW   rA   )r2   r.   r"   r,   r   r   r   r8   r8   rJ   r   3  s   z _form_blocks.<locals>.<listcomp>ZObjectBlockr+   c                 S  s    g | ]\}}t |t|d dqS r  )r2   r+   r  r8   r8   rJ   r   E  s   r-   c                 S  s    g | ]\}}t |t|d dqS r  )r2   r-   r  r8   r8   rJ   r   L  s   c                 s  s   | ]}t |V  qd S rE   r  r+  r8   r8   rJ   r   T  s     z_form_blocks.<locals>.<genexpr>rU   rr   rh   r  )r   r   equalsru   r}   rp   intersectionZ	is_uniquerZ   Zget_indexer_forrz   r   r0   r   _multi_blockifyrF  _simple_blockifyZobject_r   rv   r9  ry   r  r2   )r   r  r?   r   Z
items_dictZ
extra_locsZ	names_idxZnames_indexerr   Zname_idxvZ
block_typer=   Znumeric_blocksZdtlike_blocksZdttz_blocksZobject_blocksZ
cat_blocksZexternal_blocksrw   r  Zna_blockr8   r8   rJ   r    sp    
 
 
	
  



$
r  )r   rN   c                 C  sN   |st | |dS t| |\}}|dk	r:|j|kr:||}t||dd}|gS )zr
    return a single array of a block that has a single dtype; if dtype is
    not None, coerce to this dtype
    rr   Nrh   r  ) _tuples_to_blocks_no_consolidate_stack_arraysrs   r   r2   )tuplesrs   r   r[   rW   r   r8   r8   rJ   r  `  s    
r  zDtypeObj | None)rs   r   c           	      C  s`   |st | |dS t| dd }g }|D ]2\}}tt||\}}t||dd}|| q(|S )z@return an array of blocks that potentially have different dtypesrr   c                 S  s
   | d j S rn   rr   r,  r8   r8   rJ   <lambda>y      z!_multi_blockify.<locals>.<lambda>rh   r  )r  	itertoolsgroupbyr  r   r2   r   )	r  rs   r   grouperr   Z	tup_blockr[   rW   r   r8   r8   rJ   r  r  s     r  rp  c                   s(    d k	r fdd| D S dd | D S )Nc              	     s2   g | ]*}t t|d  j dd|d ddqS )rU   Fre  r   rh   r  )r2   ru   
atleast_2dr   r+  rr   r8   rJ   r     s     z4_tuples_to_blocks_no_consolidate.<locals>.<listcomp>c                 S  s(   g | ] }t t|d  |d ddqS )rU   r   rh   r  )r2   ru   r  r+  r8   r8   rJ   r     s     r8   )r  rs   r8   rr   rJ   r    s
    
r  znp.dtyperr   c           	      C  sT   t |  \}}|d }t|f|j }tj||d}t|D ]\}}|||< q:||fS )Nr   rr   )r  rp   rw   ru   rv   rz   )	r  rs   rW   r   firstrw   Zstackedr   r`   r8   r8   rJ   r    s    
r  r<   )r=   rN   c                 C  sR   dd }t t| |d|}g }|D ](\\}}}tt|||d}t||}q$|S )zJ
    Merge blocks having same dtype, exclude non-consolidating blocks
    c                 S  s   | j S rE   )Z_consolidate_keyr  r8   r8   rJ   r    r  z_consolidate.<locals>.<lambda>)key)rs   can_consolidate)r  r  sorted_merge_blocksr   r/   )r=   Zgkeyr  r   r   rs   Zgroup_blocksZmerged_blocksr8   r8   rJ   r     s      r   r   )r=   rs   r  rN   c           	      C  s   t | dkr| S |rtdd | D }t| d jtjrPtdd | D }n.dd | D }ttt |}|d j	|dd}t
|}|| }|| }t|}t||dd	gS | S )
NrU   c                 S  s   g | ]}|j jqS r8   r   r   r8   r8   rJ   r     s     z!_merge_blocks.<locals>.<listcomp>r   c                 S  s   g | ]
}|j qS r8   r   r   r8   r8   rJ   r     s     c                 S  s   g | ]
}|j qS r8   r   r   r8   r8   rJ   r     s     )rg   rh   r  )rp   ru   r   rX   rs   Zvstackr
   r   r   Z_concat_same_typeargsortr   r2   )	r=   rs   r  r  Z
new_valuesZbvalsZbvals2r  ra   r8   r8   rJ   r    s    
r  r9   )r`   rN   c                 C  s0   t | t j}| d }t j||| f S )z:Faster version of set(arr) for sequences of small numbers.r   )ru   Zbincountr   int_rT  Zc_)r`   countsZnzr8   r8   rJ   rO    s    rO  r  )r  lengthr  c                 C  sv   t | trd| t| |fS t | tjr4| jjdkrNt| dd }t	t
| |t| }|sdt||}d|t|fS d S )Nr\   r   rs   Zfancy)rX   r\   r  Z	slice_lenru   Zndarrayrs   kindr   r   r^   r   r#   rp   )r  r  r  rs   r|   r8   r8   rJ   r    s    




r  )T)T)N)NT)b
__future__r   collectionsr   r  typingr   r   r   r   r   r	   r
   rQ  Znumpyru   Zpandas._libsr   r  r   Zpandas._libs.internalsr   Zpandas._typingr   r   r   r   r   Zpandas.errorsr   Zpandas.util._validatorsr   Zpandas.core.dtypes.castr   Zpandas.core.dtypes.commonr   r   r   r   Zpandas.core.dtypes.dtypesr   Zpandas.core.dtypes.genericr   r   Zpandas.core.dtypes.missingr   r   Zpandas.core.algorithmscoreZ
algorithmsr  Zpandas.core.arrays._mixinsr   Zpandas.core.arrays.sparser    Zpandas.core.constructionr!   r"   Zpandas.core.indexersr#   Zpandas.core.indexes.apir$   r%   r&   Zpandas.core.internals.baser'   r(   r)   Zpandas.core.internals.blocksr*   r+   r,   r-   r.   r/   r0   r1   r2   Zpandas.core.internals.opsr3   r4   r5   r6   r)  rY   r  r  r  r3  r  r  r  r  r  r   r  rO  r  r8   r8   r8   rJ   <module>   sp   $	,            S   T%