o
    ŀg                  
   @  s  U d dl mZ d dlZd dlmZmZ d dlZd dlmZmZm	Z	m
Z
 d dlZd dl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mZmZmZmZmZmZ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. d dl/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7 d dl8m9Z9m:Z: d dl;m<Z<m=Z=m>Z>m?Z? d dl@mAZAmBZBmCZC d dlDmEZEmFZFmGZGmHZI d dlJmKZK d dlLmMZMmNZN d dlOmPZP d dlQmRZR d dlSmT  mUZV d dlWmXZYmZZZm[Z[ d dl\m]Z] d dl^m_Z_m`Z` erd dlambZbmcZc d dldmeZemfZf e	e#ejgf Zhe	eeif Zji Zkdeld< dddd Zmd!ekd"< e+ekd" dd#dddend$d% G d&d deeMZod+d)d*ZpdS ),    )annotationsN)lelt)TYPE_CHECKINGLiteralUnionoverload)lib)VALID_CLOSEDIntervalIntervalMixinintervals_to_interval_bounds)NA)	ArrayLikeAxisIntDtypeFillnaOptionsIntervalClosedTypeNpDtypePositionalIndexerScalarIndexerSelfSequenceIndexerSortKindTimeArrayLikenpt)function)IntCastingNaNError)Appender)LossySetitemErrormaybe_upcast_numeric_to_64bit)is_float_dtypeis_integer_dtypeis_list_likeis_object_dtype	is_scalaris_string_dtypeneeds_i8_conversionpandas_dtype)CategoricalDtypeIntervalDtype)ABCDataFrameABCDatetimeIndexABCIntervalIndexABCPeriodIndex)is_valid_na_for_dtypeisnanotna)isintakeuniquevalue_counts_internal)ArrowExtensionArray)ExtensionArray_extension_array_shared_docs)DatetimeArray)TimedeltaArray)arrayensure_wrapped_if_datetimelikeextract_array)check_array_indexer)invalid_comparisonunpack_zerodim_and_defer)IteratorSequence)IndexSerieszdict[str, str]_interval_shared_docsIntervalArrayzarrays.IntervalArray )klassqualnamenamea  
%(summary)s

Parameters
----------
data : array-like (1-dimensional)
    Array-like (ndarray, :class:`DateTimeArray`, :class:`TimeDeltaArray`) containing
    Interval objects from which to build the %(klass)s.
closed : {'left', 'right', 'both', 'neither'}, default 'right'
    Whether the intervals are closed on the left-side, right-side, both or
    neither.
dtype : dtype or None, default None
    If None, dtype will be inferred.
copy : bool, default False
    Copy the input data.
%(name)sverify_integrity : bool, default True
    Verify that the %(klass)s is valid.

Attributes
----------
left
right
closed
mid
length
is_empty
is_non_overlapping_monotonic
%(extra_attributes)s
Methods
-------
from_arrays
from_tuples
from_breaks
contains
overlaps
set_closed
to_tuples
%(extra_methods)s
See Also
--------
Index : The base pandas Index type.
Interval : A bounded slice-like interval; the elements of an %(klass)s.
interval_range : Function to create a fixed frequency IntervalIndex.
cut : Bin values into discrete Intervals.
qcut : Bin values into equal-sized Intervals based on rank or sample quantiles.

Notes
-----
See the `user guide
<https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html#intervalindex>`__
for more.

%(examples)sclassz@Pandas array for interval data that are closed on the same side.a      Examples
    --------
    A new ``IntervalArray`` can be constructed directly from an array-like of
    ``Interval`` objects:

    >>> pd.arrays.IntervalArray([pd.Interval(0, 1), pd.Interval(1, 5)])
    <IntervalArray>
    [(0, 1], (1, 5]]
    Length: 2, dtype: interval[int64, right]

    It may also be constructed using one of the constructor
    methods: :meth:`IntervalArray.from_arrays`,
    :meth:`IntervalArray.from_breaks`, and :meth:`IntervalArray.from_tuples`.
    )rH   summaryrJ   extra_attributesextra_methodsexamplesc                      sT  e Zd ZU dZej ZZedddZ	de
d< de
d< d	e
d
< 				ddddZedddZe			ddddZedddddd Zedd$d%Zed&ed'< eeed' d d(ed)d* 			ddd+d,Zed-ed.< eeed. d d(ed/d* 			ddd0d1Zed2ed3< eeed3 d d(ed4d* 			ddd5d6Zedd8d9Zdd:d;Zedd<d=Zedd?d@ZeddAdBZddDdEZddFdGZeddKdLZ ed dNdLZ ddQdLZ ddRdSZ!dTdU Z"e#dVdWdX Z$e#dYdZd[ Z%e#d\d]d^ Z&e#d_d`da Z'e#dbdcdd Z(e#dedfdg Z)ddhdidjd fdpdqZ*dddrddvdwZ+dddrddxdyZ,ddddzd fddZ-	dd fddZ.dd	 fddZ/d
ddZ0edddZ1dddZ2dddZ3ddddZ4dddddddZ5dd Z6dd Z7dd Z8ddddZ9ddddZ:edddZ;edddZ<edddZ=edddZ>eded< eed d edd dd Z?edddZ@eded< eed d edd dddZAded< eeed eB d
ddZC	ddddƄZDdddȄZEedɡed< eed ded̡d͜ ddddЄZFdddԄZGdddلZHdddۄZIeeJd eB 	ddddZKeded< eed d edd dd ZLdddZMedddZNdddZOd ddZP  ZQS (!  rF   Treturn
Literal[1]c                 C  s   dS )N    selfrS   rS   O/var/www/html/myenv/lib/python3.10/site-packages/pandas/core/arrays/interval.pyndim      zIntervalArray.ndimIntervalSide_left_rightr*   _dtypeNFclosedIntervalClosedType | NonedtypeDtype | Nonecopyboolverify_integrityc           
      C  s   t |dd}t|| r|j}|j}|p|j}t|j|d}n@t|r/| j d| d}t	|t
