U
    ¿mœd]¡  ã                   @  sô  U d Z ddlmZ ddlZddlmZmZmZmZm	Z	m
Z
mZmZmZmZ ddlZddlmZ ddlmZ ddlmZmZmZmZmZmZmZ 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'm(Z( ddl)m*Z*m+Z+m,Z,m-Z-m.Z. ddl/m0Z0m1Z1m2Z2 ddl3m4Z4m5Z5 ddl6m7Z7m8Z8m9Z9 ddl:m;Z; ddl<m=Z= ddl>m?Z? ddl@mAZAmBZB e�rˆddlmCZCmDZDmEZEmFZF ddlGmHZHmIZImJZJ i ZKdeLd< dddddœZMeddd�ZNG dd„ de;ƒZOG d d!„ d!ƒZPG d"d#„ d#ee ƒZQG d$d„ de=ƒZRdS )%z.
Base and utility classes for pandas objects.
é    )ÚannotationsN)
ÚTYPE_CHECKINGÚAnyÚGenericÚHashableÚIteratorÚLiteralÚTypeVarÚcastÚfinalÚoverload)Úusing_copy_on_write)Úlib)ÚAxisÚAxisIntÚDtypeObjÚ
IndexLabelÚNDFrameTÚShapeÚnpt)ÚPYPY)Úfunction©ÚAbstractMethodError)Úcache_readonlyÚdoc)Úcan_hold_element)Úis_categorical_dtypeÚis_dict_likeÚis_extension_array_dtypeÚis_object_dtypeÚ	is_scalar)ÚABCDataFrameÚABCIndexÚ	ABCSeries)ÚisnaÚremove_na_arraylike)Ú
algorithmsÚnanopsÚops)ÚDirNamesMixin)ÚOpsMixin)ÚExtensionArray)Úensure_wrapped_if_datetimelikeÚextract_array)ÚDropKeepÚNumpySorterÚNumpyValueArrayLikeÚScalarLike_co)ÚCategoricalÚIndexÚSerieszdict[str, str]Ú_shared_docsÚIndexOpsMixinÚ )ÚklassZinplaceÚuniqueÚ
duplicatedÚ_T)Úboundc                      s\   e Zd ZU dZded< edd„ ƒZddœdd	„Zddddœdd„Zddœ‡ fdd„Z	‡  Z
S )ÚPandasObjectz/
    Baseclass for various pandas objects.
    zdict[str, Any]Ú_cachec                 C  s   t | ƒS )zJ
        Class constructor (for this class it's just `__class__`.
        )Útype©Úself© rC   úI/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/pandas/core/base.pyÚ_constructorl   s    zPandasObject._constructorÚstr©Úreturnc                 C  s
   t  | ¡S )zI
        Return a string representation for a particular object.
        )ÚobjectÚ__repr__rA   rC   rC   rD   rJ   s   s    zPandasObject.__repr__Nz
str | NoneÚNone©ÚkeyrH   c                 C  s4   t | dƒsdS |dkr"| j ¡  n| j |d¡ dS )zV
        Reset cached properties. If ``key`` is passed, only clears that key.
        r?   N)Úhasattrr?   ÚclearÚpop)rB   rM   rC   rC   rD   Ú_reset_cachez   s
    
zPandasObject._reset_cacheÚintc                   s<   t | ddƒ}|r2|dd�}tt|ƒr(|n| ¡ ƒS tƒ  ¡ S )zx
        Generates the total memory usage for an object that returns
        either a value or Series of values
        Úmemory_usageNT©Údeep)ÚgetattrrR   r!   ÚsumÚsuperÚ
__sizeof__)rB   rS   Zmem©Ú	__class__rC   rD   rY   …   s
    
zPandasObject.__sizeof__)N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__ÚpropertyrE   rJ   rQ   rY   Ú__classcell__rC   rC   rZ   rD   r>   d   s   

r>   c                   @  s.   e Zd ZdZddœdd„Zdddœdd	„Zd
S )ÚNoNewAttributesMixina„  
    Mixin which prevents adding new attributes.

    Prevents additional attributes via xxx.attribute = "something" after a
    call to `self.__freeze()`. Mainly used to prevent the user from using
    wrong attributes on an accessor (`Series.cat/.str/.dt`).

    If you really want to add a new attribute at a later time, you need to use
    `object.__setattr__(self, key, value)`.
    rK   rG   c                 C  s   t  | dd¡ dS )z9
        Prevents setting additional attributes.
        Ú__frozenTN)rI   Ú__setattr__rA   rC   rC   rD   Ú_freezeŸ   s    zNoNewAttributesMixin._freezerF   rL   c                 C  sT   t | ddƒrB|dksB|t| ƒjksBt | |d ƒd k	sBtd|› d�ƒ‚t | ||¡ d S )Nrd   Fr?   z"You cannot add any new attribute 'ú')rV   r@   Ú__dict__ÚAttributeErrorrI   re   )rB   rM   ÚvaluerC   rC   rD   re   ¦   s    ÿþýz NoNewAttributesMixin.__setattr__N)r\   r]   r^   r_   rf   re   rC   rC   rC   rD   rc   “   s   rc   c                   @  s¤   e Zd ZU dZded< dZded< ded< d	d
