U
    MfL                    @  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mZ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' d dl(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0 d dl1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9 d dl:m;Z;m<Z<m=Z=m>Z> d dl?m@Z@mAZAmBZBmCZC d dlDmEZE d dlFmGZGmHZHmIZI d dlJmK  mLZ d dlMmNZNmOZOmPZPmQZQmRZRmSZS d dlTmUZU d dlVmWZWmXZXmYZY d dlZm[Z[ d dl\m]Z] d dl^m_Z_m`Z`maZambZbmcZcmdZdmeZe d dlfmgZg d dlhmiZi d dljmkZk d dllmK  mmZn d dlomK  mp  mqZq d dlrmsZsmtZt d dlumvZvmwZwmxZx d dlymK  mzZz erd dl{m|Z|m}Z} e~dZddd d!d"ZG d#d$ d$ekZG d%d& d&eZG d'd( d(ejeZG d)d* d*ejeZG d+d, d,eZG d-d. d.ejeZd/d0d1d2d3ZG d4d5 d5eZG d6d7 d7eZG d8d9 d9eZG d:d; d;eZd<d<d=d>d?Zd@dAdBdCZd<dDdEdFdGZdHd$dIdJdKZdDdHdLdMdNZdOdPdHdQdRdSdTZdedUdVdWdXZdfd<dHd<dZd[d\Zd]ddd^d_d<d`d=dadbZd<d<d=dcddZdS )g    )annotations)wrapsN)TYPE_CHECKINGAnyCallableIterableSequencecastfinal)	Timestampalgos	internalslibwriters)BlockPlacement)	ArrayLikeDtypeObjFShapenpt)np_version_under1p20)cache_readonly)find_stack_level)validate_bool_kwarg)astype_array_safecan_hold_elementfind_common_typeinfer_dtype_frommaybe_downcast_numericmaybe_downcast_to_dtypemaybe_upcastsoft_convert_objects)ensure_platform_intis_1d_only_ea_dtypeis_1d_only_ea_objis_dtype_equalis_extension_array_dtypeis_interval_dtypeis_list_likeis_string_dtype)CategoricalDtypeExtensionDtypePandasDtypePeriodDtype)ABCDataFrameABCIndexABCPandasArray	ABCSeries)is_inferred_bool_dtype)is_valid_na_for_dtypeisnana_value_for_dtype)extract_bool_arrayputmask_inplaceputmask_smartputmask_without_repeatsetitem_datetimelike_compatvalidate_putmask)quantile_compat)compare_or_regex_searchreplace_regexshould_use_regex)take_nd)shift)CategoricalDatetimeArrayExtensionArrayIntervalArrayPandasArrayPeriodArrayTimedeltaArray)NDArrayBackedExtensionArray)SparseDtype)PandasObject)ensure_wrapped_if_datetimelikeextract_array)check_setitem_lengthsis_empty_indexeris_scalar_indexer)Float64IndexIndexobjectr   )methreturnc                   s$   t  dd fdd}tt|S )zp
    If we have a multi-column block, split and operate block-wise.  Otherwise
    use the original method.
    list[Block]rU   c                   s>   | j dks| jd dkr( | f||S | j f||S d S )N   r   )ndimshapesplit_and_operate)selfargskwargsrT    @/tmp/pip-unpacked-wheel-eb6vo0j3/pandas/core/internals/blocks.pynewfunc   s    zmaybe_split.<locals>.newfunc)r   r	   r   )rT   rb   r`   r_   ra   maybe_split   s    rc   c                   @  s>  e Zd ZU dZded< ded< ded< dZd	Zd	Zd	Zd
Z	d
Z
eedd ZeddddZeeddddZeeddddZeeddddZedd ZeddddZddddd d!Zddd"d#Zeed$d% Zed&dd'd(Zejd&d)d*d(Zedd dd+d,Zedd-d d.d/d0Zed1dd2d3Zeddd4d5Zd6dd7d8Zed9d d:d;d<Zed=d&d d>d?d@Z edAddBdCZ!edDddEdFZ"dGdHdIdJZ#dKddLdMZ$dKddNdOZ%edPddQdRZ&dddPdSdTdUZ'ed6dPdVdWdXZ(dddPdYdZd[Z)edPdd\d]Z*edPdd^d_Z+eddPdPd`dadbZ,ee-dPddcddZ.eddDdd1dfdgdhZ/ddddddPdidjdkZ0edlddmdndoZ1ed6ddpdqdrZ2eddtduZ3edddvdwdxZ4edddydPdzd{d|Z5eddddPd}d~dZ6eddddddPdddZ7edddddPdddZ8dddddZ9dd Z:dPdddZ;ed dddZ<dd1ddddd1dddddPdddZ=de>j?fdd-d dddZ@ddddPdddZAddddldPdddZBdPdddZCdddddZDedddd dddZEdS )Blockz
    Canonical n-dimensional unit of homogeneous dtype contained in a pandas
    data structure

    Index-ignorant; let the container take care of that
    np.ndarray | ExtensionArrayvaluesintrY   r   __init__r`   FTc                 C  s   | j | jjfS N)_can_consolidatedtypenamer\   r`   r`   ra   _consolidate_key   s    zBlock._consolidate_keyboolrW   c                 C  s   | j }ttj|}|jdk	S z(return a boolean if I am possibly a viewN)rf   r	   npndarraybase)r\   rf   r`   r`   ra   is_view   s    zBlock.is_viewc                 C  s"   | j }t|tj r|jdkS |jS )z7
        Can we store NA values in this Block?
        )biu)rk   
isinstancerq   kind_can_hold_nar\   rk   r`   r`   ra   rz      s    
zBlock._can_hold_nac                 C  s   t jdtt d t| jtS )NzBlock.is_categorical is deprecated and will be removed in a future version.  Use isinstance(block.values, Categorical) instead. See https://github.com/pandas-dev/pandas/issues/40226
stacklevel)warningswarnDeprecationWarningr   rx   rf   rB   rm   r`   r`   ra   is_categorical   s    zBlock.is_categoricalc                 C  s
   t | jS )z^
        We can be bool if a) we are bool dtype or b) object dtype with bool objects.
        )r2   rf   rm   r`   r`   ra   is_bool   s    zBlock.is_boolc                 C  s
   t | jS ri   )external_valuesrf   rm   r`   r`   ra   r      s    zBlock.external_valuesrD   c                 C  s
   t | jS )zP
        The array that Series.array returns. Always an ExtensionArray.
        )rF   rf   rm   r`   r`   ra   array_values   s    zBlock.array_valuesNDtypeObj | None
np.ndarrayrk   rU   c                 C  s   |t kr| jt S | jS )z
        return an internal format, currently just the ndarray
        this is often overridden to handle to_dense like operations
        )
_dtype_objrf   astyper{   r`   r`   ra   
get_values   s    zBlock.get_valuesc                 C  s   | j S ri   rf   rm   r`   r`   ra   values_for_json   s    zBlock.values_for_jsonc                 C  s   t | jddS )NF)compat)r5   rk   rm   r`   r`   ra   
fill_value   s    zBlock.fill_valuer   c                 C  s   | j S ri   	_mgr_locsrm   r`   r`   ra   mgr_locs   s    zBlock.mgr_locs)new_mgr_locsc                 C  s
   || _ d S ri   r   )r\   r   r`   r`   ra   r      s    c                 C  s2   |dkr| j }| jr"t|| jd}t||| jdS )zm
        Create a new block, with type inference propagate any values that are
        not specified
        NrY   	placementrY   )r   is_extensionensure_block_shaperY   	new_block)r\   rf   r   r`   r`   ra   
make_block   s
    zBlock.make_blockBlockPlacement | None)r   rU   c                 C  sT   |dkr| j }|jjdkr@t|}||k	r<tjdtt d |}t| ||| j	dS )z2Wrap given values in a block of same type as self.NmMzIn a future version, Block.make_block_same_class will assume that datetime64 and timedelta64 ndarrays have already been cast to DatetimeArray and TimedeltaArray, respectively.r|   r   )
r   rk   ry   rL   r~   r   r   r   typerY   )r\   rf   r   
new_valuesr`   r`   ra   make_block_same_class  s    zBlock.make_block_same_classstrc                 C  sj   t | j}| jdkr0| dt|  d| j }n6ddd | jD }| d| jj d| d| j }|S )	NrX   z: z dtype: z x c                 S  s   g | ]}t |qS r`   )r   .0sr`   r`   ra   
<listcomp>-  s     z"Block.__repr__.<locals>.<listcomp>z, z	, dtype: )	r   __name__rY   lenrk   joinrZ   r   indexer)r\   rl   resultrZ   r`   r`   ra   __repr__%  s    

 zBlock.__repr__c                 C  s
   t | jS ri   )r   rf   rm   r`   r`   ra   __len__2  s    zBlock.__len__r   c                 C  s
   | j | S )zreturn a slice of my valuesr   )r\   slicerr`   r`   ra   _slice6  s    zBlock._slicezslice | npt.NDArray[np.intp]r   rU   c                 C  sR   t |tr|d n|}| j| }| |}|j| jjkr@tdt| ||| jS )
        Perform __getitem__-like, return result as block.

        Only supports slices that preserve dimensionality.
        r    Only same dim slicing is allowed)rx   tupler   r   rY   rf   