|}t||d u d\}}}	|jtkrMt|}t|}|pP|	}| j|||||d\}}}|rh| j|||d | j|||dS )	NTextract_numpyr]   z5(...) must be called with a collection of some kind, z was passed)validate_closedr]   ra   r_   r_   )r=   
isinstancerZ   r[   r]   r*   r_   r%   __name__	TypeError _maybe_convert_platform_intervalr   objectr	   maybe_convert_objects_ensure_simple_new_inputs	_validate_simple_new)
clsdatar]   r_   ra   rc   leftrightmsginfer_closedrS   rS   rV   __new__   sD   




zIntervalArray.__new__ru   rv   r   c                 C  s    t | }||_||_||_|S N)r   ry   rZ   r[   r\   )rs   ru   rv   r_   resultrS   rS   rV   rr     s
   
zIntervalArray._simple_new0tuple[IntervalSide, IntervalSide, IntervalDtype]c                 C  s  ddl m} |||d}t|}|||d}t|}|du r&t|tr&|j}|p)d}|durgt|}t|trI|jdurH||j}||j}n	d| }t	||jdu r^t|j|}n	||jkrgt
dt|jrxt|jrx||j}nt|jrt|jr||j}t|t|krdt|j d	t|j d
}t
|t|jtst|jrd}t	|t|trd}t
|t|trt|jt|jkrd|j d|j d}t
|t|jr|j|jkr|j|j\}}	||}||	}t|}t|dd}t|}t|dd}t|tst|trn(t|d|}
t|
d|
j}
t|d|}t|d|j}|
durB|
|u rB| }t|j|d}|||fS )z;Ensure correctness of input parameters for cls._simple_new.r   )ensure_indexra   Nrv   z$dtype must be an IntervalDtype, got z*closed keyword does not match dtype.closedzmust not have differing left [z] and right [z] typeszIcategory, object, and string subtypes are not supported for IntervalArrayz:Period dtypes are not supported, use a PeriodIndex insteadz2left and right must have the same time zone, got 'z' and ''Trd   _ndarray_datarf   ) pandas.core.indexes.baser}   r    rj   r*   r]   r(   subtypeastyperl   
ValueErrorr!   r_   r"   typerk   r)   r&   r.   r,   strtzr'   unitr   _ensure_matching_resosr<   r=   r6   getattrbasera   )rs   ru   rv   r]   ra   r_   r}   rw   left_arr	right_arrlbaserbaserS   rS   rV   rp   &  s   







z'IntervalArray._ensure_simple_new_inputsr_   ra   c                C  s   | |||dS )Nr   rS   )rs   scalarsr_   ra   rS   rS   rV   _from_sequence  s   zIntervalArray._from_sequencevalues
np.ndarrayoriginalc                 C  s   | j ||jdS )Nri   )r   r_   )rs   r   r   rS   rS   rV   _from_factorized     zIntervalArray._from_factorizedac  
        Construct an %(klass)s from an array of splits.

        Parameters
        ----------
        breaks : array-like (1-dimensional)
            Left and right bounds for each interval.
        closed : {'left', 'right', 'both', 'neither'}, default 'right'
            Whether the intervals are closed on the left-side, right-side, both
            or neither.        %(name)s
        copy : bool, default False
            Copy the data.
        dtype : dtype or None, default None
            If None, dtype will be inferred.

        Returns
        -------
        %(klass)s

        See Also
        --------
        interval_range : Function to create a fixed frequency IntervalIndex.
        %(klass)s.from_arrays : Construct from a left and right array.
        %(klass)s.from_tuples : Construct from a sequence of tuples.

        %(examples)s        from_breaksrG   z        Examples
        --------
        >>> pd.arrays.IntervalArray.from_breaks([0, 1, 2, 3])
        <IntervalArray>
        [(0, 1], (1, 2], (2, 3]]
        Length: 3, dtype: interval[int64, right]
        )rH   rJ   rO   c                 C  s,   t |}| j|d d |dd  |||dS )NrR   ra   r_   )rm   from_arrays)rs   breaksr]   ra   r_   rS   rS   rV   r     s   $zIntervalArray.from_breaksaC  
        Construct from two arrays defining the left and right bounds.

        Parameters
        ----------
        left : array-like (1-dimensional)
            Left bounds for each interval.
        right : array-like (1-dimensional)
            Right bounds for each interval.
        closed : {'left', 'right', 'both', 'neither'}, default 'right'
            Whether the intervals are closed on the left-side, right-side, both
            or neither.        %(name)s
        copy : bool, default False
            Copy the data.
        dtype : dtype, optional
            If None, dtype will be inferred.

        Returns
        -------
        %(klass)s

        Raises
        ------
        ValueError
            When a value is missing in only one of `left` or `right`.
            When a value in `left` is greater than the corresponding value
            in `right`.

        See Also
        --------
        interval_range : Function to create a fixed frequency IntervalIndex.
        %(klass)s.from_breaks : Construct an %(klass)s from an array of
            splits.
        %(klass)s.from_tuples : Construct an %(klass)s from an
            array-like of tuples.

        Notes
        -----
        Each element of `left` must be less than or equal to the `right`
        element at the same position. If an element is missing, it must be
        missing in both `left` and `right`. A TypeError is raised when
        using an unsupported type for `left` or `right`. At the moment,
        'category', 'object', and 'string' subtypes are not supported.

        %(examples)s        r   z        Examples
        --------
        >>> pd.arrays.IntervalArray.from_arrays([0, 1, 2], [1, 2, 3])
        <IntervalArray>
        [(0, 1], (1, 2], (2, 3]]
        Length: 3, dtype: interval[int64, right]
        c                 C  sJ   t |}t |}| j|||||d\}}}| j|||d | j|||dS )Nrh   ri   )rm   rp   rq   rr   )rs   ru   rv   r]   ra   r_   rS   rS   rV   r     s   zIntervalArray.from_arraysa  
        Construct an %(klass)s from an array-like of tuples.

        Parameters
        ----------
        data : array-like (1-dimensional)
            Array of tuples.
        closed : {'left', 'right', 'both', 'neither'}, default 'right'
            Whether the intervals are closed on the left-side, right-side, both
            or neither.        %(name)s
        copy : bool, default False
            By-default copy the data, this is compat only and ignored.
        dtype : dtype or None, default None
            If None, dtype will be inferred.

        Returns
        -------
        %(klass)s

        See Also
        --------
        interval_range : Function to create a fixed frequency IntervalIndex.
        %(klass)s.from_arrays : Construct an %(klass)s from a left and
                                    right array.
        %(klass)s.from_breaks : Construct an %(klass)s from an array of
                                    splits.

        %(examples)s        from_tuplesz        Examples
        --------
        >>> pd.arrays.IntervalArray.from_tuples([(0, 1), (1, 2)])
        <IntervalArray>
        [(0, 1], (1, 2]]
        Length: 2, dtype: interval[int64, right]
        c                 C  s   t |r