gZeeƒZe	e
dd„ ƒƒZedd„ ƒZe	eddœdd„ƒƒZe	edd„ ƒƒZdd„ Zdddœdd„Zdd„ ZeZdS )ÚSelectionMixinz‰
    mixin implementing the selection & aggregation interface on a group-like
    object sub-classes need to define: obj, exclusions
    r   ÚobjNzIndexLabel | NoneÚ
_selectionzfrozenset[Hashable]Ú
exclusionsr?   Ú__setstate__c                 C  s&   t | jtttttjfƒs | jgS | jS ©N)Ú
isinstancerm   ÚlistÚtupler$   r#   ÚnpÚndarrayrA   rC   rC   rD   Ú_selection_listÁ   s     ÿzSelectionMixin._selection_listc                 C  s,   | j d kst| jtƒr| jS | j| j  S d S rp   )rm   rq   rl   r$   rA   rC   rC   rD   Ú_selected_objÊ   s    zSelectionMixin._selected_objrR   rG   c                 C  s   | j jS rp   )rw   ÚndimrA   rC   rC   rD   rx   Ñ   s    zSelectionMixin.ndimc                 C  sV   t | jtƒr| jS | jd k	r*| j | j¡S t| jƒdkrL| jj| jddd�S | jS d S )Nr   é   T)ÚaxisZ
only_slice)	rq   rl   r$   rm   Z_getitem_nocopyrv   Úlenrn   Z
_drop_axisrA   rC   rC   rD   Ú_obj_with_exclusionsÖ   s    
z#SelectionMixin._obj_with_exclusionsc                 C  sÈ   | j d k	rtd| j › d�ƒ‚t|tttttjfƒr’t	| j
j |¡ƒt	t|ƒƒkr€tt|ƒ | j
j¡ƒ}tdt|ƒdd… › �ƒ‚| jt|ƒdd�S || j
krªtd|› �ƒ‚| j
| j}| j||d�S d S )	Nz
Column(s) z already selectedzColumns not found: ry   éÿÿÿÿé   ©rx   zColumn not found: )rm   Ú
IndexErrorrq   rr   rs   r$   r#   rt   ru   r{   rl   ÚcolumnsÚintersectionÚsetÚ
differenceÚKeyErrorrF   Ú_gotitemrx   )rB   rM   Úbad_keysrx   rC   rC   rD   Ú__getitem__è   s    

zSelectionMixin.__getitem__r   c                 C  s   t | ƒ‚dS )a  
        sub-classes to define
        return a sliced object

        Parameters
        ----------
        key : str / list of selections
        ndim : {1, 2}
            requested ndim of result
        subset : object, default None
            subset to act on
        Nr   )rB   rM   rx   ZsubsetrC   rC   rD   r†   ø   s    zSelectionMixin._gotitemc                 O  s   t | ƒ‚d S rp   r   )rB   ÚfuncÚargsÚkwargsrC   rC   rD   Ú	aggregate  s    zSelectionMixin.aggregate)N)r\   r]   r^   r_   r`   rm   Z_internal_namesrƒ   Z_internal_names_setr   ra   rv   r   rw   rx   r|   rˆ   r†   rŒ   ZaggrC   rC   rC   rD   rk   µ   s*   

rk   c                   @  s8  e Zd ZU dZdZedgƒZded< eddœdd	„ƒZ	ed
dœdd„ƒZ
edddœdd„ƒZeedd�Zeddœdd„ƒZddœdd„Zeddœdd„ƒZedd„ ƒZeddœdd„ƒZeddœd d!„ƒZed"dœd#d$„ƒZed%d&ejfd'd(d)d*d+œd,d-„ƒZeed(dœd.d/„ƒƒZdŒd1d(d2œd3d4„Zed5d6d7d8�d�d1d(dd9œd:d;„ƒZdŽd1d(d2œd<d=„Zeed6d5d>d8�d�d1d(dd9œd?d@„ƒZdAdB„ ZeZdCdœdDdE„Z e!d(dœdFdG„ƒZ"dHdœdIdJ„Z#dKd0d%d%dLœdMdNd(dOœdPdQ„Z$ed�dRdS„ƒZ%ed‘d(d(d(d(dTdUœdVdW„ƒZ&dXdY„ Z'ed’d(ddZœd[d\„ƒZ(ed(dœd]d^„ƒZ)ed(dœd_d`„ƒZ*ed(dœdadb„ƒZ+ed“d(ddcœddde„ƒZ,ee-j.dfdfdfe/ 0dg¡dh�d”d(d(didjœdkdl„ƒZ.dme1dn< e2d•dpdqdrdsdtœdudv„ƒZ3e2d–dwdqdrdxdtœdydv„ƒZ3ee1dn dzd{�d—d}dqdrd~dtœddv„ƒZ3d€d�œd‚d�œdƒd„„Z4ed˜d‚dHd…œd†d‡„ƒZ5dˆd‰„ Z6dŠd‹„ Z7d%S )™r7   zS
    Common ops mixin to support a unified interface / docs for Series / Index
    iè  Útolistzfrozenset[str]Ú_hidden_attrsr   rG   c                 C  s   t | ƒ‚d S rp   r   rA   rC   rC   rD   Údtype  s    zIndexOpsMixin.dtypezExtensionArray | np.ndarrayc                 C  s   t | ƒ‚d S rp   r   rA   rC   rC   rD   Ú_values  s    zIndexOpsMixin._valuesr<   )rB   rH   c                 O  s   t  ||¡ | S )zw
        Return the transpose, which is by definition self.

        Returns
        -------
        %(klass)s
        )ÚnvZvalidate_transpose)rB   rŠ   r‹   rC   rC   rD   Ú	transpose"  s    	zIndexOpsMixin.transposezD
        Return the transpose, which is by definition self.
        )r   r   c                 C  s   | j jS )z®
        Return a tuple of the shape of the underlying data.

        Examples
        --------
        >>> s = pd.Series([1, 2, 3])
        >>> s.shape
        (3,)
        )r�   ÚshaperA   rC   rC   rD   r“   5  s    zIndexOpsMixin.shaperR   c                 C  s   t | ƒ‚d S rp   r   rA   rC   rC   rD   Ú__len__B  s    zIndexOpsMixin.__len__z