ValueErrorr   )r\   r   Zaxis0_slicerr   r   r`   r`   ra   getitem_block;  s    

zBlock.getitem_blockslice)r   r   rU   c                 C  s2   |  |}|j| jjkr tdt| ||| jS )r   r   )r   rY   rf   r   r   )r\   r   r   r   r`   r`   ra   getitem_block_columnsL  s    	
zBlock.getitem_block_columnsr   c                 C  s   | j jS ri   )rf   rZ   rm   r`   r`   ra   rZ   ^  s    zBlock.shaper   c                 C  s   | j jS ri   rf   rk   rm   r`   r`   ra   rk   b  s    zBlock.dtype)int | tuple[int, int] | tuple[slice, int]rv   c                 C  s
   | j | S ri   r   )r\   rv   r`   r`   ra   igetf  s    z
Block.igetNonec                 C  s   || j |< dS )z
        Modify block values in-place with new item value.

        Notes
        -----
        `set` never creates a new array or new Block, whereas `setitem` _may_
        create a new array and always creates a new Block.
        Nr   r\   Zlocsrf   r`   r`   ra   set_inplaceo  s    	zBlock.set_inplacec                 C  sH   t | j|d| _| j|| _z| j  W n tk
rB   Y nX dS );
        Delete given loc(-s) from block in-place.
        r   N)rq   deleterf   r   r   _cacheclearAttributeErrorr\   locr`   r`   ra   r   z  s    
zBlock.deleterV   c                 K  s   || j f|}| |S )z[
        apply the function to my values; return a block if we are not
        one
        )rf   _split_op_result)r\   funcr^   r   r`   r`   ra   apply  s    zBlock.applyignore_failuresrU   c              	   C  s|   | j dkstz|| j}W n& ttfk
