o
    5c                     @  s  U d Z ddlmZ ddlZddlZddlmZmZmZ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 ddl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)m*Z*m+Z+ ddl,m-Z- ddl.m/Z/m0Z0m1Z1 ddl2m3Z3 ddl4m5Z5m6Z6m7Z7m8Z8 ddl9m:Z: ddl;m<Z<m=Z=m>Z> ddl?m@Z@ ddlAmBZBmCZCmDZD ddlEmFZFmGZGmHZHmIZImJZJmKZK ddlLmMZM ddlNmOZOmPZP erG dd ddZQddlmRZRmSZS i ZTdeUd< edddZVG dd dZWG dd  d ZXG d!d" d"eXZYdS )#z
An interface for extending pandas with custom arrays.

.. warning::

   This is an experimental API and subject to breaking changes
   without warning.
    )annotationsN)
TYPE_CHECKINGAnyCallableClassVarIteratorLiteralSequenceTypeVarcastoverload)lib)
	ArrayLike	AstypeArgDtypeFillnaOptionsPositionalIndexerScalarIndexerSequenceIndexerShapeTakeIndexernpt)set_function_name)functionAbstractMethodError)AppenderSubstitutioncache_readonlydeprecate_nonkeyword_arguments)find_stack_level)validate_bool_kwargvalidate_fillna_kwargsvalidate_insert_loc)maybe_cast_to_extension_array)is_dtype_equalis_list_like	is_scalarpandas_dtype)ExtensionDtype)ABCDataFrameABCIndex	ABCSeriesisna)	arraylikemissing	roperator)factorize_arrayisinmoderankresolve_na_sentinelunique)quantile_with_mask)