g g }}n| }}|D ]T}t|ts!t|r!tj }}	n9| j}
z|\}}	W n/ tyB } z|
 d| }t||d }~w tyY } z|
 d| }t||d }~ww |	| |	|	 q| j
|||d|dS )Nz..from_tuples requires tuples of length 2, got z'.from_tuples received an invalid item, Fr   )lenrj   tupler0   npnanrk   r   rl   appendr   )rs   rt   r]   ra   r_   ru   rv   dlhsrhsrJ   errrw   rS   rS   rV   r   L  s*   


zIntervalArray.from_tuplesNonec                 C  s   t |tsd| }t|t|t|krd}t|t|}t|}||k s0d}t||| || k s@d}t|dS )z
        Verify that the IntervalArray is valid.

        Checks that

        * dtype is correct
        * left and right match lengths
        * left and right have the same missing values
        * left is always below right
        zinvalid dtype: z(left and right must have the same lengthzMmissing values must be missing in the same location both left and right sidesz+left side of interval must be <= right sideN)rj   r*   r   r   r1   all)rs   ru   rv   r_   rw   	left_mask
right_maskrS   rS   rV   rq   ~  s    

zIntervalArray._validatec                 C  s6   t |j| jd}| j|||d\}}}| j|||dS )a#  
        Return a new IntervalArray with the replacement attributes

        Parameters
        ----------
        left : Index
            Values to be used for the left-side of the intervals.
        right : Index
            Values to be used for the right-side of the intervals.
        rf   ri   )r*   r_   r]   rp   rr   rU   ru   rv   r_   rS   rS   rV   _shallow_copy  s   zIntervalArray._shallow_copyc                 C  s   | j S rz   )r\   rT   rS   rS   rV   r_     s   zIntervalArray.dtypeintc                 C  s   | j j| jj S rz   )ru   nbytesrv   rT   rS   rS   rV   r     r   zIntervalArray.nbytesc                 C     | j jS rz   )ru   sizerT   rS   rS   rV   r     s   zIntervalArray.sizerA   c                 C  s   t t| S rz   )iterr   asarrayrT   rS   rS   rV   __iter__  s   zIntervalArray.__iter__c                 C  
   t | jS rz   )r   rZ   rT   rS   rS   rV   __len__     
zIntervalArray.__len__keyr   IntervalOrNAc                 C     d S rz   rS   rU   r   rS   rS   rV   __getitem__  rX   zIntervalArray.__getitem__r   c                 C  r   rz   rS   r   rS   rS   rV   r     rX   r   Self | IntervalOrNAc                 C  sz   t | |}| j| }| j| }t|tjtfs)t|r"t|r"| j	S t
||| jS t|dkr4td| j||| jdS )NrR   z&multi-dimensional indexing not allowedri   )r>   rZ   r[   rj   r   ndarrayr7   r%   r0   _fill_valuer   r]   rW   r   rr   r_   )rU   r   ru   rv   rS   rS   rV   r     s   


c                 C  s0   |  |\}}t| |}|| j|< || j|< d S rz   )_validate_setitem_valuer>   rZ   r[   )rU   r   value
value_leftvalue_rightrS   rS   rV   __setitem__  s   

zIntervalArray.__setitem__c           
   	   C  sz  t |rt| t|krtdt|}n*t|ts?|tu r9ddlm} t	j