rB   |r<g  Y S  Y nX | jj dkr`t|gg}n|dd}| |}|gS )N   rX   )	rY   AssertionErrorrf   	TypeErrorNotImplementedErrorrq   arrayreshaper   )r\   r   r   r   
res_valuesnbr`   r`   ra   reduce  s    
zBlock.reduce)r   rU   c                 C  s|   |j dkrlt|jtrlg }t| jD ]B\}}t|sF|||d  }n|| }| j||d}|| q$|S | |}|gS )NrX   rf   r   )	rY   rx   rk   r+   	enumerater   r$   r   append)r\   r   nbsrv   r   valsblockr   r`   r`   ra   r     s    
zBlock._split_op_resultinplacerU   c           	      C  s  t |d}t| j}t| j|\}}|dk	rRtjd|d}d||| jd |k< | jsl|rb| gS | 	 gS | 
|r|r~| n| 	 }t|j|| ||g|S |r|r| gS | 	 gS | jdks| jd dkr| |}|j||dddS | jt| j|||ddS dS )	zs
        fillna on the block with the value. If we fail, then convert to
        ObjectBlock and try again
        r   N)limitFrX   r   T)r   r   downcast)r   r4   rf   r;   libalgosZvalidate_limitZcumsumrY   rz   copy_can_hold_elementr7   _maybe_downcastrZ   coerce_to_target_dtypefillnar[   r   )	r\   valuer   r   r   masknoopr   blkr`   r`   ra   r     s4    




    zBlock.fillnac                 C  sb   | j dkstg }t| jD ]@\}}| jt||d  }t|}t| ||dd}|| q|S )zD
        Split a block into a list of single-column blocks.
        r   rX   r   )	rY   r   r   r   rf   r   r   r   r   )r\   Z
new_blocksrv   Zref_locr   bpr   r`   r`   ra   _split  s    zBlock._splitc                 O  sL   | j dkr| jd dkstg }|  D ]}||f||}|| q(|S )z
        Split the block and apply func column-by-column.

        Parameters
        ----------
        func : Block method
        *args
        **kwargs

        Returns
        -------
        List[Block]
        r   r   rX   )rY   rZ   r   r   extend)r\   r   r]   r^   
res_blocksr   rbsr`   r`   ra   r[     s    zBlock.split_and_operate)blocksrU   c                   sJ    dkr|S | j tkr(tdd |D S  d kr4|S t fdd|D S )NFc                 S  s   g | ]}|j d ddqS )TF)datetimenumericconvert)r   r   r`   r`   ra   r     s     z)Block._maybe_downcast.<locals>.<listcomp>c                   s   g | ]}|  qS r`   )_downcast_2dr   ru   r   r`   ra   r   #  s     )rk   r   extend_blocks)r\   r   r   r`   r   ra   r     s    
zBlock._maybe_downcastc                 C  s   t | j|d}| |gS )zs
        downcast specialized to 2D case post-validation.

        Refactored to allow use of maybe_split.
        rk   )r   rf   r   )r\   rk   r   r`   r`   ra   r   %  s    zBlock._downcast_2draise)rk   r   errorsc                 C  sl   | j }t||||d}t|}| |}|j| jkrhtd| d| jj d| j d|jj d|j d|S )a  
        Coerce to the new dtype.

        Parameters
        ----------
        dtype : np.dtype or ExtensionDtype
        copy : bool, default False
            copy if indicated
        errors : str, {'raise', 'ignore'}, default 'raise'
            - ``raise`` : allow exceptions to be raised
            - ``ignore`` : suppress exceptions. On error return original object

        Returns
        -------
        Block
        )r   r   zcannot set astype for copy = [z] for dtype (z [z]) to different shape (z]))rf   r   maybe_coerce_valuesr   rZ   r   rk   rl   )r\   rk   r   r   rf   r   Znewbr`   r`   ra   r   0  s    
.zBlock.astyper   r   r   	timedeltarU   c                 C  s   |r|   gS | gS )z
        attempt to coerce any object types to better types return a copy
        of the block (if copy = True) by definition we are not an ObjectBlock
        here!
        r   )r\   r   r   r   r   r`   r`   ra   r   P  s    zBlock.convertr   )elementrU   c                 C  s   t |dd}t| j|S )z#require the same dtype as ourselvesT)Zextract_numpy)rM   r   rf   )r\   r   r`   r`   ra   r   ^  s    zBlock._can_hold_element)r   rU   c                 C  s*   z|j | j kW S  tk
r$   Y dS X dS )z
        Should we set self.values[indexer] = value inplace or do we need to cast?

        Parameters
        ----------
        value : np.ndarray or ExtensionArray

        Returns
        -------
        bool
        FN)rk   r   )r\   r   r`   r`   ra   should_stored  s    zBlock.should_storenanc                 K  s"   t | jf||d|}| |S )"convert to our native types format)na_repquoting)to_native_typesrf   r   )r\   r  r  r^   r   r`   r`   ra   r  w  s    zBlock.to_native_types)deepc                 C  s(   | j }|r| }t| || j| jdS )zcopy constructorr   )rf   r   r   r   rY   )r\   r  rf   r`   r`   ra   r   ~  s    z
Block.copyznpt.NDArray[np.bool_] | None)r   r   rU   c           
      C  sZ  | j }t|tr8|r| n|  }|j j||dd |gS | |sV|rL| gS |  gS |dkrjt||}| s|r|| gS |  gS | |r|r| n|  }t	|j || | j
r|dks|jddd}n|g}|S | jdks| jd dkr| |}|j||d|dS g }t|  D ]4\}}	|t| j|	||d|||d  d q|S dS )	z
        replace the to_replace value with value, possible to create new
        blocks here this is just a call to putmask.
        T)
to_replacer   r   NFr   r   rX   r   r  r   r   r   )rf   rx   rB   r   _replacer   missingmask_missinganyr7   	is_objectr   rY   rZ   r   replacer   r   r   r   )
r\   r  r   r   r   rf   r   r   rv   r   r`   r`   ra   r    sL    



		zBlock.replace)r   r   rU   c           	      C  sb   |  |s|r| gS |  gS t|}|r2| jn| j }t|||| | |}|jdddS )aP  
        Replace elements by the given value.

        Parameters
        ----------
        to_replace : object or pattern
            Scalar to replace or regular expression to match.
        value : object
            Replacement object.
        inplace : bool, default False
            Perform inplace modification.
        convert : bool, default True
            If true, try to coerce any object types to better types.
        mask : array-like of bool, optional
            True indicate corresponding element is ignored.

        Returns
        -------
        List[Block]
        Fr  )r   r   recompilerf   r>   r   r   )	r\   r  r   r   r   r   rxr   r   r`   r`   ra   _replace_regex  s    