nargminmaxnargsortc                   @  s,   e Zd ZdddddZddddd	Zd
S )ExtensionArraySupportsAnyAllTskipnar=   boolreturnc                C     d S N selfr=   rB   rB   M/var/www/html/gps/gps/lib/python3.10/site-packages/pandas/core/arrays/base.pyany_      z ExtensionArraySupportsAnyAll.anyc                C  r@   rA   rB   rC   rB   rB   rE   allb   rG   z ExtensionArraySupportsAnyAll.allN)r=   r>   r?   r>   )__name__
__module____qualname__rF   rH   rB   rB   rB   rE   r;   ^   s    r;   ExtensionArray)NumpySorterNumpyValueArrayLikezdict[str, str]_extension_array_shared_docsExtensionArrayT)boundc                   @  s  e Zd ZU dZdZedddddd	Zeddddd
dZedd Ze	dddZ
e	dddZ
dddZ
ddd Zdd"d#Zdd%d&Zdd)d*Zdd-d.Zdd/d0Zdd1d2Zddejfdd8d9Zedd;d<Zedd>d?Zedd@dAZeddBdCZeddDdEZe	dddHdIZe	dddJdIZe	dddLdIZdddNdIZddPdQZeddRdSZddTdUZeddgdV	M	W	Xddd]d^Z ddd`daZ!dddbdcZ"			dddidjZ#ddkdlZ$dd dpdqZ%ddrdsZ&	t	ddd{d|Z'dd}d~Z(dddZ)dddZ*ejejfdddZ+de,d< e-d de.e,d 	ddddZ/dddd	ddZ0dddZ1dd
ddZ2dddZ3dddZ4ddddZ5dddZ6edddZ7ddddZ8edddZ9e:dddZ;dMddddZ<de=d< dddZ>dddÄZ?dddńZ@dddȄZAdddʄZBddd̄ZCddddMddМdddԄZDedddׄZEddd܄ZFdddd߄ZGdddZHdS (  rL   a%  
    Abstract base class for custom 1-D array types.

    pandas will recognize instances of this class as proper arrays
    with a custom type and will not attempt to coerce them to objects. They
    may be stored directly inside a :class:`DataFrame` or :class:`Series`.

    Attributes
    ----------
    dtype
    nbytes
    ndim
    shape

    Methods
    -------
    argsort
    astype
    copy
    dropna
    factorize
    fillna
    equals
    insert
    isin
    isna
    ravel
    repeat
    searchsorted
    shift
    take
    tolist
    unique
    view
    _concat_same_type
    _formatter
    _from_factorized
    _from_sequence
    _from_sequence_of_strings
    _reduce
    _values_for_argsort
    _values_for_factorize

    Notes
    -----
    The interface includes the following abstract methods that must be
    implemented by subclasses:

    * _from_sequence
    * _from_factorized
    * __getitem__
    * __len__
    * __eq__
    * dtype
    * nbytes
    * isna
    * take
    * copy
    * _concat_same_type

    A default repr displaying the type, (truncated) data, length,
    and dtype is provided. It can be customized or replaced by
    by overriding:

    * __repr__ : A default repr for the ExtensionArray.
    * _formatter : Print scalars inside a Series or DataFrame.

    Some methods require casting the ExtensionArray to an ndarray of Python
    objects with ``self.astype(object)``, which may be expensive. When
    performance is a concern, we highly recommend overriding the following
    methods:

    * fillna
    * dropna
    * unique
    * factorize / _values_for_factorize
    * argsort, argmax, argmin / _values_for_argsort
    * searchsorted

    The remaining methods implemented on this class should be performant,
    as they only compose abstract methods. Still, a more efficient
    implementation may be available, and these methods can be overridden.

    One can implement methods to handle array reductions.

    * _reduce

    One can implement methods to handle parsing from strings that will be used
    in methods such as ``pandas.io.parsers.read_csv``.

    * _from_sequence_of_strings

    This class does not inherit from 'abc.ABCMeta' for performance reasons.
    Methods and properties required by the interface raise
    ``pandas.errors.AbstractMethodError`` and no ``register`` method is
    provided for registering virtual subclasses.

    ExtensionArrays are limited to 1 dimension.

    They may be backed by none, one, or many NumPy arrays. For example,
    ``pandas.Categorical`` is an extension array backed by two arrays,
    one for codes and one for categories. An array of IPv6 address may
    be backed by a NumPy structured array with two fields, one for the
    lower 64 bits and one for the upper 64 bits. Or they may be backed
    by some other storage type, like Python lists. Pandas makes no
    assumptions on how the data are stored, just that it can be converted
    to a NumPy array.
    The ExtensionArray interface does not impose any rules on how this data
    is stored. However, currently, the backing data cannot be stored in
    attributes called ``.values`` or ``._values`` to ensure full compatibility
    with pandas internals. But other names as ``.data``, ``._data``,
    ``._items``, ... can be freely used.

    If implementing NumPy's ``__array_ufunc__`` interface, pandas expects
    that

    1. You defer by returning ``NotImplemented`` when any Series are present
       in `inputs`. Pandas will extract the arrays and call the ufunc again.
    2. You define a ``_HANDLED_TYPES`` tuple as an attribute on the class.
       Pandas inspect this to determine whether the ufunc is valid for the
       types present.

    See :ref:`extending.extension.ufunc` for more.

    By default, ExtensionArrays are not hashable.  Immutable subclasses may
    override this behavior.
    	extensionNFdtypecopyrT   Dtype | Nonec                C     t | )aN  
        Construct a new ExtensionArray from a sequence of scalars.

        Parameters
        ----------
        scalars : Sequence
            Each element will be an instance of the scalar type for this
            array, ``cls.dtype.type`` or be converted into this type in this method.
        dtype : dtype, optional
            Construct for this particular dtype. This should be a Dtype
            compatible with the ExtensionArray.
        copy : bool, default False
            If True, copy the underlying data.

        Returns
        -------
        ExtensionArray
        r   )clsscalarsrT   rU   rB   rB   rE   _from_sequence      zExtensionArray._from_sequencec                C  rW   )a   
        Construct a new ExtensionArray from a sequence of strings.

        Parameters
        ----------
        strings : Sequence
            Each element will be an instance of the scalar type for this
            array, ``cls.dtype.type``.
        dtype : dtype, optional
            Construct for this particular dtype. This should be a Dtype
            compatible with the ExtensionArray.
        copy : bool, default False
            If True, copy the underlying data.

        Returns
        -------
        ExtensionArray
        r   )rX   stringsrT   rU   rB   rB   rE   _from_sequence_of_strings  s   z(ExtensionArray._from_sequence_of_stringsc                 C  rW   )a  
        Reconstruct an ExtensionArray after factorization.

        Parameters
        ----------
        values : ndarray
            An integer ndarray with the factorized values.
        original : ExtensionArray
            The original ExtensionArray that factorize was called on.

        See Also
        --------
        factorize : Top-level factorize method that dispatches here.
        ExtensionArray.factorize : Encode the extension array as an enumerated type.
        r   )rX   valuesoriginalrB   rB   rE   _from_factorized'  s   zExtensionArray._from_factorizeditemr   r?   r   c                 C  r@   rA   rB   rD   ra   rB   rB   rE   __getitem__=     zExtensionArray.__getitem__rD   rP   r   c                 C  r@   rA   rB   rb   rB   rB   rE   rc   A  rd   r   ExtensionArrayT | Anyc                 C  rW   )an  
        Select a subset of self.

        Parameters
        ----------
        item : int, slice, or ndarray
            * int: The position in 'self' to get.

            * slice: A slice object, where 'start', 'stop', and 'step' are
              integers or None

            * ndarray: A 1-d boolean NumPy ndarray the same length as 'self'

            * list[int]:  A list of int

        Returns
        -------
        item : scalar or ExtensionArray

        Notes
        -----
        For scalar ``item``, return a scalar value suitable for the array's
        type. This should be an instance of ``self.dtype.type``.

        For slice ``key``, return an instance of ``ExtensionArray``, even
        if the slice is length 0 or 1.

        For a boolean mask, return an instance of ``ExtensionArray``, filtered
        to the values where ``item`` is True.
        r   rb   rB   rB   rE   rc   E  s   !keyint | slice | np.ndarrayvalueNonec                 C  s   t t|  d)a^  
        Set one or more values inplace.

        This method is not required to satisfy the pandas extension array
        interface.

        Parameters
        ----------
        key : int, ndarray, or slice
            When called from, e.g. ``Series.__setitem__``, ``key`` will be
            one of

            * scalar int
            * ndarray of integers.
            * boolean ndarray
            * slice object

        value : ExtensionDtype.type, Sequence[ExtensionDtype.type], or object
            value or values to be set of ``key``.

        Returns
        -------
        None
        z  does not implement __setitem__.)NotImplementedErrortype)rD   rf   rh   rB   rB   rE   __setitem__h  s   +zExtensionArray.__setitem__intc                 C  rW   )z\
        Length of this array

        Returns
        -------
        length : int
        r   rD   rB   rB   rE   __len__     zExtensionArray.__len__Iterator[Any]c                 c  s"    t t| D ]}| | V  qdS )z5
        Iterate over elements of the array.
        N)rangelen)rD   irB   rB   rE   __iter__  s   zExtensionArray.__iter__objectbool | np.bool_c                 C  sJ   t |rt|r| jsdS || jju st|| jjr| jS dS || k S )z,
        Return for `item in self`.
        F)	r'   r.   _can_hold_narT   na_value
isinstancerk   _hasnarF   rb   rB   rB   rE   __contains__  s   zExtensionArray.__contains__otherr   c                 C  rW   )zE
        Return for `self == other` (element-wise equality).
        r   rD   r}   rB   rB   rE   __eq__  s   
zExtensionArray.__eq__c                 C  s
   | |k S )zH
        Return for `self != other` (element-wise in-equality).
        rB   r~   rB   rB   rE   __ne__  s   