| jtd}t	j| jtd}|||S t| ||S t|trItd}n-t|jtsS|j}n#|jj}t|trv| j|jjkrit| ||S |jjj|jd|jjd}t|tr| j|jkrt| ||S t|tst| |}|tju r| j|jk| j|jk@ S |tj u r| j|jk| j|jkB S |tj!u r| j|jk| j|jk| j|jk@ B S |tj"u r| |k| |kB S |tj#u r| j|jk | j|jk| j|jk @ B S | |k| |k B S t$|st| ||S t	j%t| td}t&|D ]+\}}	z|| | |	||< W q t'y:   |	tu r6|(t)}t||< n Y qw |S )NzLengths must match to comparer   )BooleanArrayri   intervalT
allow_fill
fill_value)*r#   r   r   pd_arrayrj   r   r   pandas.core.arraysr   r   emptyshaperb   onesr?   r(   r_   r)   
categoriesr*   r]   _valuesr3   codes	_na_valuer   operatoreqrZ   ru   r[   rv   negtger   r$   zeros	enumeraterl   r   rn   )
rU   otheropr   arrmaskother_dtyper{   iobjrS   rS   rV   _cmp_method  sp   


















zIntervalArray._cmp_method__eq__c                 C     |  |tjS rz   )r   r   r   rU   r   rS   rS   rV   r   6     zIntervalArray.__eq____ne__c                 C  r   rz   )r   r   r   r   rS   rS   rV   r   :  r   zIntervalArray.__ne____gt__c                 C  r   rz   )r   r   r   r   rS   rS   rV   r   >  r   zIntervalArray.__gt____ge__c                 C  r   rz   )r   r   r   r   rS   rS   rV   r   B  r   zIntervalArray.__ge____lt__c                 C  r   rz   )r   r   r   r   rS   rS   rV   r   F  r   zIntervalArray.__lt____le__c                 C  r   rz   )r   r   r   r   rS   rS   rV   r   J  r   zIntervalArray.__le__	quicksortlast	ascendingkindna_positionr   r   r   r   r   c                  sN   t |d|}|r|dkr|dkrt| j| jfS t jd|||d|S )NrS   r   r   r   )nvvalidate_argsort_with_ascendingr   lexsortrv   ru   superargsort)rU   r   r   r   kwargs	__class__rS   rV   r   N  s   zIntervalArray.argsort)axisskipnar   AxisInt | Noner   c                C  Z   t || j t| s| jS |  }| r!|s| jS | |  }n| }| d }|| S )Nr   r   validate_minmax_axisrW   r   r   r0   anyr   rU   r   r   r   r   indexerrS   rS   rV   minb     zIntervalArray.minc                C  r   )Nr   r   r   rS   rS   rV   maxs  r  zIntervalArray.max)limit
limit_areara   methodr   r  
int | Noner  #Literal['inside', 'outside'] | Nonec                  s   t  j||||dS )N)r  r  r  ra   )r   _pad_or_backfill)rU   r  r  r  ra   r   rS   rV   r
    s   
zIntervalArray._pad_or_backfillc           	        s\   |du rt |durt j|||dS | |\}}| jj|d}| jj|d}| ||S )a  
        Fill NA/NaN values using the specified method.

        Parameters
        ----------
        value : scalar, dict, Series
            If a scalar value is passed it is used to fill all missing values.
            Alternatively, a Series or dict can be used to fill in different
            values for each index. The value should not be a list. The
            value(s) passed should be either Interval objects or NA/NaN.
        method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None
            (Not implemented yet for IntervalArray)
            Method to use for filling holes in reindexed Series
        limit : int, default None
            (Not implemented yet for IntervalArray)
            If method is specified, this is the maximum number of consecutive
            NaN values to forward/backward fill. In other words, if there is
            a gap with more than this number of consecutive NaNs, it will only
            be partially filled. If method is not specified, this is the
            maximum number of entries along the entire axis where NaNs will be
            filled.
        copy : bool, default True
            Whether to make a copy of the data before filling. If False, then
            the original should be modified and no new memory should be allocated.
            For ExtensionArray subclasses that cannot do this, it is at the
            author's discretion whether to ignore "copy=False" or to raise.

        Returns
        -------
        filled : IntervalArray with NA/NaN filled
        FN)r   r  r  )r   )NotImplementedErrorr   fillna_validate_scalarru   rv   r   )	rU   r   r  r  ra   r   r   ru   rv   r   rS   rV   r    s   "zIntervalArray.fillnac              
     sH  ddl m} |durt|}t|tr||| jkr |r|  S | S t| jjr9t	|jr9d| j d| d}t
|z|| jdd|j}|| jdd|j}W n$ tyY     t
tfyu } zd| j d| d}t
||d}~ww | ||S z	t j||dW S  t
tfy } zd	t| j d
| }t
||d}~ww )a(  
        Cast to an ExtensionArray or NumPy array with dtype 'dtype'.

        Parameters
        ----------
        dtype : str or dtype
            Typecode or data-type to which the array is cast.

        copy : bool, default True
            Whether to copy the data, even if not necessary. If False,
            a copy is made only if the old dtype does not match the
            new dtype.

        Returns
        -------
        array : ExtensionArray or ndarray
            ExtensionArray or NumPy ndarray with 'dtype' for its dtype.
        r   rC   NzCannot convert z to z; subtypes are incompatibleFr~   zCannot cast z
 to dtype )pandasrC   r(   rj   r*   r_   ra   r!   r   r'   rl   rZ   r   r[   r   r   r   r   r   rk   )rU   r_   ra   rC   rw   new_left	new_rightr   r   rS   rV   r     s>   



zIntervalArray.astypec                 C  s@   t | t |kr
dS t| j|jko| j|jo| j|jS )NF)r   rb   r]   ru   equalsrv   r   rS   rS   rV   r    s   zIntervalArray.equals	to_concatSequence[IntervalArray]c                 C  sx   dd |D }t |dkrtd| }tdd |D }tdd |D }| j|||d\}}}| j|||d	S )
z
        Concatenate multiple IntervalArray

        Parameters
        ----------
        to_concat : sequence of IntervalArray

        Returns
        -------
        IntervalArray
        c                 S  s   h | ]}|j qS rS   rf   .0r   rS   rS   rV   	<setcomp>      z2IntervalArray._concat_same_type.<locals>.<setcomp>rR   z.Intervals must all be closed on the same side.c                 S     g | ]}|j qS rS   )ru   r  rS   rS   rV   