Literal[1]c                 C  s   dS )zO
        Number of dimensions of the underlying data, by definition 1.
        ry   rC   rA   rC   rC   rD   rx   F  s    zIndexOpsMixin.ndimc                 C  s$   t | ƒdkrtt| ƒƒS tdƒ‚dS )a  
        Return the first element of the underlying data as a Python scalar.

        Returns
        -------
        scalar
            The first element of %(klass)s.

        Raises
        ------
        ValueError
            If the data is not length-1.
        ry   z6can only convert an array of size 1 to a Python scalarN)r{   ÚnextÚiterÚ
ValueErrorrA   rC   rC   rD   ÚitemM  s    zIndexOpsMixin.itemc                 C  s   | j jS )zD
        Return the number of bytes in the underlying data.
        )r�   ÚnbytesrA   rC   rC   rD   r™   `  s    zIndexOpsMixin.nbytesc                 C  s
   t | jƒS )zG
        Return the number of elements in the underlying data.
        )r{   r�   rA   rC   rC   rD   Úsizeg  s    zIndexOpsMixin.sizer,   c                 C  s   t | ƒ‚dS )aM  
        The ExtensionArray of the data backing this Series or Index.

        Returns
        -------
        ExtensionArray
            An ExtensionArray of the values stored within. For extension
            types, this is the actual array. For NumPy native types, this
            is a thin (no copy) wrapper around :class:`numpy.ndarray`.

            ``.array`` differs ``.values`` which may require converting the
            data to a different form.

        See Also
        --------
        Index.to_numpy : Similar method that always returns a NumPy array.
        Series.to_numpy : Similar method that always returns a NumPy array.

        Notes
        -----
        This table lays out the different array types for each extension
        dtype within pandas.

        ================== =============================
        dtype              array type
        ================== =============================
        category           Categorical
        period             PeriodArray
        interval           IntervalArray
        IntegerNA          IntegerArray
        string             StringArray
        boolean            BooleanArray
        datetime64[ns, tz] DatetimeArray
        ================== =============================

        For any 3rd-party extension types, the array type will be an
        ExtensionArray.

        For all remaining dtypes ``.array`` will be a
        :class:`arrays.NumpyExtensionArray` wrapping the actual ndarray
        stored within. If you absolutely need a NumPy array (possibly with
        copying / coercing data), then use :meth:`Series.to_numpy` instead.

        Examples
        --------
        For regular NumPy types like int, and float, a PandasArray
        is returned.

        >>> pd.Series([1, 2, 3]).array
        <PandasArray>
        [1, 2, 3]
        Length: 3, dtype: int64

        For extension types, like Categorical, the actual ExtensionArray
        is returned

        >>> ser = pd.Series(pd.Categorical(['a', 'b', 'a']))
        >>> ser.array
        ['a', 'b', 'a']
        Categories (2, object): ['a', 'b']
        Nr   rA   rC   rC   rD   Úarrayn  s    ?zIndexOpsMixin.arrayNFznpt.DTypeLike | NoneÚboolrI   z
np.ndarray)r�   ÚcopyÚna_valuerH   c                 K  s   t | jƒr$| jj|f||dœ|—ŽS |rHt| ¡ ƒd }td|› d�ƒ‚|tjk	rŽ| j	}t
||ƒsrtj||d�}n| ¡ }||t |  ¡ ¡< n| j	}tj||d�}|r°|tjksº|sütƒ rüt | j	dd… |dd… ¡rütƒ rô|sô| ¡ }d|j_n| ¡ }|S )	a«  
        A NumPy ndarray representing the values in this Series or Index.

        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 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.
        **kwargs
            Additional keywords passed through to the ``to_numpy`` method
            of the underlying array (for extension arrays).

        Returns
        -------
        numpy.ndarray

        See Also
        --------
        Series.array : Get the actual data stored within.
        Index.array : Get the actual data stored within.
        DataFrame.to_numpy : Similar method for DataFrame.

        Notes
        -----
        The returned array will be the same up to equality (values equal
        in `self` will be equal in the returned array; likewise for values
        that are not equal). When `self` contains an ExtensionArray, the
        dtype may be different. For example, for a category-dtype Series,
        ``to_numpy()`` will return a NumPy array and the categorical dtype
        will be lost.

        For NumPy dtypes, this will be a reference to the actual data stored
        in this Series or Index (assuming ``copy=False``). Modifying the result
        in place will modify the data stored in the Series or Index (not that
        we recommend doing that).

        For extension types, ``to_numpy()`` *may* require copying data and
        coercing the result to a NumPy type (possibly object), which may be
        expensive. When you need a no-copy reference to the underlying data,
        :attr:`Series.array` should be used instead.

        This table lays out the different dtypes and default return types of
        ``to_numpy()`` for various dtypes within pandas.

        ================== ================================
        dtype              array type
        ================== ================================
        category[T]        ndarray[T] (same dtype as input)
        period             ndarray[object] (Periods)
        interval           ndarray[object] (Intervals)
        IntegerNA          ndarray[object]
        datetime64[ns]     datetime64[ns]
        datetime64[ns, tz] ndarray[object] (Timestamps)
        ================== ================================

        Examples
        --------
        >>> ser = pd.Series(pd.Categorical(['a', 'b', 'a']))
        >>> ser.to_numpy()
        array(['a', 'b', 'a'], dtype=object)

        Specify the `dtype` to control how datetime-aware data is represented.
        Use ``dtype=object`` to return an ndarray of pandas :class:`Timestamp`
        objects, each with the correct ``tz``.

        >>> ser = pd.Series(pd.date_range('2000', periods=2, tz="CET"))
        >>> ser.to_numpy(dtype=object)
        array([Timestamp('2000-01-01 00:00:00+0100', tz='CET'),
               Timestamp('2000-01-02 00:00:00+0100', tz='CET')],
              dtype=object)

        Or ``dtype='datetime64[ns]'`` to return an ndarray of native
        datetime64 values. The values are converted to UTC and the timezone
        info is dropped.

        >>> ser.to_numpy(dtype="datetime64[ns]")
        ... # doctest: +ELLIPSIS
        array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00...'],
              dtype='datetime64[ns]')
        )r�   rž   r   z/to_numpy() got an unexpected keyword argument 'rg   ©r�   Nr~   F)r   r�   r›   Úto_numpyrr   ÚkeysÚ	TypeErrorr   Ú
no_defaultr�   r   rt   Zasarrayr�   Z
asanyarrayr%   r   Zshares_memoryÚviewÚflagsZ	writeable)rB   r�   r�   rž   r‹   r‡   ÚvaluesÚresultrC   rC   rD   r    ¯  s4    _

ÿ

ÿÿ

zIndexOpsMixin.to_numpyc                 C  s   | j  S rp   )rš   rA   rC   rC   rD   Úempty3  s    zIndexOpsMixin.emptyTzAxisInt | None)rz   Úskipnac                 O  s&   t  |¡ t  ||¡ tj| j|d�S )a  
        Return the maximum value of the Index.

        Parameters
        ----------
        axis : int, optional
            For compatibility with NumPy. Only 0 or None are allowed.
        skipna : bool, default True
            Exclude NA/null values when showing the result.
        *args, **kwargs
            Additional arguments and keywords for compatibility with NumPy.

        Returns
        -------
        scalar
            Maximum value.

        See Also
        --------
        Index.min : Return the minimum value in an Index.
        Series.max : Return the maximum value in a Series.
        DataFrame.max : Return the maximum values in a DataFrame.

        Examples
        --------
        >>> idx = pd.Index([3, 2, 1])
        >>> idx.max()
        3

        >>> idx = pd.Index(['c', 'b', 'a'])
        >>> idx.max()
        'c'

        For a MultiIndex, the maximum is determined lexicographically.

        >>> idx = pd.MultiIndex.from_product([('a', 'b'), (2, 1)])
        >>> idx.max()
        ('b', 2)
        ©r©   )r‘   Úvalidate_minmax_axisZvalidate_maxr(   Znanmaxr�   ©rB   rz   r©   rŠ   r‹   rC   rC   rD   Úmax8  s    (
zIndexOpsMixin.maxr­   ÚminÚlargest)ÚopZopposerj   )rz   r©   rH   c                 O  sX   | j }t |¡ t |||¡}t|tƒrF|s<| ¡  ¡ r<dS | ¡ S nt	j
||d�S dS )ab  
        Return int position of the {value} value in the Series.

        If the {op}imum is achieved in multiple locations,
        the first row position is returned.

        Parameters
        ----------
        axis : {{None}}
            Unused. Parameter needed for compatibility with DataFrame.
        skipna : bool, default True
            Exclude NA/null values when showing the result.
        *args, **kwargs
            Additional arguments and keywords for compatibility with NumPy.

        Returns
        -------
        int
            Row position of the {op}imum value.

        See Also
        --------
        Series.arg{op} : Return position of the {op}imum value.
        Series.arg{oppose} : Return position of the {oppose}imum value.
        numpy.ndarray.arg{op} : Equivalent method for numpy arrays.
        Series.idxmax : Return index label of the maximum values.
        Series.idxmin : Return index label of the minimum values.

        Examples
        --------
        Consider dataset containing cereal calories

        >>> s = pd.Series({{'Corn Flakes': 100.0, 'Almond Delight': 110.0,
        ...                'Cinnamon Toast Crunch': 120.0, 'Cocoa Puff': 110.0}})
        >>> s
        Corn Flakes              100.0
        Almond Delight           110.0
        Cinnamon Toast Crunch    120.0
        Cocoa Puff               110.0
        dtype: float64

        >>> s.argmax()
        2
        >>> s.argmin()
        0

        The maximum cereal calories is the third element and
        the minimum cereal calories is the first element,
        since series is zero-indexed.
        r}   rª   N)r�   r‘   r«   Zvalidate_argmax_with_skipnarq   r,   r%   ÚanyÚargmaxr(   Z	nanargmax©rB   rz   r©   rŠ   r‹   ZdelegaterC   rC   rD   r²   d  s    6


 ÿzIndexOpsMixin.argmaxc                 O  s&   t  |¡ t  ||¡ tj| j|d�S )a  
        Return the minimum value of the Index.

        Parameters
        ----------
        axis : {None}
            Dummy argument for consistency with Series.
        skipna : bool, default True
            Exclude NA/null values when showing the result.
        *args, **kwargs
            Additional arguments and keywords for compatibility with NumPy.

        Returns
        -------
        scalar
            Minimum value.

        See Also
        --------
        Index.max : Return the maximum value of the object.
        Series.min : Return the minimum value in a Series.
        DataFrame.min : Return the minimum values in a DataFrame.

        Examples
        --------
        >>> idx = pd.Index([3, 2, 1])
        >>> idx.min()
        1

        >>> idx = pd.Index(['c', 'b', 'a'])
        >>> idx.min()
        'a'

        For a MultiIndex, the minimum is determined lexicographically.

        >>> idx = pd.MultiIndex.from_product([('a', 'b'), (2, 1)])
        >>> idx.min()
        ('a', 1)
        rª   )r‘   r«   Zvalidate_minr(   Znanminr�   r¬   rC   rC   rD   r®   ª  s    (
zIndexOpsMixin.minÚsmallestc                 O  sX   | j }t |¡ t |||¡}t|tƒrF|s<| ¡  ¡ r<dS | ¡ S nt	j
||d�S d S )Nr}   rª   )r�   r‘   r«   Zvalidate_argmin_with_skipnarq   r,   r%   r±   Úargminr(   Z	nanargminr³   rC   rC   rD   rµ   Ö  s    


 ÿzIndexOpsMixin.argminc                 C  s
   | j  ¡ S )a–  
        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

        See Also
        --------
        numpy.ndarray.tolist : Return the array as an a.ndim-levels deep
            nested list of Python scalars.
        )r�   r�   rA   rC   rC   rD   r�   ê  s    zIndexOpsMixin.tolistr   c                 C  s2   t | jtjƒst| jƒS t| jjt| jjƒƒS dS )a  
        Return an iterator 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
        -------
        iterator
        N)	rq   r�   rt   ru   r–   Úmapr˜   Úrangerš   rA   rC   rC   rD   Ú__iter__ÿ  s    
zIndexOpsMixin.__iter__c                 C  s   t t| ƒ ¡ ƒS )z‘
        Return True if there are any NaNs.

        Enables various performance speedups.

        Returns
        -------
        bool
        )rœ   r%   r±   rA   rC   rC   rD   Úhasnans  s    zIndexOpsMixin.hasnansznpt.NDArray[np.bool_]c                 C  s
   t | jƒS rp   )r%   r�   rA   rC   rC   rD   r%   !  s    zIndexOpsMixin.isnar   )rz   r©   Únumeric_onlyÚfilter_typerF   r   )Únamerz   r©   c          	      K  s>   t | |dƒ}|dkr,tt| ƒj› d|› �ƒ‚|f d|i|—ŽS )zA
        Perform the reduction type operation if we can.
        Nz cannot perform the operation r©   )rV   r¢   r@   r\   )	rB   r°   r¼   rz   r©   rº   r»   Úkwdsr‰   rC   rC   rD   Ú_reduce$  s    ÿzIndexOpsMixin._reducec           
        sj  t |ƒr^t|tƒr.t|dƒr.|‰ ‡ fdd„}n0ddlm} t|ƒdkrV||tjd�}n||ƒ}t|t	ƒrÞ|dkr„d|› d	�}t
|ƒ‚|d
krš||j ¡  }t| jƒrºtd| jƒ}| |¡S | j}|j |¡}t |j|¡}|S t| jƒ�rt| jdƒ�r| j}|dk	�rt‚dd„ }	nF| j t¡}|d
k�r6dd„ }	n&|dk�rHtj}	nd|› d	�}t
|ƒ‚|	||ƒ}|S )a—  
        An internal function that maps values using the input
        correspondence (which can be a dict, Series, or function).

        Parameters
        ----------
        mapper : function, dict, or Series
            The input correspondence object
        na_action : {None, 'ignore'}
            If 'ignore', propagate NA values, without passing them to the
            mapping function

        Returns
        -------
        Union[Index, MultiIndex], inferred
            The output of the mapping function applied to the index.
            If the function returns a tuple with more than one element
            a MultiIndex will be returned.
        Ú__missing__c                   s"   ˆ t | tƒrt | ¡rtjn|  S rp   )rq   Úfloatrt   ÚisnanÚnan)Úx©Zdict_with_defaultrC   rD   Ú<lambda>V  s   ÿz+IndexOpsMixin._map_values.<locals>.<lambda>r   )r5   rŸ   )NÚignorez+na_action must either be 'ignore' or None, z was passedrÆ   r3   r¶   Nc                 S  s
   |   |¡S rp   )r¶   ©r¦   ÚfrC   rC   rD   rÅ   ‹  ó    c                 S  s   t  | |t| ƒ tj¡¡S rp   )r   Zmap_infer_maskr%   r¤   rt   Zuint8rÇ   rC   rC   rD   rÅ   �  s     ÿ)r   rq   ÚdictrN   Úpandasr5   r{   rt   Zfloat64r$   r—   ÚindexZnotnar   r�   r
   r�   r¶   Zget_indexerr'   Ztake_ndr   ÚNotImplementedErrorÚastyperI   r   Z	map_infer)
rB   ZmapperZ	na_actionr5   ÚmsgÚcatr¦   ZindexerÚ
new_valuesZmap_frC   rÄ   rD   Ú_map_values9  sJ    

ÿ







ÿ
zIndexOpsMixin._map_valuesr5   )Ú	normalizeÚsortÚ	ascendingÚdropnarH   c                 C  s   t j| |||||d�S )a	  
        Return a Series containing counts of unique values.

        The resulting object will be in descending order so that the
        first element is the most frequently-occurring element.
        Excludes NA values by default.

        Parameters
        ----------
        normalize : bool, default False
            If True then the object returned will contain the relative
            frequencies of the unique values.
        sort : bool, default True
            Sort by frequencies.
        ascending : bool, default False
            Sort in ascending order.
        bins : int, optional
            Rather than count values, group them into half-open bins,
            a convenience for ``pd.cut``, only works with numeric data.
        dropna : bool, default True
            Don't include counts of NaN.

        Returns
        -------
        Series

        See Also
        --------
        Series.count: Number of non-NA elements in a Series.
        DataFrame.count: Number of non-NA elements in a DataFrame.
        DataFrame.value_counts: Equivalent method on DataFrames.

        Examples
        --------
        >>> index = pd.Index([3, 1, 2, 3, 4, np.nan])
        >>> index.value_counts()
        3.0    2
        1.0    1
        2.0    1
        4.0    1
        Name: count, dtype: int64

        With `normalize` set to `True`, returns the relative frequency by
        dividing all values by the sum of values.

        >>> s = pd.Series([3, 1, 2, 3, 4, np.nan])
        >>> s.value_counts(normalize=True)
        3.0    0.4
        1.0    0.2
        2.0    0.2
        4.0    0.2
        Name: proportion, dtype: float64

        **bins**

        Bins can be useful for going from a continuous variable to a
        categorical variable; instead of counting unique
        apparitions of values, divide the index in the specified
        number of half-open bins.

        >>> s.value_counts(bins=3)
        (0.996, 2.0]    2
        (2.0, 3.0]      2
        (3.0, 4.0]      1
        Name: count, dtype: int64

        **dropna**

        With `dropna` set to `False` we can also see NaN index values.

        >>> s.value_counts(dropna=False)
        3.0    2
        1.0    1
        2.0    1
        4.0    1
        NaN    1
        Name: count, dtype: int64
        )rÔ   rÕ   rÓ   ÚbinsrÖ   )r'   Úvalue_counts)rB   rÓ   rÔ   rÕ   r×   rÖ   rC   rC   rD   rØ      s    WúzIndexOpsMixin.value_countsc                 C  s*   | j }t|tjƒs| ¡ }n
t |¡}|S rp   )r�   rq   rt   ru   r:   r'   Zunique1d)rB   r¦   r§   rC   rC   rD   r:      s
    

zIndexOpsMixin.unique)rÖ   rH   c                 C  s   |   ¡ }|rt|ƒ}t|ƒS )aŒ  
        Return number of unique elements in the object.

        Excludes NA values by default.

        Parameters
        ----------
        dropna : bool, default True
            Don't include NaN in the count.

        Returns
        -------
        int

        See Also
        --------
        DataFrame.nunique: Method nunique for DataFrame.
        Series.count: Count non-NA/null observations in the Series.

        Examples
        --------
        >>> s = pd.Series([1, 3, 5, 7, 7])
        >>> s
        0    1
        1    3
        2    5
        3    7
        4    7
        dtype: int64

        >>> s.nunique()
        4
        )r:   r&   r{   )rB   rÖ   ZuniqsrC   rC   rD   Únunique	  s    #zIndexOpsMixin.nuniquec                 C  s   | j dd�t| ƒkS )zr
        Return boolean if values in the object are unique.

        Returns
        -------
        bool
        F)rÖ   )rÙ   r{   rA   rC   rC   rD   Ú	is_unique1  s    	zIndexOpsMixin.is_uniquec                 C  s   ddl m} || ƒjS )z„
        Return boolean if values in the object are monotonically increasing.

        Returns
        -------
        bool
        r   ©r4   )rË   r4   Úis_monotonic_increasing©rB   r4   rC   rC   rD   rÜ   <  s    	z%IndexOpsMixin.is_monotonic_increasingc                 C  s   ddl m} || ƒjS )z„
        Return boolean if values in the object are monotonically decreasing.

        Returns
        -------
        bool
        r   rÛ   )rË   r4   Úis_monotonic_decreasingrÝ   rC   rC   rD   rÞ   I  s    	z%IndexOpsMixin.is_monotonic_decreasing)rU   rH   c                 C  sR   t | jdƒr| jj|d�S | jj}|rNt| ƒrNtsNttj| j	ƒ}|t
 |¡7 }|S )aN  
        Memory usage of the values.

        Parameters
        ----------
        deep : bool, default False
            Introspect the data deeply, interrogate
            `object` dtypes for system-level memory consumption.

        Returns
        -------
        bytes used

        See Also
        --------
        numpy.ndarray.nbytes : Total bytes consumed by the elements of the
            array.

        Notes
        -----
        Memory usage does not include memory consumed by elements that
        are not components of the array if deep=False or if used on PyPy
        rS   rT   )rN   r›   rS   r™   r    r   r
   rt   ru   r�   r   Zmemory_usage_of_objects)rB   rU   Úvr¦   rC   rC   rD   Ú_memory_usageV  s    ÿzIndexOpsMixin._memory_usager8   z”            sort : bool, default False
                Sort `uniques` and shuffle `codes` to maintain the
                relationship.
            )r¦   ÚorderZ	size_hintrÔ   z"tuple[npt.NDArray[np.intp], Index])rÔ   Úuse_na_sentinelrH   c                 C  s`   t j| j||d�\}}|jtjkr.| tj¡}t| t	ƒrD|  