zExtensionArray.__ne__c                 K  sV   t | d}dt|jvr'| jdvr)| j}tjd| d| dtt d d S d S d S )N	factorizeuse_na_sentinel)TimelikeOpsDatetimeArrayTimedeltaArrayzThe `na_sentinel` argument of `zy.factorize` is deprecated. In the future, pandas will use the `use_na_sentinel` argument instead.  Add this argument to `zU.factorize` to be compatible with future versions of pandas and silence this warning.)
stacklevel)	getattrinspect	signature
parametersrI   warningswarnDeprecationWarningr    )rX   kwargsr   namerB   rB   rE   __init_subclass__  s   

z ExtensionArray.__init_subclass__npt.DTypeLike | NonerU   r>   ry   
np.ndarrayc                 C  s>   t j| |d}|s|tjur| }|tjur|||  < |S )aj  
        Convert to a NumPy ndarray.

        .. versionadded:: 1.0.0

        This is similar to :meth:`numpy.asarray`, but may provide additional control
        over how the conversion is done.

        Parameters
        ----------
        dtype : str or numpy.dtype, optional
            The dtype to pass to :meth:`numpy.asarray`.
        copy : bool, default False
            Whether to ensure that the returned value is a not a view on
            another array. Note that ``copy=False`` does not *ensure* that
            ``to_numpy()`` is no-copy. Rather, ``copy=True`` ensure that
            a copy is made, even if not strictly necessary.
        na_value : Any, optional
            The value to use for missing values. The default value depends
            on `dtype` and the type of the array.

        Returns
        -------
        numpy.ndarray
        rT   )npasarrayr   
no_defaultrU   r.   )rD   rT   rU   ry   resultrB   rB   rE   to_numpy  s   
zExtensionArray.to_numpyr)   c                 C  rW   )z2
        An instance of 'ExtensionDtype'.
        r   rn   rB   rB   rE   rT     s   zExtensionArray.dtyper   c                 C  s
   t | fS )z9
        Return a tuple of the array dimensions.
        )rs   rn   rB   rB   rE   shape  s   
zExtensionArray.shapec                 C  s   t | jS )z6
        The number of elements in the array.
        )r   prodr   rn   rB   rB   rE   size     zExtensionArray.sizec                 C  s   dS )zH
        Extension Arrays are only allowed to be 1-dimensional.
           rB   rn   rB   rB   rE   ndim#  s   zExtensionArray.ndimc                 C  rW   )zL
        The number of bytes needed to store this object in memory.
        r   rn   rB   rB   rE   nbytes*  s   zExtensionArray.nbytes.npt.DTypeLikec                 C  r@   rA   rB   rD   rT   rU   rB   rB   rE   astype7  rd   zExtensionArray.astypec                 C  r@   rA   rB   r   rB   rB   rE   r   ;  rd   r   c                 C  r@   rA   rB   r   rB   rB   rE   r   ?  rd   Tc                 C  sV   t |}t|| jr|s| S |  S t|tr#| }|j| ||dS tj	| ||dS )aW  
        Cast to a NumPy array or ExtensionArray with '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 : np.ndarray or ExtensionArray
            An ExtensionArray if dtype is ExtensionDtype,
            Otherwise a NumPy ndarray with 'dtype' for its dtype.
        rS   )
r(   r%   rT   rU   rz   r)   construct_array_typerZ   r   array)rD   rT   rU   rX   rB   rB   rE   r   C  s   
)np.ndarray | ExtensionArraySupportsAnyAllc                 C  rW   )a  
        A 1-D array indicating if each value is missing.

        Returns
        -------
        na_values : Union[np.ndarray, ExtensionArray]
            In most cases, this should return a NumPy ndarray. For
            exceptional cases like ``SparseArray``, where returning
            an ndarray would be expensive, an ExtensionArray may be
            returned.

        Notes
        -----
        If returning an ExtensionArray, then

        * ``na_values._is_boolean`` should be True
        * `na_values` should implement :func:`ExtensionArray._reduce`
        * ``na_values.any`` and ``na_values.all`` should be implemented
        r   rn   rB   rB   rE   r.   d  r[   zExtensionArray.isnac                 C  s   t |   S )z
        Equivalent to `self.isna().any()`.

        Some ExtensionArray subclasses may be able to optimize this check.
        )r>   r.   rF   rn   rB   rB   rE   r{   z  s   zExtensionArray._hasnac                 C  s
   t | S )a	  
        Return values for sorting.

        Returns
        -------
        ndarray
            The transformed values should maintain the ordering between values
            within the array.

        See Also
        --------
        ExtensionArray.argsort : Return the indices that would sort this array.

        Notes
        -----
        The caller is responsible for *not* modifying these values in-place, so
        it is safe for implementors to give views on `self`.

        Functions that use this (e.g. ExtensionArray.argsort) should ignore
        entries with missing values in the original array (according to `self.isna()`).
        This means that the corresponding entries in the returned array don't need to
        be modified to sort correctly.
        )r   r   rn   rB   rB   rE   _values_for_argsort  s   
z"ExtensionArray._values_for_argsort)versionallowed_args	quicksortlast	ascendingkindstrna_positionc              	   O  s2   t |||}|  }t||||t|  dS )a  
        Return the indices that would sort this array.

        Parameters
        ----------
        ascending : bool, default True
            Whether the indices should result in an ascending
            or descending sort.
        kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
            Sorting algorithm.
        *args, **kwargs:
            Passed through to :func:`numpy.argsort`.

        Returns
        -------
        np.ndarray[np.intp]
            Array of indices that sort ``self``. If NaN values are contained,
            NaN values are placed at the end.

        See Also
        --------
        numpy.argsort : Sorting implementation used internally.
        )r   r   r   mask)nvvalidate_argsort_with_ascendingr   r:   r   r   r.   )rD   r   r   r   argsr   r^   rB   rB   rE   argsort  s   %zExtensionArray.argsortr=   c                 C  "   t |d |s| jrtt| dS )aq  
        Return the index of minimum value.

        In case of multiple occurrences of the minimum value, the index
        corresponding to the first occurrence is returned.

        Parameters
        ----------
        skipna : bool, default True

        Returns
        -------
        int

        See Also
        --------
        ExtensionArray.argmax
        r=   argminr!   r{   rj   r9   rC   rB   rB   rE   r        


zExtensionArray.argminc                 C  r   )aq  
        Return the index of maximum value.

        In case of multiple occurrences of the maximum value, the index
        corresponding to the first occurrence is returned.

        Parameters
        ----------
        skipna : bool, default True

        Returns
        -------
        int

        See Also
        --------
        ExtensionArray.argmin
        r=   argmaxr   rC   rB   rB   rE   r     r   zExtensionArray.argmaxobject | ArrayLike | NonemethodFillnaOptions | Nonelimit