zBlock._replace_regexzIterable[Any]zSequence[Any])src_list	dest_listr   regexrU   c              	     sp  j fddt||D }t|s:|r0gS  gS t|d }tjrrt   fdd|D }nfdd|D }dd |D }|rn g}t|D ]\}	\}
}|	|k}g }t|D ]\}}t|dkr||	 }n(||	 }t|t	rt
|||d  }|j|
|||d}|rZ|jrZtdd	 |D sZtd
d |D }|| q|}q|S )z:
        See BlockManager.replace_list docstring.
        c                   s"   g | ]\}}  |r||fqS r`   )r   )r   xyrm   r`   ra   r     s    
 z&Block.replace_list.<locals>.<listcomp>rX   c                   s    g | ]}t |d   dqS )r   )r  r   )r=   r   )r   r  rf   r`   ra   r     s   c                   s   g | ]}t  |d  qS )r   )r	  r
  r   r   r`   ra   r     s     c                 S  s   g | ]}t |qS r`   )r6   r   r  r`   r`   ra   r   $  s     )r  r   r   r   r  c                 s  s   | ]}|d kV  qd S ri   r`   r  r`   r`   ra   	<genexpr>=  s     z%Block.replace_list.<locals>.<genexpr>c                 S  s   g | ]}|j d ddqS )FTr  r   r   r`   r`   ra   r   @  s     )rf   zipr   r   r)   rk   r4   r   rx   ro   r   _replace_coercer  allr   r   )r\   r  r  r   r  pairsZsrc_lenmasksrbrv   srcdestr   Znew_rbZblk_numr   r   Zmibr   r`   )r   r  r\   rf   ra   replace_list  sL    



"zBlock.replace_list)r   r   r  rU   c                 C  sx   t ||r| j|||d|dS |dkrb| jttdd}|| krN|sN| }t|j|| |gS | j	||||dS dS )ai  
        Replace value corresponding to the given boolean array with another
        value.

        Parameters
        ----------
        to_replace : object or pattern
            Scalar to replace or regular expression to match.
        value : object
            Replacement object.
        mask : np.ndarray[bool]
            True indicate corresponding element is ignored.
        inplace : bool, default True
            Perform inplace modification.
        regex : bool, default False
            If true, perform regular expression substitution.

        Returns
        -------
        List[Block]
        F)r   r   r   Nr   r  )
r?   r  r   rq   rk   rS   r   r7   rf   r  )r\   r  r   r   r   r  r   r`   r`   ra   r  F  s(    
   zBlock._replace_coerce)argrU   c                 C  s   |S )zA
        For compatibility with 1D-only ExtensionArrays.
        r`   r\   r"  r`   r`   ra   _maybe_squeeze_argz  s    zBlock._maybe_squeeze_argc                 C  s   | j dk}t|tjr2|j | j kr2td| j  |dkrF| jrFtj}ttj| j}| 	|sp| 
|||S tt|ddr|}n
t|}|r|j}t||| t||rn2t|| j r|||< nt|t|| |}|||< | S )a  
        Attempt self.values[indexer] = value, possibly creating a new array.

        Parameters
        ----------
        indexer : tuple, list-like, array-like, slice, int
            The subset of self.values to set
        value : object
            The value being set

        Returns
        -------
        Block

        Notes
        -----
        `indexer` is a direct slice/positional indexer. `value` must
        be a compatible shape.
        r   zCannot set values with ndim > Nrk   )rY   rx   rq   rr   r   
is_numericr   r	   rf   r   r   setitemr&   getattrasarrayTrN   rO   rP   r:   r   )r\   r   r   	transposerf   Z	arr_valuer`   r`   ra   r&    s,    




zBlock.setitemc                 C  s~  |}t tj| j}t|j|\}}t|ttt	fr6t
|tjkrF| j}| js^t|| jr^| j}| |r|t|j|| | gS trt|d jdkr| || S |r| gS | jdks| jd dk rt|s| |||S t|j||j}| |gS t|tj}g }|  }	t|	D ]Z\}
}|}|rD|dd|
|
d f }|dd|
|
d f }|||}| | q|S dS )aV  
        putmask the data to the block; it is possible that we may create a
        new dtype of block

        Return the resulting block(s).

        Parameters
        ----------
        mask : np.ndarray[bool], SparseArray[bool], or BooleanArray
        new : a ndarray/object

        Returns
        -------
        List[Block]
        r   r   rX   N)!r	   rq   rr   rf   r;   r)  rx   r/   r1   r.   r   r   
no_defaultr   r  r3   rk   r   r9   r   r   ry   whererY   rZ   r(   r   putmaskr8   r   r   r   r   )r\   r   newZ	orig_maskrf   r   nvZis_arrayr   r   rv   r   nZsubmaskr   r`   r`   ra   r-    s>    

zBlock.putmaskc                 C  s,   t |dd\}}t| j|g}| j|ddS )z
        coerce the current block to a dtype compat for other
        we will return a block, possibly object, and not raise

        we can also safely try to coerce to the same dtype
        and will receive the same block
        T)Zpandas_dtypeFr   )r   r   rk   r   )r\   otherrk   _Z	new_dtyper`   r`   ra   r     s    
zBlock.coerce_to_target_dtypepadr   forwardzIndex | Nonez
int | Nonez
str | Nonez
Any | None)methodaxisindexr   r   limit_direction
limit_arear   coercer   rU   c                 K  s  t |d}| js$|r| gS |  gS | jrr| jdkrr| jd dkrr|dkrr| jt| j|||||||||	|
f|S zt	
|}W n tk
r   d }Y nX |d kr| jjdkr| gS |r| jn| j }ttj|}t	j|f|||||||d| | |}||g|
S )Nr   r   r   rX   f)r5  r6  r7  r   r8  r9  r   )r   rz   r   r  rY   rZ   r[   r   interpolater	  Zclean_fill_methodr   rk   ry   rf   r	   rq   rr   Zinterpolate_array_2dr   r   )r\   r5  r6  r7  r   r   r8  r9  r   r:  r   r^   r   datar   r`   r`   ra   r<    sT    
&
	
zBlock.interpolater6  r   rU   c                 C  s   | j }|tjkr| j}d}nd}tj|||||d}|dkrH|dkrHt|dkrV| j}t|j	| j	sp| 
||S | ||S dS )zQ
        Take values according to indexer and return them as a block.bb

        FT)r6  
allow_fillr   r   N)rf   r   r+  r   r   r@   r   r   r%   rk   r   r   )r\   r   r6  r   r   rf   r?  r   r`   r`   ra   r@   Z  s$    
    zBlock.take_ndrX   r0  r6  rU   c                 C  s    t j| j||d}| j|dgS )z'return block for the diff of the valuesr6  r   )r   diffrf   r   )r\   r0  r6  r   r`   r`   ra   rB    s    z