<listcomp>  r  z3IntervalArray._concat_same_type.<locals>.<listcomp>c                 S  r  rS   )rv   r  rS   rS   rV   r    r  rf   ri   )r   r   popr   concatenaterp   rr   )rs   r  
closed_setr]   ru   rv   r_   rS   rS   rV   _concat_same_type  s   zIntervalArray._concat_same_typec                 C  s*   | j  }| j }| j}| j|||dS )zd
        Return a copy of the array.

        Returns
        -------
        IntervalArray
        ri   )rZ   ra   r[   r_   rr   r   rS   rS   rV   ra     s   

zIntervalArray.copyc                 C  r   rz   )r0   rZ   rT   rS   rS   rV   r0   ,  r   zIntervalArray.isnarR   periodsr   rn   c                 C  s   t | r|dkr|  S | | tt|t | }t|r7ddlm} || jddj	}t
|g|d  }n| j|g| | jd}|dkrP|}| d |  }n
| t|d  }|}| ||gS )Nr   r  Fr~   rR   ri   )r   ra   r  r  absr0   r  rC   rZ   r   rF   r   r   r_   r  )rU   r  r   	empty_lenrC   r   abrS   rS   rV   shift/  s   
zIntervalArray.shift)r   r   r   r   c          
      K  sV   t d| | }}|r| |\}}t| j|||d}t| j|||d}	| ||	S )am  
        Take elements from the IntervalArray.

        Parameters
        ----------
        indices : sequence of integers
            Indices to be taken.

        allow_fill : bool, default False
            How to handle negative values in `indices`.

            * False: negative values in `indices` indicate positional indices
              from the right (the default). This is similar to
              :func:`numpy.take`.

            * True: negative values in `indices` indicate
              missing values. These values are set to `fill_value`. Any other
              other negative values raise a ``ValueError``.

        fill_value : Interval or NA, optional
            Fill value to use for NA-indices when `allow_fill` is True.
            This may be ``None``, in which case the default NA value for
            the type, ``self.dtype.na_value``, is used.

            For many ExtensionArrays, there will be two representations of
            `fill_value`: a user-facing "boxed" scalar, and a low-level
            physical NA value. `fill_value` should be the user-facing version,
            and the implementation should handle translating that to the
            physical version for processing the take if necessary.

        axis : any, default None
            Present for compat with IntervalIndex; does nothing.

        Returns
        -------
        IntervalArray

        Raises
        ------
        IndexError
            When the indices are out of bounds for the array.
        ValueError
            When `indices` contains negative values other than ``-1``
            and `allow_fill` is True.
        rS   r   )r   validate_taker  r3   rZ   r[   r   )
rU   indicesr   r   r   r   	fill_left
fill_right	left_take
right_takerS   rS   rV   r3   K  s   6

zIntervalArray.takec              
   C  s   zt |}| j|dd |j|j}}W n ty- } zdt| d}t||d }~ww z| j| W ||fS  ttfyT } zdt| d}t||d }~ww )Nr   rJ   z('value' should be an interval type, got z	 instead.z2'value' should be a compatible interval type, got )rF   _check_closed_matchesru   rv   rl   r   _validate_fill_valuer   )rU   r   r;   r   r   r   rw   rS   rS   rV   _validate_listlike  s(   

z IntervalArray._validate_listlikec                 C  sX   t |tr| j|dd |j|j}}||fS t|| jjr(| jj }}||fS td)Nr   r+  z=can only insert Interval objects and NA into an IntervalArray)	rj   r   r,  ru   rv   r/   r_   r   rl   )rU   r   ru   rv   rS   rS   rV   r    s   
	zIntervalArray._validate_scalarc                 C  s   t || jjr| jj}t| jjrtd||}}||fS t|trA| j	|dd |j|j
}}| j| | j| ||fS | |S )Nz4Cannot set float NaN to integer-backed IntervalArrayr   r+  )r/   ru   r_   r   r"   r   rl   rj   r   r,  rv   r-  r.  )rU   r   r   r   rS   rS   rV   r     s   


z%IntervalArray._validate_setitem_valuedropnarD   c                 C  sP   t   t jddtd tt| |d}W d   |S 1 s!w   Y  |S )a2  
        Returns a Series containing counts of each interval.

        Parameters
        ----------
        dropna : bool, default True
            Don't include counts of NaN.

        Returns
        -------
        counts : Series

        See Also
        --------
        Series.value_counts
        ignorez<The behavior of value_counts with object-dtype is deprecated)category)r/  N)warningscatch_warningsfilterwarningsFutureWarningvalue_countsr   r   )rU   r/  r{   rS   rS   rV   r6    s   

		zIntervalArray.value_countsboxedc                 C  s   t S rz   )r   )rU   r7  rS   rS   rV   