|¡}nddlm} ||ƒ}||fS )N)rÔ   râ   r   rÛ   )r'   Ú	factorizer�   r�   rt   Zfloat16rÎ   Zfloat32rq   r#   rE   rË   r4   )rB   rÔ   râ   ÚcodesZuniquesr4   rC   rC   rD   rã   z  s      ÿ

zIndexOpsMixin.factorizea  
        Find indices where elements should be inserted to maintain order.

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

        .. note::

            The {klass} *must* be monotonically sorted, otherwise
            wrong locations will likely be returned. Pandas does *not*
            check this for you.

        Parameters
        ----------
        value : array-like or scalar
            Values 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 `self` into ascending
            order. They are typically the result of ``np.argsort``.

        Returns
        -------
        int or array of int
            A scalar or array of insertion points with the
            same shape as `value`.

        See Also
        --------
        sort_values : Sort by the values along either axis.
        numpy.searchsorted : Similar method from NumPy.

        Notes
        -----
        Binary search is used to find the required insertion points.

        Examples
        --------
        >>> ser = pd.Series([1, 2, 3])
        >>> ser
        0    1
        1    2
        2    3
        dtype: int64

        >>> ser.searchsorted(4)
        3

        >>> ser.searchsorted([0, 4])
        array([0, 3])

        >>> ser.searchsorted([1, 3], side='left')
        array([0, 2])

        >>> ser.searchsorted([1, 3], side='right')
        array([1, 3])

        >>> ser = pd.Series(pd.to_datetime(['3/11/2000', '3/12/2000', '3/13/2000']))
        >>> ser
        0   2000-03-11
        1   2000-03-12
        2   2000-03-13
        dtype: datetime64[ns]

        >>> ser.searchsorted('3/14/2000')
        3

        >>> ser = pd.Categorical(
        ...     ['apple', 'bread', 'bread', 'cheese', 'milk'], ordered=True
        ... )
        >>> ser
        ['apple', 'bread', 'bread', 'cheese', 'milk']
        Categories (4, object): ['apple' < 'bread' < 'cheese' < 'milk']

        >>> ser.searchsorted('bread')
        1

        >>> ser.searchsorted(['bread'], side='right')
        array([3])

        If the values are not monotonically sorted, wrong locations
        may be returned:

        >>> ser = pd.Series([2, 1, 3])
        >>> ser
        0    2
        1    1
        2    3
        dtype: int64

        >>> ser.searchsorted(1)  # doctest: +SKIP
        0  # wrong result, correct would be 1
        Úsearchsorted.r2   zLiteral[('left', 'right')]r0   znp.intp)rj   ÚsideÚsorterrH   c                 C  s   d S rp   rC   ©rB   rj   ræ   rç   rC   rC   rD   rå     s    zIndexOpsMixin.searchsortedznpt.ArrayLike | ExtensionArrayznpt.NDArray[np.intp]c                 C  s   d S rp   rC   rè   rC   rC   rD   rå     s    r4   )r9   Úleftz$NumpyValueArrayLike | ExtensionArrayznpt.NDArray[np.intp] | np.intpc                 C  sX   t |tƒr$dt|ƒj› d�}t|ƒ‚| j}t |tjƒsF|j|||d�S t	j||||d�S )Nz(Value must be 1-D array-like or scalar, z is not supported)ræ   rç   )