Block.diffperiodsr6  r   rU   c                 C  s6   t tj| j}t||\}}t||||}| |gS )z+shift the block by periods, possibly upcast)r	   rq   rr   rf   r    rA   r   r\   rD  r6  r   rf   r   r`   r`   ra   rA     s    zBlock.shiftc                 C  sL  |j | j kstt|tttfr$t| j dk}ttj| j	}|}|rJ|j
}t|| \}}|rf|  S |tjkrv| j}t|| jr| jtkr| j}| |s| |}|||}	| |	dS t|| |}
|
|k	r$t|rt|t|k rt| || td| }t|||
 nNt|rbt|tjsbt|| jd krbt||j}t | ||}| j!s| j dkr|r|j
}| "|gS | }|j d }|#|d}|j$dd}g }|| fD ]r}|% r|j&|' d |d}t(|| j}|j|jkr$t)j*dt+t, d	 | j"|j
| j-| d
}|.| q|S )a  
        evaluate the block; return result block(s) from the result

        Parameters
        ----------
        other : a ndarray/object
        cond : np.ndarray[bool], SparseArray[bool], or BooleanArray

        Returns
        -------
        List[Block]
        r   inferzThis should not be reached; call to np.where above is expected to raise ValueError. Please report a bug at github.com/pandas-dev/pandasr   rX   r   rA  zDowncasting integer-dtype results in .where is deprecated and will change in a future version. To retain the old behavior, explicitly cast the results to the desired dtype.r|   r   )/rY   r   rx   r/   r1   r.   r	   rq   rr   rf   r)  r;   r   r   r+  r   r3   rk   r   r   r   r,  r   r:   sumr(   r   r   r-  rZ   r   r   expressionsrz   r   Zswapaxesr  r  takeZnonzeror   r~   r   FutureWarningr   r   r   )r\   r1  condr*  rf   Z
orig_othericondr   r   r   Zaltr   r6  r   Zresult_blocksr   Ztakenrr   r`   r`   ra   r,    sr    







zBlock.wherenpt.NDArray[np.intp]npt.NDArray[np.bool_]new_placementneeds_maskingc           	      C  sP   |j | jj|d\}}|d}|j| }|| }t|}t||dg}||fS )a  
        Return a list of unstacked blocks of self

        Parameters
        ----------
        unstacker : reshape._Unstacker
        fill_value : int
            Only used in ExtensionBlock._unstack
        new_placement : np.ndarray[np.intp]
        allow_fill : bool
        needs_masking : np.ndarray[bool]

        Returns
        -------
        blocks : list of Block
            New blocks of unstacked values.
        mask : array-like of bool
            The mask of columns of `blocks` we should keep.
        r   r   rG  )Zget_new_valuesrf   r)  r  r   new_block_2d)	r\   	unstackerr   rR  rS  r   r   r   r   r`   r`   ra   _unstack  s     


zBlock._unstacklinearrQ   )qsr6  rU   c                 C  sV   | j dkst|dkstt|s&tt| jt|j|}t|dd}t	|| j
dS )a\  
        compute the quantiles of the

        Parameters
        ----------
        qs : Float64Index
            List of the quantiles to be computed.
        interpolation : str, default 'linear'
            Type of interpolation.
        axis : int, default 0
            Axis to compute.

        Returns
        -------
        Block
        r   rX   r   rG  )rY   r   r(   r<   rf   rq   r(  _valuesr   rU  r   )r\   rY  interpolationr6  r   r`   r`   ra   quantile&  s    zBlock.quantile)N)N)N)F)NFN)N)Fr   )TTTT)r   N)T)FN)FTN)FF)TF)