int | Nonec                 C  s   t ||\}}|  }t||t| }| rA|dur7t|}| t}||||d | j	|| j
d}|S |  }|||< |S |  }|S )a  
        Fill NA/NaN values using the specified method.

        Parameters
        ----------
        value : scalar, array-like
            If a scalar value is passed it is used to fill all missing values.
            Alternatively, an array-like 'value' can be given. It's expected
            that the array-like have the same length as 'self'.
        method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None
            Method to use for filling holes in reindexed Series
            pad / ffill: propagate last valid observation forward to next valid
            backfill / bfill: use NEXT valid observation to fill gap.
        limit : int, default None
            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.

        Returns
        -------
        ExtensionArray
            With NA/NaN filled.
        Nr   r   r   )r"   r.   r0   check_value_sizers   rF   get_fill_funcr   rv   rZ   rT   rU   )rD   rh   r   r   r   funcnpvalues
new_valuesrB   rB   rE   fillna  s"    


zExtensionArray.fillnac                 C  s   | |     S )zz
        Return ExtensionArray without NA values.

        Returns
        -------
        valid : ExtensionArray
        r-   rn   rB   rB   rE   dropna>  s   	zExtensionArray.dropnar   periods
fill_valuec                 C  s   t | r|dkr|  S t|r| jj}| j|gtt|t |  | jd}|dkr4|}| d|  }n
| t|d }|}| ||gS )a>  
        Shift values by desired number.

        Newly introduced missing values are filled with
        ``self.dtype.na_value``.

        Parameters
        ----------
        periods : int, default 1
            The number of periods to shift. Negative values are allowed
            for shifting backwards.

        fill_value : object, optional
            The scalar value to use for newly introduced missing values.
            The default is ``self.dtype.na_value``.

        Returns
        -------
        ExtensionArray
            Shifted.

        Notes
        -----
        If ``self`` is empty or ``periods`` is 0, a copy of ``self`` is
        returned.

        If ``periods > len(self)``, then an array of size
        len(self) is returned, with all values filled with
        ``self.dtype.na_value``.
        r   r   N)	rs   rU   r.   rT   ry   rZ   minabs_concat_same_type)rD   r   r   emptyabrB   rB   rE   shiftI  s   !zExtensionArray.shiftc                 C  s   t | t}| j|| jdS )z
        Compute the ExtensionArray of unique values.

        Returns
        -------
        uniques : ExtensionArray
        r   )r7   r   rv   rZ   rT   )rD   uniquesrB   rB   rE   r7   {  s   zExtensionArray.uniqueleft$NumpyValueArrayLike | ExtensionArraysideLiteral['left', 'right']sorterrM   npt.NDArray[np.intp] | np.intpc                 C  s.   |  t}t|tr| t}|j|||dS )a  
        Find indices where elements should be inserted to maintain order.

        Find the indices into a sorted array `self` (a) such that, if the
        corresponding elements in `value` were inserted before the indices,
        the order of `self` would be preserved.

        Assuming that `self` is sorted:

        ======  ================================
        `side`  returned index `i` satisfies
        ======  ================================
        left    ``self[i-1] < value <= self[i]``
        right   ``self[i-1] <= value < self[i]``
        ======  ================================

        Parameters
        ----------
        value : array-like, list or scalar
            Value(s) to insert into `self`.
        side : {'left', 'right'}, optional
            If 'left', the index of the first suitable location found is given.
            If 'right', return the last such index.  If there is no suitable
            index, return either 0 or N (where N is the length of `self`).
        sorter : 1-D array-like, optional
            Optional array of integer indices that sort array a into ascending
            order. They are typically the result of argsort.

        Returns
        -------
        array of ints or int
            If value is array-like, array of insertion points.
            If value is scalar, a single integer.

        See Also
        --------
        numpy.searchsorted : Similar method from NumPy.
        )r   r   )r   rv   rz   rL   searchsorted)rD   rh   r   r   arrrB   rB   rE   r     s   
1

zExtensionArray.searchsortedc                 C  s   t | t |kr
dS tt|}t| j|jsdS t| t|kr"dS | |k}t|tr0|d}|  | @ }t	||B 
 S )a  
        Return if another array is equivalent to this array.

        Equivalent means that both arrays have the same shape and dtype, and
        all values compare equal. Missing values in the same location are
        considered equal (in contrast with normal equality).

        Parameters
        ----------
        other : ExtensionArray
            Array to compare to this Array.

        Returns
        -------
        boolean
            Whether the arrays are equivalent.
        F)rk   r   rL   r%   rT   rs   rz   r   r.   r>   rH   )rD   r}   equal_valuesequal_narB   rB   rE   equals  s   