_formatter  s   zIntervalArray._formatterrC   c                 C     ddl m} || jddS )a  
        Return the left endpoints of each Interval in the IntervalArray as an Index.

        Examples
        --------

        >>> interv_arr = pd.arrays.IntervalArray([pd.Interval(0, 1), pd.Interval(2, 5)])
        >>> interv_arr
        <IntervalArray>
        [(0, 1], (2, 5]]
        Length: 2, dtype: interval[int64, right]
        >>> interv_arr.left
        Index([0, 2], dtype='int64')
        r   r  Fr~   )r  rC   rZ   rU   rC   rS   rS   rV   ru        zIntervalArray.leftc                 C  r9  )a  
        Return the right endpoints of each Interval in the IntervalArray as an Index.

        Examples
        --------

        >>> interv_arr = pd.arrays.IntervalArray([pd.Interval(0, 1), pd.Interval(2, 5)])
        >>> interv_arr
        <IntervalArray>
        [(0, 1], (2, 5]]
        Length: 2, dtype: interval[int64, right]
        >>> interv_arr.right
        Index([1, 5], dtype='int64')
        r   r  Fr~   )r  rC   r[   r:  rS   rS   rV   rv     r;  zIntervalArray.rightc                 C  s   | j | j S )a  
        Return an Index with entries denoting the length of each Interval.

        Examples
        --------

        >>> interv_arr = pd.arrays.IntervalArray([pd.Interval(0, 1), pd.Interval(1, 5)])
        >>> interv_arr
        <IntervalArray>
        [(0, 1], (1, 5]]
        Length: 2, dtype: interval[int64, right]
        >>> interv_arr.length
        Index([1, 4], dtype='int64')
        )rv   ru   rT   rS   rS   rV   length  s   zIntervalArray.lengthc                 C  s6   z	d| j | j  W S  ty   | j d| j   Y S w )a  
        Return the midpoint of each Interval in the IntervalArray as an Index.

        Examples
        --------

        >>> interv_arr = pd.arrays.IntervalArray([pd.Interval(0, 1), pd.Interval(1, 5)])
        >>> interv_arr
        <IntervalArray>
        [(0, 1], (1, 5]]
        Length: 2, dtype: interval[int64, right]
        >>> interv_arr.mid
        Index([0.5, 3.0], dtype='float64')
        g      ?)ru   rv   rl   r<  rT   rS   rS   rV   mid-  s
   zIntervalArray.midaI  
        Check elementwise if an Interval overlaps the values in the %(klass)s.

        Two intervals overlap if they share a common point, including closed
        endpoints. Intervals that only have an open endpoint in common do not
        overlap.

        Parameters
        ----------
        other : %(klass)s
            Interval to check against for an overlap.

        Returns
        -------
        ndarray
            Boolean array positionally indicating where an overlap occurs.

        See Also
        --------
        Interval.overlaps : Check whether two Interval objects overlap.

        Examples
        --------
        %(examples)s
        >>> intervals.overlaps(pd.Interval(0.5, 1.5))
        array([ True,  True, False])

        Intervals that share closed endpoints overlap:

        >>> intervals.overlaps(pd.Interval(1, 3, closed='left'))
        array([ True,  True, True])

        Intervals that only have an open endpoint in common do not overlap:

        >>> intervals.overlaps(pd.Interval(1, 2, closed='right'))
        array([False,  True, False])
        overlapsz        >>> data = [(0, 1), (1, 3), (2, 4)]
        >>> intervals = pd.arrays.IntervalArray.from_tuples(data)
        >>> intervals
        <IntervalArray>
        [(0, 1], (1, 3], (2, 4]]
        Length: 3, dtype: interval[int64, right]
        )rH   rO   c                 C  sx   t |ttfr	tt |tsdt|j }t|| jr"|j	r"t
nt}|jr,| j	r,t
nt}|| j|j||j| j@ S )Nz#`other` must be Interval-like, got )rj   rF   r-   r  r   r   rk   rl   closed_leftclosed_rightr   r   ru   rv   )rU   r   rw   op1op2rS   rS   rV   r>  k  s   
zIntervalArray.overlapsr   c                 C  r   )a  
        String describing the inclusive side the intervals.

        Either ``left``, ``right``, ``both`` or ``neither``.

        Examples
        --------

        For arrays:

        >>> interv_arr = pd.arrays.IntervalArray([pd.Interval(0, 1), pd.Interval(1, 5)])
        >>> interv_arr
        <IntervalArray>
        [(0, 1], (1, 5]]
        Length: 2, dtype: interval[int64, right]
        >>> interv_arr.closed
        'right'

        For Interval Index:

        >>> interv_idx = pd.interval_range(start=0, end=2)
        >>> interv_idx
        IntervalIndex([(0, 1], (1, 2]], dtype='interval[int64, right]')
        >>> interv_idx.closed
        'right'
        )r_   r]   rT   rS   rS   rV   r]     s   zIntervalArray.closedaZ  
        Return an identical %(klass)s closed on the specified side.

        Parameters
        ----------
        closed : {'left', 'right', 'both', 'neither'}
            Whether the intervals are closed on the left-side, right-side, both
            or neither.

        Returns
        -------
        %(klass)s

        %(examples)s        
set_closedav          Examples
        --------
        >>> index = pd.arrays.IntervalArray.from_breaks(range(4))
        >>> index
        <IntervalArray>
        [(0, 1], (1, 2], (2, 3]]
        Length: 3, dtype: interval[int64, right]
        >>> index.set_closed('both')
        <IntervalArray>
        [[0, 1], [1, 2], [2, 3]]
        Length: 3, dtype: interval[int64, both]
        c                 C  sF   |t vrd| }t|| j| j}}t|j|d}| j|||dS )Nzinvalid option for 'closed': rf   ri   )r
   r   rZ   r[   r*   r_   rr   )rU   r]   rw   ru   rv   r_   rS   rS   rV   rC    s   
zIntervalArray.set_closedak  
        Return a boolean whether the %(klass)s is non-overlapping and monotonic.

        Non-overlapping means (no Intervals share points), and monotonic means
        either monotonic increasing or monotonic decreasing.

        Examples
        --------
        For arrays:

        >>> interv_arr = pd.arrays.IntervalArray([pd.Interval(0, 1), pd.Interval(1, 5)])
        >>> interv_arr
        <IntervalArray>
        [(0, 1], (1, 5]]
        Length: 2, dtype: interval[int64, right]
        >>> interv_arr.is_non_overlapping_monotonic
        True

        >>> interv_arr = pd.arrays.IntervalArray([pd.Interval(0, 1),
        ...                                       pd.Interval(-1, 0.1)])
        >>> interv_arr
        <IntervalArray>
        [(0.0, 1.0], (-1.0, 0.1]]
        Length: 2, dtype: interval[float64, right]
        >>> interv_arr.is_non_overlapping_monotonic
        False

        For Interval Index:

        >>> interv_idx = pd.interval_range(start=0, end=2)
        >>> interv_idx
        IntervalIndex([(0, 1], (1, 2]], dtype='interval[int64, right]')
        >>> interv_idx.is_non_overlapping_monotonic
        True

        >>> interv_idx = pd.interval_range(start=0, end=2, closed='both')
        >>> interv_idx
        IntervalIndex([[0, 1], [1, 2]], dtype='interval[int64, both]')
        >>> interv_idx.is_non_overlapping_monotonic
        False
        is_non_overlapping_monotonicc                 C  s   | j dkr't| jd d | jdd  k  p%| jd d | jdd  k S t| jd d | jdd  k pG| jd d | jdd  k S )Nbothr   rR   )r]   rb   r[   rZ   r   rT   rS   rS   rV   rD    s   
  z*IntervalArray.is_non_overlapping_monotonicNpDtype | Nonebool | Nonec           
      C  sj   | j }| j}|  }| j}tjt|td}t|D ]\}}	|| r(tj	||< qt
|	|| |||< q|S )zt
        Return the IntervalArray's data as a numpy array of Interval
        objects (with dtype='object')
        ri   )rZ   r[   r0   r]   r   r   r   rn   r   r   r   )