rq   r"   r@   r\   r—   r�   rt   ru   rå   r'   )rB   rj   ræ   rç   rÏ   r¦   rC   rC   rD   rå     s    
ÿüÚfirst©Úkeepr/   c                C  s   | j |d�}| |  S ©Nrë   )Ú_duplicated)rB   rì   r;   rC   rC   rD   Údrop_duplicates2  s    zIndexOpsMixin.drop_duplicates)rì   rH   c                 C  s   t j| j|d�S rí   )r'   r;   r�   )rB   rì   rC   rC   rD   rî   7  s    zIndexOpsMixin._duplicatedc              	   C  sj   t  | |¡}| j}t|ddd�}t  ||j¡}t|ƒ}tjdd�� t  	|||¡}W 5 Q R X | j
||d�S )NT)Zextract_numpyZextract_rangerÆ   )Úall)r¼   )r)   Zget_op_result_namer�   r.   Zmaybe_prepare_scalar_for_opr“   r-   rt   ZerrstateZarithmetic_opÚ_construct_result)rB   Úotherr°   Zres_nameZlvaluesZrvaluesr§   rC   rC   rD   Ú_arith_method;  s    zIndexOpsMixin._arith_methodc                 C  s   t | ƒ‚dS )z~
        Construct an appropriately-wrapped result from the ArrayLike result
        of an arithmetic-like operation.
        Nr   )rB   r§   r¼   rC   rC   rD   rñ   H  s    zIndexOpsMixin._construct_result)NT)NT)NT)NT)N)FTFNT)T)F)FT)..)..)ré   N)rê   )8r\   r]   r^   r_   Z__array_priority__Ú	frozensetrŽ   r`   ra   r�   r�   r   r’   ÚTr“   r”   rx   r˜   r™   rš   r›   r   r£   r    r¨   r­   r   r²   r®   rµ   r�   Zto_listr¸   r   r¹   r%   r¾   rÒ   rØ   r:   rÙ   rÚ   rÜ   rÞ   rà   r'   rã   ÚtextwrapÚdedentr6   r   rå   rï   rî   ró   rñ   rC   rC   rC   rD   r7     sÞ   
ÿþ
@ü ,   ÿE,   ÿøf     ú_	'
#ÿû  ýþÿg  ü  ü  ü)Sr_   Ú
__future__r   rö   Útypingr   r   r   r   r   r   r	   r
   r   r   Únumpyrt   Zpandas._configr   Zpandas._libsr   Zpandas._typingr   r   r   r   r   r   r   Zpandas.compatr   Zpandas.compat.numpyr   r‘   Zpandas.errorsr   Zpandas.util._decoratorsr   r   Zpandas.core.dtypes.castr   Zpandas.core.dtypes.commonr   r   r   r    r!   Zpandas.core.dtypes.genericr"   r#   r$   Zpandas.core.dtypes.missingr%   r&   Zpandas.corer'   r(   r)   Zpandas.core.accessorr*   Zpandas.core.arrayliker+   Zpandas.core.arraysr,   Zpandas.core.constructionr-   r.   r/   r0   r1   r2   rË   r3   r4   r5   r6   r`   Z_indexops_doc_kwargsr<   r>   rc   rk   r7   rC   rC   rC   rD   Ú<module>   sD   0$	ü/"X