r3  r   NFNr4  NNFN)rX   )r   N)rX  r   )Fr   
__module____qualname____doc____annotations__	__slots__r%  r  r   rj   _validate_ndimr
   r   rn   propertyrt   rz   r   r   r   r   r   r   r   r   setterr   r   r   r   r   r   r   rZ   rk   r   r   r   r   r   r   r   r   r[   r   rc   r   r   r   r   r   r  r   r  r  r!  r  r$  r&  r-  r   r<  r   r+  r@   rB  rA   r,  rW  r\  r`   r`   r`   ra   rd      s  
	

 		     *	!    
  J   )  G  3AG          $F&h,   rd   c                   @  s   e Zd ZU dZded< ddddZdddd	Zd
dddZeddddZ	ddddddZ
ddddZdddZdS )EABackedBlockz>
    Mixin for Block subclasses backed by ExtensionArray.
    rD   rf   rV   rW   c              
   C  s  | j j}t|}| |}| |}|tjkr4| j}t|| \}}|rP|  S z|	||j}W n t
tfk
r
 } zt| t| jr| |}|jtkr ||| W Y JS t| trt| jtr΂ | |}|||}	| |	d W Y S  W 5 d }~X Y nX | |}
|
gS )NrF  )rf   r)  r6   r$  r   r+  r   r;   r   Z_wherer   r   _catch_deprecated_value_errorr'   rk   r   r   r,  rx   NDArrayBackedExtensionBlockr-   r   r   )r\   r1  rL  ZarrrM  r   r   errr   r   r   r`   r`   ra   r,  M  s6    








zEABackedBlock.wherec              
   C  s   t |}| j}| |}z||| W n ttfk
r } zxt| t| jrz| 	|}|jt
krf ||| W Y >S t| trt| jtr | 	|}||| W Y S  W 5 d}~X Y nX | gS )z+
        See Block.putmask.__doc__
        N)r6   rf   r$  Z_putmaskr   r   rf  r'   rk   r   r   r-  rx   rg  r-   )r\   r   r.  rf   rh  r   r`   r`   ra   r-  |  s&    





zEABackedBlock.putmaskr   c                 C  sD   | j || _ | j|| _z| j  W n tk
r>   Y nX dS )r   N)rf   r   r   r   r   r   r   r   r`   r`   ra   r     s    zEABackedBlock.deletec                 C  s   | j S ri   r   rm   r`   r`   ra   r     s    zEABackedBlock.array_valuesNr   r   r   c                 C  s*   | j }|tkr|t}t|| jS )zS
        return object dtype as boxed values, such as Timestamps/Timedelta
        )rf   r   r   rS   rq   r(  r   rZ   )r\   rk   rf   r`   r`   ra   r     s    
zEABackedBlock.get_valuesc                 C  s   t | jS ri   )rq   r(  rf   rm   r`   r`   ra   r     s    zEABackedBlock.values_for_jsonr3  r   Fc           	      K  sH   | j }|jdkr.|dkr.|jj|||dj}n|j|||d}| |S )Nr   r   )r   r5  r   )rf   rY   r)  r   r   )	r\   r5  r6  r   r   r   r^   rf   r   r`   r`   ra   r<    s
    zEABackedBlock.interpolate)N)r3  r   FNN)r   r]  r^  r_  r`  r,  r-  r   r   r   r   r   r<  r`   r`   r`   ra   re  F  s   
/(
         re  c                      s  e Zd ZU dZdZdZdZded< edddd	Z	d
dddZ
ddddZdd ZeddddZedd Zdd Zddejfddddd d!Zddd"d#Zed$d d%d&d'Zd9dd(d)d*d+Zd:ddd(d- fd.d/Zd;ddd0d(d1d2d3Zd4d5d6d7d8Z  ZS )<ExtensionBlocka  
    Block for holding extension types.

    Notes
    -----
    This holds all 3rd-party extension array types. It's also the immediate
    parent class for our internal extension types' blocks, CategoricalBlock.

    ExtensionArrays are limited to 1-D.
    FTrD   rf   r   rW   c                 C  s*   | j dkrt| jfS t| jt| jfS NrX   )rY   r   rf   r   rm   r`   r`   ra   rZ     s    
zExtensionBlock.shaper   r   c                 C  s   t |trh|\}}t|s4|dkr4t|  dn*t |tr^|td krRt|| j|g S | j| S |dkr~t|  d| jS d S )Nr   z only contains one item)rx   r   comZis_null_slice
IndexErrorr   r   rf   )r\   rv   colr   r`   r`   ra   r     s    	


zExtensionBlock.igetr   c                 C  s.   || _ z| j  W n tk
r(   Y nX d S ri   )rf   r   r   r   r   r`   r`   ra   r     s
    zExtensionBlock.set_inplacec                 C  sD   t |tjr@|j| jjd kr@|jd dks0t|dddf }|S )z@
        If necessary, squeeze a (N, 1) ndarray to (N,)
        rX   Nr   )rx   rq   rr   rY   rf   rZ   r   r#  r`   r`   ra   r$    s    z!ExtensionBlock._maybe_squeeze_argro   c                 C  s   dS )z,Extension arrays are never treated as views.Fr`   rm   r`   r`   ra   rt     s    zExtensionBlock.is_viewc                 C  s
   | j jjS ri   )rf   rk   Z_is_numericrm   r`   r`   ra   r%    s    zExtensionBlock.is_numericc                 C  s   |  |s| |||S t|trj|d }t|tjrj|jdkrj|jd dkrZt	d|dddf }t|tjt
fr|jdkr|jd dkst|dddf }n,t|tr|jd dkst|jdddj}t||| j || j|< | S )a7  
        Attempt self.values[indexer] = value, possibly creating a new array.

        This differs from Block.setitem by not allowing setitem to change
        the dtype of the Block.

        Parameters
        ----------
        indexer : tuple, list-like, array-like, slice, int
            The subset of self.values to set
        value : object
            The value being set

        Returns
        -------
        Block

        Notes
        -----
        `indexer` is a direct slice/positional indexer. `value` must
        be a compatible shape.
        r   r   rX   zPThis should not be reached. Please report a bug at github.com/pandas-dev/pandas/NrA  )r   r   r&  rx   r   rq   rr   rY   rZ   r   rD   r   r.   Z_ixsrZ  rN   rf   )r\   r   r   r`   r`   ra   r&     s&    



zExtensionBlock.setitemr   Nrg   r   rd   r>  c                 C  sP   |t jkrd}| jj||dd}| jdkr6|dkr6t|dkrD| j}| ||S )zN
        Take values according to indexer and return them as a block.
        NT)r   r?  rX   )r   r+  rf   rJ  rY   r   r   r   )r\   r   r6  r   r   r   r`   r`   ra   r@   W  s    

zExtensionBlock.take_ndc                 C  s   t |ts | jdkr |tdf}t |trzt|dkrz|d }t |tsRtd|td| }t|rp|d }n
td|| j| S )a  
        Return a slice of my values.

        Parameters
        ----------
        slicer : slice, ndarray[int], or a tuple of these
            Valid (non-reducing) indexer for self.values.

        Returns
        -------
        ExtensionArray
        r   Nr   z+invalid slicing for a 1-ndim ExtensionArrayrX   )rx   r   rY   r   r   r   rangerf   )r\   r   firstZnew_locsr`   r`   ra   r   r  s"    
 
 zExtensionBlock._slicer   r   c                 C  s    | j | }t| || j| jdS )zN
        Perform __getitem__-like specialized to slicing along index.
        r   )rf   r   r   rY   )r\   r   r   r`   r`   ra   getitem_block_index  s    