zExtensionArray.equalsnpt.NDArray[np.bool_]c                 C  s   t t| |S )a  
        Pointwise comparison for set containment in the given values.

        Roughly equivalent to `np.array([x in values for x in self])`

        Parameters
        ----------
        values : Sequence

        Returns
        -------
        np.ndarray[bool]
        )r3   r   r   )rD   r^   rB   rB   rE   r3     s   zExtensionArray.isintuple[np.ndarray, Any]c                 C  s   |  ttjfS )a  
        Return an array and missing value suitable for factorization.

        Returns
        -------
        values : ndarray

            An array suitable for factorization. This should maintain order
            and be a supported dtype (Float64, Int64, UInt64, String, Object).
            By default, the extension array is cast to object dtype.
        na_value : object
            The value in `values` to consider missing. This will be treated
            as NA in the factorization routines, so it will be coded as
            `na_sentinel` and not included in `uniques`. By default,
            ``np.nan`` is used.

        Notes
        -----
        The values returned by this method are also used in
        :func:`pandas.util.hash_pandas_object`.
        )r   rv   r   nanrn   rB   rB   rE   _values_for_factorize  s   z$ExtensionArray._values_for_factorizena_sentinelint | lib.NoDefaultr   bool | lib.NoDefault!tuple[np.ndarray, ExtensionArray]c           	      C  s<   t ||}|  \}}t|||d\}}| || }||fS )aj  
        Encode the extension array as an enumerated type.

        Parameters
        ----------
        na_sentinel : int, default -1
            Value to use in the `codes` array to indicate missing values.

            .. deprecated:: 1.5.0
                The na_sentinel argument is deprecated and
                will be removed in a future version of pandas. Specify use_na_sentinel
                as either True or False.

        use_na_sentinel : bool, default True
            If True, the sentinel -1 will be used for NaN values. If False,
            NaN values will be encoded as non-negative integers and will not drop the
            NaN from the uniques of the values.

            .. versionadded:: 1.5.0

        Returns
        -------
        codes : ndarray
            An integer NumPy array that's an indexer into the original
            ExtensionArray.
        uniques : ExtensionArray
            An ExtensionArray containing the unique values of `self`.

            .. note::

               uniques will *not* contain an entry for the NA value of
               the ExtensionArray if there are any missing values present
               in `self`.

        See Also
        --------
        factorize : Top-level factorize method that dispatches here.

        Notes
        -----
        :meth:`pandas.factorize` offers a `sort` keyword as well.
        )r   ry   )r6   r   r2   r`   )	rD   r   r   resolved_na_sentinelr   ry   codesr   
uniques_earB   rB   rE   r     s   
7
zExtensionArray.factorizeaL  
        Repeat elements of a %(klass)s.

        Returns a new %(klass)s where each element of the current %(klass)s
        is repeated consecutively a given number of times.

        Parameters
        ----------
        repeats : int or array of ints
            The number of repetitions for each element. This should be a
            non-negative integer. Repeating 0 times will return an empty
            %(klass)s.
        axis : None
            Must be ``None``. Has no effect but is accepted for compatibility
            with numpy.

        Returns
        -------
        repeated_array : %(klass)s
            Newly created %(klass)s with repeated elements.

        See Also
        --------
        Series.repeat : Equivalent function for Series.
        Index.repeat : Equivalent function for Index.
        numpy.repeat : Similar method for :class:`numpy.ndarray`.
        ExtensionArray.take : Take arbitrary positions.

        Examples
        --------
        >>> cat = pd.Categorical(['a', 'b', 'c'])
        >>> cat
        ['a', 'b', 'c']
        Categories (3, object): ['a', 'b', 'c']
        >>> cat.repeat(2)
        ['a', 'a', 'b', 'b', 'c', 'c']
        Categories (3, object): ['a', 'b', 'c']
        >>> cat.repeat([1, 2, 3])
        ['a', 'b', 'b', 'c', 'c', 'c']
        Categories (3, object): ['a', 'b', 'c']
        repeat)klassrepeatsint | Sequence[int]axisc                 C  s.   t dd|i tt| |}| |S )NrB   r   )r   validate_repeatr   arangers   r   take)rD   r   r   indrB   rB   rE   r   s  s   
zExtensionArray.repeat)
allow_fillr   indicesr   r   c                C  rW   )a  
        Take elements from an array.

        Parameters
        ----------
        indices : sequence of int or one-dimensional np.ndarray of int
            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 : any, 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.

        Returns
        -------
        ExtensionArray

        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.

        See Also
        --------
        numpy.take : Take elements from an array along an axis.
        api.extensions.take : Take elements from an array.

        Notes
        -----
        ExtensionArray.take is called by ``Series.__getitem__``, ``.loc``,
        ``iloc``, when `indices` is a sequence of values. Additionally,
        it's called by :meth:`Series.reindex`, or any other method
        that causes realignment, with a `fill_value`.

        Examples
        --------
        Here's an example implementation, which relies on casting the
        extension array to object dtype. This uses the helper method
        :func:`pandas.api.extensions.take`.

        .. code-block:: python

           def take(self, indices, allow_fill=False, fill_value=None):
               from pandas.core.algorithms import take

               # If the ExtensionArray is backed by an ndarray, then
               # just pass that here instead of coercing to object.
               data = self.astype(object)

               if allow_fill and fill_value is None:
                   fill_value = self.dtype.na_value

               # fill value should always be translated from the scalar
               # type for the array, to the physical storage type for
               # the data, before passing to take.

               result = take(data, indices, fill_value=fill_value,
                             allow_fill=allow_fill)
               return self._from_sequence(result, dtype=self.dtype)
        r   )rD   r   r   r   rB   rB   rE   r     s   ]zExtensionArray.takec                 C  rW   )ze
        Return a copy of the array.

        Returns
        -------
        ExtensionArray
        r   rn   rB   rB   rE   rU     rp   zExtensionArray.copyc                 C  s   |durt || dd S )a)  
        Return a view on the array.

        Parameters
        ----------
        dtype : str, np.dtype, or ExtensionDtype, optional
            Default None.

        Returns
        -------
        ExtensionArray or np.ndarray
            A view on the :class:`ExtensionArray`'s data.
        N)rj   )rD   rT   rB   rB   rE   view  s   zExtensionArray.viewc                 C  sf   | j dkr	|  S ddlm} || |  ddd}dt| j d}| | d	t|  d
| j	 S )Nr   r   format_object_summaryFindent_for_name, 
<z>
z	
Length: 	, dtype: )
r   _repr_2dpandas.io.formats.printingr   
_formatterrstriprk   rI   rs   rT   )rD   r   data
class_namerB   rB   rE   __repr__  s   

zExtensionArray.__repr__c                   sZ   ddl m   fddD }d|}dtj d}| d| d	j d
j S )Nr   r   c                   s$   g | ]} |  d ddqS )Fr   r   )r   r   .0xr   rD   rB   rE   
<listcomp>  s    z+ExtensionArray._repr_2d.<locals>.<listcomp>z,
r   >z
[
z

]
Shape: r   )r   r   joinrk   rI   r   rT   )rD   linesr   r   rB   r  rE   r     s   
zExtensionArray._repr_2dboxedCallable[[Any], str | None]c                 C  s   |rt S tS )aY  
        Formatting function for scalar values.

        This is used in the default '__repr__'. The returned formatting
        function receives instances of your scalar type.

        Parameters
        ----------
        boxed : bool, default False
            An indicated for whether or not your array is being printed
            within a Series, DataFrame, or Index (True), or just by
            itself (False). This may be useful if you want scalar values
            to appear differently within a Series versus on its own (e.g.
            quoted or not).

        Returns
        -------
        Callable[[Any], str]
            A callable that gets instances of the scalar type and
            returns a string. By default, :func:`repr` is used
            when ``boxed=False`` and :func:`str` is used when
            ``boxed=True``.
        )r   repr)rD   r  rB   rB   rE   r   "  s   zExtensionArray._formatteraxesc                 G  s   | dd S )z
        Return a transposed view on this array.

        Because ExtensionArrays are always 1D, this is a no-op.  It is included
        for compatibility with np.ndarray.
        NrB   )rD   r  rB   rB   rE   	transposeB  r   zExtensionArray.transposec                 C  s   |   S rA   )r  rn   rB   rB   rE   TK     zExtensionArray.TCorder"Literal['C', 'F', 'A', 'K'] | Nonec                 C  s   | S )ax  
        Return a flattened view on this array.

        Parameters
        ----------
        order : {None, 'C', 'F', 'A', 'K'}, default 'C'

        Returns
        -------
        ExtensionArray

        Notes
        -----
        - Because ExtensionArrays are 1D-only, this is a no-op.
        - The "order" argument is ignored, is for compatibility with NumPy.
        rB   )rD   r  rB   rB   rE   ravelO  s   zExtensionArray.ravelrX   type[ExtensionArrayT]	to_concatSequence[ExtensionArrayT]c                 C  rW   )z
        Concatenate multiple array of this dtype.

        Parameters
        ----------
        to_concat : sequence of this type

        Returns
        -------
        ExtensionArray
        r   )rX   r  rB   rB   rE   r   b  r[   z ExtensionArray._concat_same_typec                 C  s   | j jS rA   )rT   rx   rn   rB   rB   rE   rx   }  r  zExtensionArray._can_hold_nar<   r   c                K  sJ   t | |d}|du rtdt| j d| j d| d|dd|i|S )a  
        Return a scalar result of performing the reduction operation.

        Parameters
        ----------
        name : str
            Name of the function, supported values are:
            { any, all, min, max, sum, mean, median, prod,
            std, var, sem, kurt, skew }.
        skipna : bool, default True
            If True, skip NaN values.
        **kwargs
            Additional keyword arguments passed to the reduction function.
            Currently, `ddof` is the only supported kwarg.

        Returns
        -------
        scalar

        Raises
        ------
        TypeError : subclass does not define reductions
        N'z' with dtype z does not support reduction 'r=   rB   )r   	TypeErrorrk   rI   rT   )rD   r   r=   r   methrB   rB   rE   _reduce  s   zExtensionArray._reducezClassVar[None]__hash__listc                 C  s    | j dkrdd | D S t| S )z
        Return a list of the values.

        These are each a scalar type, which is a Python scalar
        (for str, int, float) or a pandas scalar
        (for Timestamp/Timedelta/Interval/Period)

        Returns
        -------
        list
        r   c                 S  s   g | ]}|  qS rB   )tolistr   rB   rB   rE   r    s    z)ExtensionArray.tolist.<locals>.<listcomp>)r   r  rn   rB   rB   rE   r    s   
zExtensionArray.tolistlocc                 C  s    t t t| |}| |S rA   )r   deleter   rs   r   )rD   r  indexerrB   rB   rE   r    s   
zExtensionArray.deletec                 C  sH   t |t| }t| j|g| jd}t| | d| || |d gS )a  
        Insert an item at the given position.

        Parameters
        ----------
        loc : int
        item : scalar-like

        Returns
        -------
        same type as self

        Notes
        -----
        This method should be both type and dtype-preserving.  If the item
        cannot be held in an array of this type/dtype, either ValueError or
        TypeError should be raised.

        The default implementation relies on _from_sequence to raise on invalid
        items.
        r   N)r#   rs   rk   rZ   rT   r   )rD   r  ra   item_arrrB   rB   rE   insert  s   $zExtensionArray.insertr   c                 C  s"   t |r	|| }n|}|| |< dS )a  
        Analogue to np.putmask(self, mask, value)

        Parameters
        ----------
        mask : np.ndarray[bool]
        value : scalar or listlike
            If listlike, must be arraylike with same length as self.

        Returns
        -------
        None

        Notes
        -----
        Unlike np.putmask, we do not repeat listlike values with mismatched length.
        'value' should either be a scalar or an arraylike with the same length
        as self.
        N)r&   )rD   r   rh   valrB   rB   rE   _putmask  s   
zExtensionArray._putmaskc                 C  s.   |   }t|r||  }n|}||| < |S )z
        Analogue to np.where(mask, self, value)

        Parameters
        ----------
        mask : np.ndarray[bool]
        value : scalar or listlike

        Returns
        -------
        same type as self
        )rU   r&   )rD   r   rh   r   r"  rB   rB   rE   _where  s   
zExtensionArray._wherec                 C  sF   t |}| t}|||| d | j|| jd}|| | |< dS )z
        Replace values in locations specified by 'mask' using pad or backfill.

        See also
        --------
        ExtensionArray.fillna
        r   r   N)r0   r   r   rv   rU   rZ   rT   )rD   r   r   r   r   r   r   rB   rB   rE   _fill_mask_inplace  s   


z!ExtensionArray._fill_mask_inplacer   averagekeepr   r   	na_optionr   pctr)  r*  c                C  s    |dkrt t| |||||dS )z*
        See Series.rank.__doc__.
        r   r(  )rj   r5   )rD   r   r   r)  r   r*  rB   rB   rE   _rank!  s   zExtensionArray._rankr   c                 C  sV   | j g |d}ttd|}|j|dd}t|| r!||jkr)td| d|S )z
        Create an ExtensionArray with the given shape and dtype.

        See also
        --------
        ExtensionDtype.empty
            ExtensionDtype.empty is the 'official' public version of this API.
        r   T)r   z5Default 'empty' implementation is invalid for dtype='r  )rZ   r   broadcast_tointpr   rz   rT   rj   )rX   r   rT   objtakerr   rB   rB   rE   _empty;  s   
zExtensionArray._emptyqsnpt.NDArray[np.float64]interpolationc                 C  s<   t |  }t | }t j}t|||||}t| |S )z
        Compute the quantiles of self for each quantile in `qs`.

        Parameters
        ----------
        qs : np.ndarray[float64]
        interpolation: str

        Returns
        -------
        same type as self
        )r   r   r.   r   r8   rk   rZ   )rD   r2  r4  r   r   r   
res_valuesrB   rB   rE   	_quantileR  s
   
zExtensionArray._quantiler   c                 C  s   t | |dS )aT  
        Returns the mode(s) of the ExtensionArray.

        Always returns `ExtensionArray` even if only one value.

        Parameters
        ----------
        dropna : bool, default True
            Don't consider counts of NA values.

        Returns
        -------
        same type as self
            Sorted, if possible.
        )r   )r4   )rD   r   rB   rB   rE   _modeh  s   zExtensionArray._modeufuncnp.ufuncc                 O  s   t dd |D rtS tj| ||g|R i |}|tur|S d|v r1tj| ||g|R i |S |dkrItj| ||g|R i |}|turI|S tj| ||g|R i |S )Nc                 s  s     | ]}t |tttfV  qd S rA   )rz   r,   r+   r*   )r  r}   rB   rB   rE   	<genexpr>}  s    
z1ExtensionArray.__array_ufunc__.<locals>.<genexpr>outreduce)rF   NotImplementedr/   !maybe_dispatch_ufunc_to_dunder_opdispatch_ufunc_with_outdispatch_reduction_ufuncdefault_array_ufunc)rD   r8  r   inputsr   r   rB   rB   rE   __array_ufunc__|  s@   zExtensionArray.__array_ufunc__)rT   rV   )ra   r   r?   r   )rD   rP   ra   r   r?   rP   )rD   rP   ra   r   r?   re   )rf   rg   rh   r   r?   ri   )r?   rm   )r?   rq   )ra   rv   r?   rw   )r}   r   r?   r   )r?   ri   )rT   r   rU   r>   ry   rv   r?   r   )r?   r)   )r?   r   ).)rT   r   rU   r>   r?   r   )rT   r)   rU   r>   r?   rL   )rT   r   rU   r>   r?   r   )T)r?   r   )r?   r>   )r?   r   )Tr   r   )r   r>   r   r   r   r   r?   r   )r=   r>   r?   rm   )NNN)
rD   rP   rh   r   r   r   r   r   r?   rP   )rD   rP   r?   rP   )r   N)r   rm   r   rv   r?   rL   )r   N)rh   r   r   r   r   rM   r?   r   )r}   rv   r?   r>   )r?   r   )r?   r   )r   r   r   r   r?   r   rA   )rD   rP   r   r   r   r   r?   rP   )
rD   rP   r   r   r   r>   r   r   r?   rP   )rT   rV   r?   r   )r?   r   )F)r  r>   r?   r	  )r  rm   r?   rL   )r?   rL   )r  )r  r  r?   rL   )rX   r  r  r  r?   rP   )r   r   r=   r>   )r?   r  )rD   rP   r  r   r?   rP   )rD   rP   r  rm   r?   rP   )r   r   r?   ri   )rD   rP   r   r   r?   rP   )r   r   r   r   r?   ri   )
r   rm   r   r   r)  r   r   r>   r*  r>   )r   r   rT   r)   )rD   rP   r2  r3  r4  r   r?   rP   )rD   rP   r   r>   r?   rP   )r8  r9  r   r   )IrI   rJ   rK   __doc___typclassmethodrZ   r]   r`   r   rc   rl   ro   ru   r|   r   r   r   r   r   r   propertyrT   r   r   r   r   r   r.   r{   r   r   r   r   r   r   r   r   r7   r   r   r3   r   r   rO   r   r   r   r   rU   r   r   r   r   r  r  r  r   r   rx   r  __annotations__r  r  r!  r#  r$  r%  r+  r1  r6  r7  rC  rB   rB   rB   rE   rL   p   s   
  


#
-






*
!
	/
7
26"C,

_
 	#c                   @  sX   e Zd ZdZedd Zedd Zedd Zedd	 Zed
d Z	edd Z
dS )ExtensionOpsMixinz
    A base class for linking the operators to their dunder names.

    .. note::

       You may want to set ``__array_priority__`` if you want your
       implementation to be called when involved in binary operations
       with NumPy arrays.
    c                 C  rW   rA   r   rX   oprB   rB   rE   _create_arithmetic_method  r  z+ExtensionOpsMixin._create_arithmetic_methodc                 C  sB  t | d| tj t | d| tj t | d| tj t | d| tj t | d| tj t | d| tj	 t | d| tj
 t | d| tj t | d	| tj t | d