rU   r_   ra   ru   rv   r   r]   r{   r   
left_valuerS   rS   rV   	__array__"  s   zIntervalArray.__array__c           
   
   C  s^  ddl }ddlm} z	|| jj}W n ty* } ztd| jj d|d}~ww ||| j}|jj	|j
| j|dd|j
| j|ddgdd	gd
}|  }| rs|
|  d }	|jj|jt||	g|d|dgd}|dur||jr|S t||r||std| jj d|j d| j d|j d	ntd| d|j||S )z6
        Convert myself into a pyarrow Array.
        r   N)ArrowIntervalTypez"Conversion to arrow with subtype 'z' is not supportedT)r   from_pandasru   rv   )namesrR   )childrenzINot supported to convert IntervalArray to type with different 'subtype' (z vs z) and 'closed' (z) attributesz+Not supported to convert IntervalArray to 'z' type)pyarrow(pandas.core.arrays.arrow.extension_typesrJ  from_numpy_dtyper_   r   rl   r]   StructArrayr   r;   rZ   r[   r0   r   buffersfrom_buffersr   r   fieldr  storage_typerj   r7   from_storage)
rU   r   rN  rJ  r   r   interval_typestorage_arrayr   null_bitmaprS   rS   rV   __arrow_array__6  sb   


zIntervalArray.__arrow_array__am  
        Return an %(return_type)s of tuples of the form (left, right).

        Parameters
        ----------
        na_tuple : bool, default True
            If ``True``, return ``NA`` as a tuple ``(nan, nan)``. If ``False``,
            just return ``NA`` as ``nan``.

        Returns
        -------
        tuples: %(return_type)s
        %(examples)s        	to_tupleszFndarray (if self is IntervalArray) or Index (if self is IntervalIndex)aq  
         Examples
         --------
         For :class:`pandas.IntervalArray`:

         >>> idx = pd.arrays.IntervalArray.from_tuples([(0, 1), (1, 2)])
         >>> idx
         <IntervalArray>
         [(0, 1], (1, 2]]
         Length: 2, dtype: interval[int64, right]
         >>> idx.to_tuples()
         array([(0, 1), (1, 2)], dtype=object)

         For :class:`pandas.IntervalIndex`:

         >>> idx = pd.interval_range(start=0, end=2)
         >>> idx
         IntervalIndex([(0, 1], (1, 2]], dtype='interval[int64, right]')
         >>> idx.to_tuples()
         Index([(0, 1), (1, 2)], dtype='object')
         )return_typerO   na_tuplec                 C  s2   t t| j| j}|st|   |tj}|S rz   )	comasarray_tuplesafeziprZ   r[   r   wherer0   r   )rU   r]  tuplesrS   rS   rV   r[  {  s   !zIntervalArray.to_tuplesr   npt.NDArray[np.bool_]c                 C  s   |  |\}}t| jtjr)t| j|| t| jtjsJ t| j|| d S | j|| t| jtjr9J | j|| d S rz   )r   rj   rZ   r   r   putmaskr[   _putmask)rU   r   r   r   r   rS   rS   rV   re    s   zIntervalArray._putmasklocitemr   c                 C  s6   |  |\}}| j||}| j||}| ||S )ac  
        Return a new IntervalArray inserting new item at location. Follows
        Python numpy.insert semantics for negative values.  Only Interval
        objects and NA can be inserted into an IntervalIndex

        Parameters
        ----------
        loc : int
        item : Interval

        Returns
        -------
        IntervalArray
        )r  ru   insertrv   r   )rU   rf  rg  left_insertright_insertr  r  rS   rS   rV   rh    s   zIntervalArray.insertc                 C  sv   t | jtjrt| j|}t | jtjsJ t| j|}n| j|}t | jtjr.J | j|}| j||dS )Nru   rv   )rj   rZ   r   r   deleter[   r   )rU   rf  r  r  rS   rS   rV   rl    s   zIntervalArray.deleterepeatrepeatsint | Sequence[int]c                 C  s6   t dd|i | j|}| j|}| j||dS )NrS   r   rk  )r   validate_repeatru   rm  rv   r   )rU   rn  r   left_repeatright_repeatrS   rS   rV   rm    s   zIntervalArray.repeata  
        Check elementwise if the Intervals contain the value.

        Return a boolean mask whether the value is contained in the Intervals
        of the %(klass)s.

        Parameters
        ----------
        other : scalar
            The value to check whether it is contained in the Intervals.

        Returns
        -------
        boolean array

        See Also
        --------
        Interval.contains : Check whether Interval object contains value.
        %(klass)s.overlaps : Check if an Interval overlaps the values in the
            %(klass)s.

        Examples
        --------
        %(examples)s
        >>> intervals.contains(0.5)
        array([ True, False, False])
    containsz        >>> intervals = pd.arrays.IntervalArray.from_tuples([(0, 1), (1, 3), (2, 4)])
        >>> intervals
        <IntervalArray>
        [(0, 1], (1, 3], (2, 4]]
        Length: 3, dtype: interval[int64, right]
        c                 C  sH   t |tr	td| jr| j|k n| j|k| jr|| jk @ S || jk@ S )Nz*contains not implemented for two intervals)rj   r   r  	open_leftrZ   