z"ExtensionBlock.getitem_block_indexrV   r   c                 C  s   | j j||d}| j|dgS )Nr   r   r   )rf   r   r   )r\   r   r   r   r   rf   r`   r`   ra   r     s    zExtensionBlock.fillnarX   r@  c                   s@   |dkr&|dkr&t  jt| jddS |dkr2d}t  ||S )Nr   rA  rX   )superrB  r   rf   )r\   r0  r6  	__class__r`   ra   rB    s
    zExtensionBlock.diffr   rC  c                 C  s   | j j||d}| |gS )z
        Shift the block by `periods`.

        Dispatches to underlying ExtensionArray and re-boxes in an
        ExtensionBlock.
        )rD  r   rf   rA   r   )r\   rD  r6  r   r   r`   r`   ra   rA     s    zExtensionBlock.shiftrO  rP  rQ  c                   sD   |j \}}|j| }|| } fddtt||D }||fS )Nc                   s<   g | ]4\}\}}t jj||  d t|ddqS ))r?  r   r   r   )r   rf   rJ  r   )r   rv   indicesZplacer   rS  r\   r`   ra   r     s   	
  z+ExtensionBlock._unstack.<locals>.<listcomp>)Zarange_resultr)  r   r  )r\   rV  r   rR  rS  r   r   r   r`   rw  ra   rW    s    

	zExtensionBlock._unstack)NFN)rX   )r   N)r   r]  r^  r_  rj   rb  r   r`  r   rZ   r   r   r$  rc  rt   r%  r&  r   r+  r@   r   r
   rp  r   rB  rA   rW  __classcell__r`   r`   rs  ra   ri    s:   

:(
     
ri  c                   @  s   e Zd ZU ded< dS )
NumpyBlockr   rf   N)r   r]  r^  r`  r`   r`   r`   ra   ry    s   
ry  c                   @  s   e Zd ZdZdZdS )NumericBlockr`   TN)r   r]  r^  ra  r%  r`   r`   r`   ra   rz    s   rz  c                   @  s   e Zd ZU dZded< eddddZedddd	Zd
d Z	dddddddZ
ddddddddZddddddZdS )rg  z8
    Block backed by an NDArrayBackedExtensionArray
    rI   rf   ro   rW   c                 C  s   t | jtj S ri   )rx   rk   rq   rm   r`   r`   ra   r     s    z(NDArrayBackedExtensionBlock.is_extensionc                 C  s   | j jjdk	S rp   )rf   _ndarrayrs   rm   r`   r`   ra   rt     s    z#NDArrayBackedExtensionBlock.is_viewc                 C  s>   |  |s| |||S | j}| jdkr2|j}|||< | S rj  )r   r   r&  rf   rY   r)  )r\   r   r   rf   r`   r`   ra   r&    s    

z#NDArrayBackedExtensionBlock.setitemr   rg   rV   r@  c                 C  s$   | j }||j||d }| |gS )a  
        1st discrete difference.

        Parameters
        ----------
        n : int
            Number of periods to diff.
        axis : int, default 0
            Axis to diff upon.

        Returns
        -------
        A list with a new Block.

        Notes
        -----
        The arguments here are mimicking shift so they are called correctly
        by apply.
        rA  )rf   rA   r   )r\   r0  r6  rf   r   r`   r`   ra   rB    s    z NDArrayBackedExtensionBlock.diffNr   rC  c                 C  s"   | j }|j|||d}| |gS )N)r   r6  ru  rE  r`   r`   ra   rA   ,  s    z!NDArrayBackedExtensionBlock.shiftFr   c                 C  sJ   |  |s,| jjdkr,| |||||S | jj||d}| j|dgS )Nr   rq  r   )r   rk   ry   r   r   rf   r   )r\   r   r   r   r   r   r`   r`   ra   r   1  s    
   z"NDArrayBackedExtensionBlock.fillna)r   )r   N)NFN)r   r]  r^  r_  r`  r   r   rc  rt   r&  rB  rA   r   r`   r`   r`   ra   rg    s   
     rg  	Exceptionr   )rh  rU   c                 C  s   t | trdt| kr dS )z
    We catch ValueError for now, but only a specific one raised by DatetimeArray
    which will no longer be raised in version.2.0.
    zTimezones don't matchN)rx   r   r   )rh  r`   r`   ra   rf  A  s    
rf  c                   @  s0   e Zd ZU dZdZdZded< dddd	Zd
S )DatetimeLikeBlockz*Block for datetime64[ns], timedelta64[ns].r`   FzDatetimeArray | TimedeltaArrayrf   r   rW   c                 C  s   | j jS ri   )rf   r{  rm   r`   r`   ra   r   T  s    z!DatetimeLikeBlock.values_for_jsonN)r   r]  r^  r_  ra  r%  r`  r   r`   r`   r`   ra   r}  M  s
   
r}  c                   @  s*   e Zd ZU dZded< dZdZdZdZdS )DatetimeTZBlockz0implement a datetime64 block with a tz attributerC   rf   r`   TFN)	r   r]  r^  r_  r`  ra  r   rb  rj   r`   r`   r`   ra   r~  Z  s   
r~  c                   @  sF   e Zd ZdZdZeddddddZeddddddd	d
dZdS )ObjectBlockr`   TFro   rV   r   c                 C  sr   | j dkstz|| j}W n tk
r:   |s2 g  Y S X t|tjsLt|j dksZt|dd}| |gS )z;
        For object-dtype, we operate column-wise.
        r   rX   r   )	rY   r   rf   r   rx   rq   rr   r   r   )r\   r   r   resr`   r`   ra   r   i  s    
zObjectBlock.reducer   c                 C  sB   | j }|jdkr|d }t|||||d}t|| j}| |gS )z
        attempt to cast any object types to better types return a copy of
        the block (if copy = True) by definition we ARE an ObjectBlock!!!!!
        r   r   )r   r   r   r   )rf   rY   r!   r   r   )r\   r   r   r   r   rf   r   r`   r`   ra   r   |  s    