| tj t | d| tj t | d| tj t | d| tj t | d| tj t | d| t t | d| tj d S )N__add____radd____sub____rsub____mul____rmul____pow____rpow____mod____rmod____floordiv____rfloordiv____truediv____rtruediv__
__divmod____rdivmod__)setattrrL  operatoraddr1   raddsubrsubmulrmulpowrpowmodrmodfloordiv	rfloordivtruedivrtruedivdivmodrdivmodrX   rB   rB   rE   _add_arithmetic_ops  s$   z%ExtensionOpsMixin._add_arithmetic_opsc                 C  rW   rA   r   rJ  rB   rB   rE   _create_comparison_method  r  z+ExtensionOpsMixin._create_comparison_methodc                 C  s|   t | d| tj t | d| tj t | d| tj t | d| tj t | d| tj t | d| tj d S )Nr   r   __lt____gt____le____ge__)	r]  rq  r^  eqneltgtlegero  rB   rB   rE   _add_comparison_ops     z%ExtensionOpsMixin._add_comparison_opsc                 C  rW   rA   r   rJ  rB   rB   rE   _create_logical_method  r  z(ExtensionOpsMixin._create_logical_methodc                 C  s|   t | d| tj t | d| tj t | d| tj t | d| tj t | d| tj t | d| tj	 d S )N__and____rand____or____ror____xor____rxor__)
r]  r~  r^  and_r1   rand_or_ror_xorrxorro  rB   rB   rE   _add_logical_ops  r}  z"ExtensionOpsMixin._add_logical_opsN)rI   rJ   rK   rD  rF  rL  rp  rq  r|  r~  r  rB   rB   rB   rE   rI    s    