open_rightr[   r   rS   rS   rV   rs    s   
zIntervalArray.containsr   c                 C  s   t |trA| j|jkrtj| jtdS | j|jkr-| j	d}|j	d}t
|| S t| jjt|jjA rAtj| jtdS t
| t|tS )Nri   
complex128)rj   rF   r]   r   r   r   rb   r_   	_combinedviewr2   ravelr'   ru   r   rn   )rU   r   ru   rv   rS   rS   rV   r2     s   
zIntervalArray.isinc                 C  sV   | j jdd}| jjdd}t|jr |j||gdd}|S tj||gdd}|S )Nr   rR   )r   )	ru   r   reshaperv   r'   r_   r  r   r  )rU   ru   rv   combrS   rS   rV   rw  -  s   
zIntervalArray._combinedcombinedc                 C  s   | ddd}| jj}t|rFt| jttfsJ t| jj	|dddf |d}t| j
ttfs5J t| j
j	|dddf |d}nt|tjsNJ |dddf  |}|dddf  |}| j||dS )	zY
        Create a new IntervalArray with our dtype from a 1D complex128 ndarray.
        i8r      Nr   ri   rR   rk  )rx  rz  rZ   r_   r'   rj   r9   r:   r   r   r[   r   r   )rU   r|  ncr_   r  r  rS   rS   rV   _from_combined=  s    "zIntervalArray._from_combinedc                 C  s6   t | jdd d df }|d d d f }| |S )Nrv  r   )r4   rw  rx  r  )rU   r  rS   rS   rV   r4   O  s
   
zIntervalArray.unique)rP   rQ   )NNFT)r]   r^   r_   r`   ra   rb   rc   rb   )ru   rY   rv   rY   r_   r*   rP   r   )NFN)r]   r^   ra   rb   r_   r`   rP   r|   )r_   r`   ra   rb   rP   r   )r   r   r   rF   rP   r   )rv   FN)r]   r^   ra   rb   r_   r`   rP   r   )r_   r*   rP   r   )rP   r   )rP   r*   )rP   r   )rP   rA   )r   r   rP   r   )r   r   rP   r   )r   r   rP   r   )rP   r   )r   rb   r   r   r   r   rP   r   )r   r   r   rb   rP   r   )
r  r   r  r  r  r	  ra   rb   rP   r   )NNNT)r  r  ra   rb   rP   r   )T)ra   rb   )rP   rb   )r  r  rP   r   )rP   r   )rR   N)r  r   r   rn   rP   rF   )r   rb   rP   r   )r/  rb   rP   rD   )F)r7  rb   )rP   rC   )rP   r   )r]   r   rP   r   )NN)r_   rF  ra   rG  rP   r   rz   )r]  rb   rP   r   )r   rc  rP   r   )rf  r   rg  r   rP   r   )rn  ro  r   r   rP   r   )r   r   rP   rc  )rP   rY   )r|  r   rP   rF   )rP   rF   )Rrk   
__module____qualname__can_hold_nar   r   r   r   propertyrW   __annotations__ry   classmethodrr   rp   r   r   textwrapdedentrE   r   r   r   r   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  ra   r0   r$  r3   r.  r  r   r6  r8  ru   rv   r<  r=  r>  r]   rC  _shared_docs_kwargsrD  rI  rZ  r[  re  rh  rl  r8   rm  rs  r2   rw  r  r4   __classcell__rS   rS   r   rV   rF      s  
 
3`	2! 


O





-=

 E (
,
4 	


rP   r   c                 C  s   t | ttfrt| dkrtjg tjdS t| rt | tr | S t t	| ddt
r/t| } nt| ds>t | tttfs>| S t| dd} t| ds`t| } | jjdv r`| jtjkr`| tj} | S )a  
    Try to do platform conversion, with special casing for IntervalArray.
    Wrapper around maybe_convert_platform that alters the default return
    dtype in certain cases to be compatible with IntervalArray.  For example,
    empty lists return with integer dtype instead of object dtype, which is
    prohibited for IntervalArray.

    Parameters
    ----------
    values : array-like

    Returns
    -------
    array
    r   ri   r_   NTrd   iu)rj   listr   r   r   r;   int64r#   r+   r   r)   r   hasattrranger=   r_   r   r   )r   rS   rS   rV   rm   Y  s   

rm   )rP   r   )q
__future__r   r   r   r   r  typingr   r   r   r   r2  numpyr   pandas._libsr	   pandas._libs.intervalr
   r   r   r   pandas._libs.missingr   pandas._typingr   r   r   r   r   r   r   r   r   r   r   r   r   pandas.compat.numpyr   r   pandas.errorsr   pandas.util._decoratorsr   pandas.core.dtypes.castr   r    pandas.core.dtypes.commonr!   r"   r#   r$   r%   r&   r'   r(   pandas.core.dtypes.dtypesr)   r*   pandas.core.dtypes.genericr+   r,   r-   r.   pandas.core.dtypes.missingr/   r0   r1   pandas.core.algorithmsr2   r3   r4   r5   r6  r   r6   pandas.core.arrays.baser7   r8   pandas.core.arrays.datetimesr9   pandas.core.arrays.timedeltasr:   pandas.core.commoncorecommonr^  pandas.core.constructionr;   r   r<   r=   pandas.core.indexersr>   pandas.core.opsr?   r@   collections.abcrA   rB   r  rC   rD   r   rY   floatr   rE   r  r  r  rF   rm   rS   rS   rS   rV   <module>   s    <(
	=             