zObjectBlock.convertN)F)TTTT)r   r]  r^  ra  r  rc   r   r   r`   r`   r`   ra   r  e  s       r  c                   @  s"   e Zd ZdZeddddZdS )CategoricalBlockr`   r   rW   c                 C  s   | j jS ri   r   rm   r`   r`   ra   rk     s    zCategoricalBlock.dtypeN)r   r]  r^  ra  rc  rk   r`   r`   r`   ra   r    s   r  r   )rf   rU   c                 C  sV   t | tjr0t| } t| jjtr0tj| t	d} t | t
tfrR| jdk	rR| d} | S )a:  
    Input validation for values passed to __init__. Ensure that
    any datetime64/timedelta64 dtypes are in nanoseconds.  Ensure
    that we do not have string dtypes.

    Parameters
    ----------
    values : np.ndarray or ExtensionArray

    Returns
    -------
    values : np.ndarray or ExtensionArray
    r   N)rx   rq   rr   rL   
issubclassrk   r   r   r   rS   rC   rH   freqZ
_with_freqr   r`   r`   ra   r     s    
r   r   r   c                 C  s~   | j }| j}t| trt}n^t| tr,t}nN|tkr:t}n@t| t	rJt
}n0t| trZt}n |dkrht}n|dkrvt}nt}|S )z
    Find the appropriate Block subclass to use for the given values and dtype.

    Parameters
    ----------
    dtype : numpy or pandas dtype

    Returns
    -------
    cls : class, subclass of Block
    )r   r   )r;  crv   rw   ru   )r   ry   rx   rJ   ri  r*   r  r   r~  r-   rg  r+   r}  rz  r  )rk   vtypery   clsr`   r`   ra   get_block_type  s$    



r  r   r   c                 C  s    t | j}t| } || d|dS )Nr   rY   r   )r  rk   r   )rf   r   klassr`   r`   ra   rU    s    
rU  rg   )rY   rU   c                C  s>   t |tst|}t| || t| j}t| } || ||dS )Nr  )rx   r   
check_ndimr  rk   r   )rf   r   rY   r  r`   r`   ra   r     s    

r   r   c                 C  s   | j |kr$td| j  d| dnvt| js~| j |krPtd| j  d| dt|t| krtdt|  dt| n|dkrt|d	krtd
dS )aV  
    ndim inference and validation.

    Validates that values.ndim and ndim are consistent.
    Validates that len(values) and len(placement) are consistent.

    Parameters
    ----------
    values : array-like
    placement : BlockPlacement
    ndim : int

    Raises
    ------
    ValueError : the number of dimensions do not match
    z0Wrong number of dimensions. values.ndim > ndim [z > ]z1Wrong number of dimensions. values.ndim != ndim [z != zWrong number of items passed z, placement implies r   rX   zneed to splitN)rY   r   r#   rk   r   )rf   r   rY   r`   r`   ra   r    s    


r  re   r   z3tuple[np.ndarray | ExtensionArray, DtypeObj | None])rf   rk   rY   rU   c                 C  s@   t | tr(|  } |r(|dkr(t| } t |tr8|j}| |fS )zL
    Ensure that we don't allow PandasArray / PandasDtype in internals.
    rX   )rx   r0   Zto_numpyrq   Z
atleast_2dr,   Znumpy_dtype)rf   rk   rY   r`   r`   ra   extract_pandas_array1  s    


r  rV   rW   c                 C  sf   |dkrg }t | trB| D ]$}t |tr4|| q|| qn t | tsXtt| ||  |S )z.return a new extended blocks, given the resultN)rx   listr   r   rd   r   r   )r   r   rN  r`   r`   ra   r   G  s    


r   rX   )rf   rY   rU   c                 C  s.   | j |k r*t| js*td| } | dd} | S )z:
    Reshape if possible to have values.ndim == ndim.
    z+np.ndarray | DatetimeArray | TimedeltaArrayrX   r   )rY   r#   rk   r	   r   )rf   rY   r`   r`   ra   r   W  s
    


r   r   .)r  r  float_formatdecimalr   c                K  s  t | tr"t| jjt| j|d} t| } t | tt	fr| j
dkrh| jf d|i|}|jtdd}|S g }tt| D ]8}| |ddf jf d|i|}||jtdd qxt|S t | trt| }	t| t}
||
|	< |
S | jjdkr|dkrN|dkrNt| }	|s&| t} ntj| d	d
} || |	< | jtdd} | S ddlm} || ||||dd}| }|jtdd}|S t| }	t|}| jtkr|s|r| t} | jj tdj  |k r| d| } ntj| d	d
} || |	< | jtdd} | S dS )r   rT  rX   r  Fr   Nr;  r  rS   r   r   )FloatArrayFormatter)r  r  r  r  Zfixed_widthZU1z<U)!rx   rB   r@   
categoriesrZ  r"   _codesrL   rC   rH   rY   Z_format_native_typesr   rS   rn  r   r   rq   ZvstackrD   r4   r(  rk   ry   r   r   Zpandas.io.formats.formatr  Zget_result_as_arrayr   Zword_lenr   itemsize)rf   r  r  r  r  r^   r   Zresults_convertedrv   r   r   r  	formatterr  r  r`   r`   ra   r  g  sj    


 



r  c                 C  s4   t | ttfr| tS t | ttfr,| jS | S dS )a+  
    The array that Series.values returns (public attribute).

    This has some historical constraints, and is overridden in block
    subclasses to return the correct array (e.g. period returns
    object ndarray and datetimetz a datetime64[ns] ndarray instead of
    proper extension array).
    N)rx   rG   rE   r   rS   rC   rH   _datar   r`   r`   ra   r     s
    	
r   )N)rX   )
__future__r   	functoolsr   r  typingr   r   r   r   r   r	   r
   r~   Znumpyrq   Zpandas._libsr   r   r   r   Zlibinternalsr   r   Zpandas._libs.internalsr   Zpandas._typingr   r   r   r   r   Zpandas.compatr   Zpandas.util._decoratorsr   Zpandas.util._exceptionsr   Zpandas.util._validatorsr   Zpandas.core.dtypes.castr   r   r   r   r   r   r    r!   Zpandas.core.dtypes.commonr"   r#   r$   r%   r&   r'   r(   r)   Zpandas.core.dtypes.dtypesr*   r+   r,   r-   Zpandas.core.dtypes.genericr.   r/   r0   r1   Zpandas.core.dtypes.inferencer2   Zpandas.core.dtypes.missingr3   r4   r5   Zpandas.core.algorithmscoreZ
algorithmsZpandas.core.array_algos.putmaskr6   r7   r8   r9   r:   r;   Z pandas.core.array_algos.quantiler<   Zpandas.core.array_algos.replacer=   r>   r?   Zpandas.core.array_algos.taker@   Z"pandas.core.array_algos.transformsrA   Zpandas.core.arraysrB   rC   rD   rE   rF   rG   rH   Zpandas.core.arrays._mixinsrI   Zpandas.core.arrays.sparserJ   Zpandas.core.baserK   Zpandas.core.commoncommonrk  Z#pandas.core.computation.expressionsZcomputationrI  Zpandas.core.constructionrL   rM   Zpandas.core.indexersrN   rO   rP   Zpandas.core.missingr	  ZpandasrQ   rR   rk   r   rc   rd   re  ri  ry  rz  ZNDArrayBackedBlockrg  rf  r}  r~  r  r  r   r  rU  r   r  r  r   r   r  r   r`   r`   r`   ra   <module>   s   $	(
(
 $	
         < 	  M4)*X