rI  c                   @  s6   e Zd ZdZed
ddZedd Zedd	 ZdS )ExtensionScalarOpsMixina  
    A mixin for defining ops on an ExtensionArray.

    It is assumed that the underlying scalar objects have the operators
    already defined.

    Notes
    -----
    If you have defined a subclass MyExtensionArray(ExtensionArray), then
    use MyExtensionArray(ExtensionArray, ExtensionScalarOpsMixin) to
    get the arithmetic operators.  After the definition of MyExtensionArray,
    insert the lines

    MyExtensionArray._add_arithmetic_ops()
    MyExtensionArray._add_comparison_ops()

    to link the operators to your class.

    .. note::

       You may want to set ``__array_priority__`` if you want your
       implementation to be called when involved in binary operations
       with NumPy arrays.
    TNc                   s*    fdd}dj  d}t||| S )a  
        A class method that returns a method that will correspond to an
        operator for an ExtensionArray subclass, by dispatching to the
        relevant operator defined on the individual elements of the
        ExtensionArray.

        Parameters
        ----------
        op : function
            An operator that takes arguments op(a, b)
        coerce_to_dtype : bool, default True
            boolean indicating whether to attempt to convert
            the result to the underlying ExtensionArray dtype.
            If it's not possible to create a new ExtensionArray with the
            values, an ndarray is returned instead.

        Returns
        -------
        Callable[[Any, Any], Union[ndarray, ExtensionArray]]
            A method that can be bound to a class. When used, the method
            receives the two arguments, one of which is the instance of
            this class, and should return an ExtensionArray or an ndarray.

            Returning an ndarray may be necessary when the result of the
            `op` cannot be stored in the ExtensionArray. The dtype of the
            ndarray uses NumPy's normal inference rules.

        Examples
        --------
        Given an ExtensionArray subclass called MyExtensionArray, use

            __add__ = cls._create_method(operator.add)

        in the class definition of MyExtensionArray to create the operator
        for addition, that will be based on the operator implementation
        of the underlying elements of the ExtensionArray
        c           	        s    fdd}t |tttfrtS  }||}fddt||D } fdd}jdv r=t| \}}||||fS ||S )Nc                   s,   t | ts	t| r| }|S | gt  }|S rA   )rz   rL   r&   rs   )paramovaluesrn   rB   rE   convert_values  s
   zNExtensionScalarOpsMixin._create_method.<locals>._binop.<locals>.convert_valuesc                   s   g | ]	\}} ||qS rB   rB   )r  r   r   )rK  rB   rE   r  )  s    zJExtensionScalarOpsMixin._create_method.<locals>._binop.<locals>.<listcomp>c                   s@    rt t| }t|tst| }|S tj| d}|S )Nr   )r$   rk   rz   r   r   )r   res)coerce_to_dtyperesult_dtyperD   rB   rE   _maybe_convert+  s   
zNExtensionScalarOpsMixin._create_method.<locals>._binop.<locals>._maybe_convert>   rm  rn  )rz   r,   r+   r*   r=  ziprI   )	rD   r}   r  lvaluesrvaluesr  r  r   r   r  rK  r  rn   rE   _binop  s   
z6ExtensionScalarOpsMixin._create_method.<locals>._binop__)rI   r   )rX   rK  r  r  r  op_namerB   r  rE   _create_method  s   (&z&ExtensionScalarOpsMixin._create_methodc                 C  s
   |  |S rA   )r  rJ  rB   rB   rE   rL  A  s   
z1ExtensionScalarOpsMixin._create_arithmetic_methodc                 C  s   | j |dtdS )NF)r  r  )r  r>   rJ  rB   rB   rE   rq  E  s   z1ExtensionScalarOpsMixin._create_comparison_method)TN)rI   rJ   rK   rD  rF  r  rL  rq  rB   rB   rB   rE   r    s    P
r  )ZrD  
__future__r   r   r^  typingr   r   r   r   r   r   r	   r
   r   r   r   numpyr   pandas._libsr   pandas._typingr   r   r   r   r   r   r   r   r   r   pandas.compatr   pandas.compat.numpyr   r   pandas.errorsr   pandas.util._decoratorsr   r   r   r   pandas.util._exceptionsr    pandas.util._validatorsr!   r"   r#   pandas.core.dtypes.castr$   pandas.core.dtypes.commonr%   r&   r'   r(   pandas.core.dtypes.dtypesr)   pandas.core.dtypes.genericr*   r+   r,   pandas.core.dtypes.missingr.   pandas.corer/   r0   r1   pandas.core.algorithmsr2   r3   r4   r5   r6   r7    pandas.core.array_algos.quantiler8   pandas.core.sortingr9   r:   r;   rM   rN   rO   rH  rP   rL   rI  r  rB   rB   rB   rE   <module>   sX    00             3?