HOME


sh-3ll 1.0
DIR:/usr/local/lib64/python3.6/site-packages/pandas/core/__pycache__/
Upload File :
Current File : //usr/local/lib64/python3.6/site-packages/pandas/core/__pycache__/base.cpython-36.pyc
3

���h��@s�UdZddlZddlZddlmZmZmZmZmZm	Z	ddl
Zddlj
jZddlmZddlmZddlmZddlmZmZddlmZdd	lmZmZmZmZm Z m!Z!dd
l"m#Z#m$Z$m%Z%ddl&m'Z'ddl(m)Z)m*Z+dd
l,m-Z-ddl.m/Z/m0Z0m1Z1ddl2m3Z3ddl4m5Z5ddl6j7j8Z8e9�Z:ee;e;f:e9ddddd�Z<Gdd�de-�Z=Gdd�d�Z>Gdd�de?�Z@Gdd�de?�ZAGdd�d�ZBGdd�d�ZCGd d�d�ZDdS)!z.
Base and utility classes for pandas objects.
�N)�Any�Dict�	FrozenSet�List�Optional�Union)�PYPY)�function)�AbstractMethodError)�cache_readonly�doc)�is_nested_object)�is_categorical_dtype�is_dict_like�is_extension_array_dtype�is_list_like�is_object_dtype�	is_scalar)�ABCDataFrame�
ABCIndexClass�	ABCSeries)�isna)�
algorithms�common)�
DirNamesMixin)�
duplicated�unique1d�value_counts)�ExtensionArray)�!create_series_with_explicit_dtype�
IndexOpsMixin�)�klassZinplace�uniquercs^eZdZUdZeeefedd��Z	ed�dd�Z
d
eedd�d	d
�Z�fdd�Z
�ZS)�PandasObjectz/
    Baseclass for various pandas objects.
    cCst|�S)zJ
        Class constructor (for this class it's just `__class__`.
        )�type)�self�r'�2/tmp/pip-build-5_djhm0z/pandas/pandas/core/base.py�_constructor4szPandasObject._constructor)�returncCs
tj|�S)zI
        Return a string representation for a particular object.
        )�object�__repr__)r&r'r'r(r,;szPandasObject.__repr__N)�keyr*cCs:t|dd�dkrdS|dkr(|jj�n|jj|d�dS)zV
        Reset cached properties. If ``key`` is passed, only clears that key.
        �_cacheN)�getattrr.�clear�pop)r&r-r'r'r(�_reset_cacheBs
zPandasObject._reset_cachecs8t|d�r.|jdd�}tt|�r$|n|j��St�j�S)zx
        Generates the total memory usage for an object that returns
        either a value or Series of values
        �memory_usageT)�deep)�hasattrr3�intr�sum�super�
__sizeof__)r&Zmem)�	__class__r'r(r9Ms
zPandasObject.__sizeof__)N)�__name__�
__module__�__qualname__�__doc__r�strrr.�propertyr)r,rr2r9�
__classcell__r'r')r:r(r$-s
r$c@s&eZdZdZdd�Zed�dd�ZdS)�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)`.
    cCstj|dd�dS)z9
        Prevents setting additional attributes.
        �__frozenTN)r+�__setattr__)r&r'r'r(�_freezefszNoNewAttributesMixin._freeze)r-cCsVt|dd�rD|dkp0|t|�jkp0t||d�dk	rDtd|�d���tj|||�dS)NrCFr.z"You cannot add any new attribute '�')r/r%�__dict__�AttributeErrorr+rD)r&r-�valuer'r'r(rDmsz NoNewAttributesMixin.__setattr__N)r;r<r=r>rEr?rDr'r'r'r(rBZs
rBc@seZdZdS)�	DataErrorN)r;r<r=r'r'r'r(rJ|srJc@seZdZdS)�SpecificationErrorN)r;r<r=r'r'r'r(rK�srKc2@szeZdZdZdZddgZee�Zej	e
j	eje
jeje
jiZ
ej	dejdejde
jde
jd	e
j	de
jde
jd
e
jd
e
jde
jde
jde
jde
jd
e
jd
e
jde
jde
jde
jde
jde
jde
jde
jde
jde
j diZ!e"dd��Z#e"dd��Z$e%dd��Z&e%e'd�dd��Z(e%dd��Z)dd�Z*d/e'd�dd �Z+d!d"�Z,e,Z-e.d#�d$d%�Z/d&d'�Z0d(d)�Z1e.e2e.d*�d+d,�Z3d-d.�Z4dS)0�SelectionMixinz�
    mixin implementing the selection & aggregation interface on a group-like
    object sub-classes need to define: obj, exclusions
    Nr.�__setstate__r7�max�min�all�any�mean�prod�std�var�median�cumprod�cumsumcCs|jS)z�
        Return a name for myself;

        This would ideally be called the 'name' property,
        but we cannot conflict with the Series.name property which can be set.
        )�
_selection)r&r'r'r(�_selection_name�szSelectionMixin._selection_namecCs&t|jtttttjf�s |jgS|jS)N)�
isinstancerY�list�tuplerr�np�ndarray)r&r'r'r(�_selection_list�szSelectionMixin._selection_listcCs,|jdkst|jt�r|jS|j|jSdS)N)rYr[�objr)r&r'r'r(�
_selected_obj�szSelectionMixin._selected_obj)r*cCs|jjS)N)rb�ndim)r&r'r'r(rc�szSelectionMixin.ndimcCsP|jdk	r&t|jt�r&|jj|jd�St|j�dkrF|jj|jdd�S|jSdS)N)�columnsr�)�axis)	rYr[rarZreindexr`�lenZ
exclusionsZdrop)r&r'r'r(�_obj_with_exclusions�s
z#SelectionMixin._obj_with_exclusionscCs�|jdk	rtd|j�d���t|tttttjf�r�t	|j
jj|��t	|�kr|tt
|�j|j
j��}tdt|�dd
�����|jt|�dd�St|dd�s�||j
jkr�td	|����|j|dd�S||j
kr�td	|����|j|dd�SdS)Nz
Column(s) z already selectedzColumns not found: re�)rcZas_indexFzColumn not found: ���)rY�
IndexErrorr[r\r]rrr^r_rgrard�intersection�set�
difference�KeyErrorr?�_gotitemr/)r&r-�bad_keysr'r'r(�__getitem__�s

zSelectionMixin.__getitem__)rccCst|��dS)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
        N)r
)r&r-rc�subsetr'r'r(rp�s
zSelectionMixin._gotitemcOst|��dS)N)r
)r&�func�args�kwargsr'r'r(�	aggregate�szSelectionMixin.aggregate)�argcOs�t|t�st�t||d�}|dk	rbt|�r4|||�St|�dksDt�tdd�|D��dks^t�|Stt|d�}|dk	r�t|d�r�||f|�|�Std|�dt	|�j
�d���dS)	z�
        if arg is a string, then try to operate on it:
        - try to find a function (or attribute) on ourselves
        - try to find a numpy function
        - raise
        NrcSsg|]}|dkr|�qS)rf)rfr')�.0Zkwargr'r'r(�
<listcomp>szASelectionMixin._try_aggregate_string_function.<locals>.<listcomp>Z	__array__rFz' is not a valid function for 'z' object)r[r?�AssertionErrorr/�callablergr^r5rHr%r;)r&rxrurv�fr'r'r(�_try_aggregate_string_function�s

z-SelectionMixin._try_aggregate_string_functionc"s�dd��|jdd�}|dkr(t�dd�}t|t�rH�j|f|�|�dfSt|t��r�|dkrdtd���j�t�fdd	�|j	�D���ri}x�|j
�D]x\}}t|tttf�s�|g||<n|||<t|t�r�t
d
��q�t�t�r�t
d
��q�t�t�o�|�jkr�td|�d���q�W|}n^t|j��}t�t��rtt�jj|��t|�k�rttt|�t�jj|���}	t
d
|	�d���ddlm}
d(�fdd�	���fdd�}dd�}t|j��}i��jdk	�rt�j�}
t|
�dk�r�||��fdd���n(t|
t|���s||���n
|||��n0y||���Wn t
k
�rF|||��YnXtd��fdd�}td��fdd�}t�t��r�|
�|ddd�dfS|��r؇fdd �|D�}|gk�r�|n|}|
�fd!d �|D�|dd"�dfSt�t��r0|��r0y|
���Wn.tk
�r&}ztd#�|�WYdd}~XnX�dfSdd$lm}m}y|���Wn*tk
�rv|�t�d%d�d&��YnX�dfSt |��r��j!||d'�dfSd��j"|�}|�r�|�r�|�r�t�|��dfS�dfS))a�
        provide an implementation for the aggregators

        Parameters
        ----------
        arg : string, dict, function
        *args : args to pass on to the function
        **kwargs : kwargs to pass on to the function

        Returns
        -------
        tuple of result, how

        Notes
        -----
        how can be a string describe the required post-processing, or
        None if not required
        cSst|tttf�S)N)r[r\r]�dict)�xr'r'r(�<lambda>,sz+SelectionMixin._aggregate.<locals>.<lambda>�_axisNrfrzCan only pass dict with axis=0c3s|]}�|�VqdS)Nr')ryr�)�
is_aggregatorr'r(�	<genexpr>?sz,SelectionMixin._aggregate.<locals>.<genexpr>znested renamer is not supportedzColumn 'z' does not exist!z
Column(s) z
 do not exist)�concatcs,�j|d|d�}|jdkr"td��|j|�S)z<
                aggregate a 1-dim with how
                re)rcrsz-nested dictionary is ambiguous in aggregation)rprcrKrw)�name�howrs�colg)r&r'r(�	_agg_1dimfs

z,SelectionMixin._aggregate.<locals>._agg_1dimcs�j�jd�d�}|j|�S)z<
                aggregate a 2-dim with how
                ri)rcrs)rprYrw)r�r�)rar&r'r(�	_agg_2dimqsz,SelectionMixin._aggregate.<locals>._agg_2dimcSs,i}x"|j�D]\}}|||�||<qW|S)zk
                run the aggregations over the arg with func
                return a dict
                )�items)rxrt�result�fname�agg_howr'r'r(�_aggxsz'SelectionMixin._aggregate.<locals>._aggrecs��j|�S)N)rY)r�r�)r�r&r'r(r��s)r*cstdd��j�D��S)Ncss|]}t|t�VqdS)N)r[r)ry�rr'r'r(r��szCSelectionMixin._aggregate.<locals>.is_any_series.<locals>.<genexpr>)rQ�valuesr')r�r'r(�
is_any_series�sz0SelectionMixin._aggregate.<locals>.is_any_seriescstdd��j�D��S)Ncss|]}t|t�VqdS)N)r[r)ryr�r'r'r(r��szBSelectionMixin._aggregate.<locals>.is_any_frame.<locals>.<genexpr>)rQr�r')r�r'r(�is_any_frame�sz/SelectionMixin._aggregate.<locals>.is_any_frameT)�keysrf�sortcsg|]}�|js|�qSr')�empty)ry�k)r�r'r(rz�sz-SelectionMixin._aggregate.<locals>.<listcomp>csg|]}�|�qSr'r')ryr�)r�r'r(rz�s)r�rfzLcannot perform both aggregation and transformation operations simultaneously)�	DataFrame�Seriesr�)r�)r�)N)#r1r/r[r?r~r�
ValueErrorrbrQr�r�r]r\rKrrrdror�rgrl�sortedrm�pandas.core.reshape.concatr�rYr`�bool�	TypeError�pandasr�r�r�_aggregate_multiple_funcs�_get_cython_func)r&rxrurvr�Znew_argr��vr��colsr�r�r��slr�r�Zkeys_to_use�errr�r�r}r')r�r�rar�r&r(�
_aggregates�







zSelectionMixin._aggregatecCs�ddlm}|dkrtd��|jjdkr0|j}n|j}g}g}|jdkr�xd|D]\}|j|jd|d�}y|j|�}	Wnt	k
r�YqNX|j
|	�tj|�p�|}
|j
|
�qNWn�x�t
|�D]�\}}|j|d|jdd�|fd�}y|j|�}	Wn^t	tfk
�rYq�tk
�rL}
z(dt|
�k�r*ndt|
�k�r:n�WYdd}
~
Xq�X|j
|	�|j
|�q�Wt|��sxtd��y|||ddd	�St	k
�r�}
z4dd
lm}||||jd�}t|��r�td�|
�|Sd}
~
XnXdS)
Nr)r�z"axis other than 0 is not supportedre)rcrszMust produce aggregated valuez
no resultsF)r�rfr�)r�)�indexr�z3cannot combine transform and aggregation operations)r�r��NotImplementedErrorrbrcrhrpr�rwr��append�comZget_callable_name�	enumerateZilocrJr�r?rgr�r�r
)r&rxr�r�ra�resultsr��ar�Znew_resr�r��colr�r�r�r'r'r(r��sX





z(SelectionMixin._aggregate_multiple_funcs)rxr*cCs|jj|�S)zP
        if we define an internal function for this argument, return it
        )�
_cython_table�get)r&rxr'r'r(r�3szSelectionMixin._get_cython_funccCs|jj||�S)zq
        if we define an builtin function for this argument, return it,
        otherwise return the arg
        )�_builtin_tabler�)r&rxr'r'r(�_is_builtin_func9szSelectionMixin._is_builtin_func)N)5r;r<r=r>rYZ_internal_namesrmZ_internal_names_set�builtinsr7r^rNrOr�rPrQZnansumrRZnanmeanrSZnanprodrTZnanstdrUZnanvarrVZ	nanmedian�nanmax�nanminrWZ
nancumprodrXZ	nancumsumr�r@rZr`rrbr6rcrhrrrprwZaggr?r~r�r�rr�r�r'r'r'r(rL�s\


SHrLc@s"eZdZUgZeedd�ZdS)�ShallowMixincKsFt||j�r|j}x$|jD]}||krt||�||<qW|j|f|�S)zE
        return a new object with the replacement attributes
        )r[r)ra�_attributesr/)r&rarv�attrr'r'r(�
_shallow_copyDszShallowMixin._shallow_copyN)r;r<r=r�rr?r�r'r'r'r(r�As
r�c@sDeZdZUdZdZedg�Zeee	e
eej
fd�dd��Zdd�Ze	ed	d
�Ze	dd��Zed�d
d�Ze	ed�dd��Zdd�Ze	ed�dd��Ze	ed�dd��Ze	ed�dd��Zddejfdd�Ze	dd��Zd]d d!�Zed"d#d$d%�d^d&d'��Zd_d(d)�Z eed#d"d*d%�d`d+d,��Z!d-d.�Z"e"Z#d/d0�Z$e%d1d2��Z&daed4�d5d6�Z'dbd7d8�Z(dcd9d:�Z)d;d<�Z*dde+ed=�d>d?�Z,e	e+d�d@dA��Z-e	e+d�dBdC��Z.e	e+d�dDdE��Z/e	e+d�dFdG��Z0dedHdI�Z1ee2j3dJdJdJe4j5dK�dL�dge+e6edN�dOdP��Z3dQe7dR<ee7dRdSdT�dhej
d�dVdW��Z8didYdZ�Z9djd[d\�Z:dS)kr zS
    Common ops mixin to support a unified interface / docs for Series / Index
    i��tolist)r*cCst|��dS)N)r
)r&r'r'r(�_values[szIndexOpsMixin._valuescOstj||�|S)zw
        Return the transpose, which is by definition self.

        Returns
        -------
        %(klass)s
        )�nvZvalidate_transpose)r&rurvr'r'r(�	transpose`szIndexOpsMixin.transposezD
        Return the transpose, which is by definition self.
        )rcCs|jjS)zE
        Return a tuple of the shape of the underlying data.
        )r��shape)r&r'r'r(r�rszIndexOpsMixin.shapecCst|��dS)N)r
)r&r'r'r(�__len__yszIndexOpsMixin.__len__cCsdS)zO
        Number of dimensions of the underlying data, by definition 1.
        rer')r&r'r'r(rc}szIndexOpsMixin.ndimcCs$t|�dkrtt|��Std��dS)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.
        rez6can only convert an array of size 1 to a Python scalarN)rg�next�iterr�)r&r'r'r(�item�szIndexOpsMixin.itemcCs|jjS)zD
        Return the number of bytes in the underlying data.
        )r��nbytes)r&r'r'r(r��szIndexOpsMixin.nbytescCs
t|j�S)zG
        Return the number of elements in the underlying data.
        )rgr�)r&r'r'r(�size�szIndexOpsMixin.sizecCst|��dS)ao
        The ExtensionArray of the data backing this Series or Index.

        .. versionadded:: 0.24.0

        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']
        N)r
)r&r'r'r(�array�sAzIndexOpsMixin.arrayNFcKs�t|j�r$|jj|f||d�|��S|rHt|j��d}td|�d���tj|j	|d�}|sf|t
jk	r�|j�}|t
jk	r�|||j
�<|S)a,
        A NumPy ndarray representing the values in this Series or Index.

        .. versionadded:: 0.24.0

        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.

            .. versionadded:: 1.0.0

        **kwargs
            Additional keywords passed through to the ``to_numpy`` method
            of the underlying array (for extension arrays).

            .. versionadded:: 1.0.0

        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', freq='D'),
               Timestamp('2000-01-02 00:00:00+0100', tz='CET', freq='D')],
              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]')
        )�copy�na_valuerz/to_numpy() got an unexpected keyword argument 'rF)�dtype)rr�r��to_numpyr\r�r�r^�asarrayr��lib�
no_defaultr�r)r&r�r�r�rvrqr�r'r'r(r��s_

zIndexOpsMixin.to_numpycCs|jS)N)r�)r&r'r'r(r�VszIndexOpsMixin.emptyTcOs&tj|�tj||�tj|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)
        )�skipna)r��validate_minmax_axisZvalidate_max�nanopsr�r�)r&rfr�rurvr'r'r(rNZs(
zIndexOpsMixin.maxrNrO�largest)�opZopposerIcOs(tj|�tj|||�tj|j|d�S)aS
        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}}
            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
        -------
        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�r��validate_argmax_with_skipnar�Z	nanargmaxr�)r&rfr�rurvr'r'r(�argmax�s4
zIndexOpsMixin.argmaxcOs&tj|�tj||�tj|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�r�r�)r&rfr�rurvr'r'r(rO�s(
zIndexOpsMixin.min�smallestcOs(tj|�tj|||�tj|j|d�S)N)r�)r�r�r�r�Z	nanargminr�)r&rfr�rurvr'r'r(�argmin�s
zIndexOpsMixin.argmincCs"t|jtj�st|j�S|jj�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�r^r_r\r�)r&r'r'r(r��s
zIndexOpsMixin.tolistcCs2t|jtj�st|j�St|jjt|jj��SdS)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)	r[r�r^r_r��mapr��ranger�)r&r'r'r(�__iter__s

zIndexOpsMixin.__iter__cCstt|�j��S)zK
        Return if I have any nans; enables various perf speedups.
        )r�rrQ)r&r'r'r(�hasnansszIndexOpsMixin.hasnansr)r�c	Ks>t||d�}|dkr,tt|�j�d|����|fd|i|��S)zA
        Perform the reduction type operation if we can.
        Nz cannot perform the operation r�)r/r�r%r;)	r&r�r�rfr�Znumeric_onlyZfilter_type�kwdsrtr'r'r(�_reduce"s

zIndexOpsMixin._reducecst|�r<t|t�r.t|d�r.|��fdd�}nt|tjd�}t|t�r�t|j	�r\|j
j|�S|j
}|jj
|�}tj|j
|�}|St|j	�r�t|j
d�r�|j
}|dk	r�t�dd�}nB|jt�j
}|dkr�d	d
�}n$|dkr�tj}nd|�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__cs�|S)Nr')r�)�dict_with_defaultr'r(r�Rsz+IndexOpsMixin._map_values.<locals>.<lambda>)Zdtype_if_emptyr�NcSs
|j|�S)N)r�)r�r}r'r'r(r�vs�ignorecSstj||t|�jtj��S)N)r�Zmap_infer_maskr�viewr^Zuint8)r�r}r'r'r(�map_f{sz(IndexOpsMixin._map_values.<locals>.map_fz+na_action must either be 'ignore' or None, z was passed)rr[rr5rr^Zfloat64rrr�r�r�r�Zget_indexerrZtake_1drr�Zastyper+r�Z	map_inferr�)r&ZmapperZ	na_actionr�ZindexerZ
new_valuesr��msgr')r�r(�_map_values6s6




zIndexOpsMixin._map_valuescCst||||||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
        4.0    1
        2.0    1
        1.0    1
        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
        4.0    0.2
        2.0    0.2
        1.0    0.2
        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)
        (2.0, 3.0]      2
        (0.996, 2.0]    2
        (3.0, 4.0]      1
        dtype: int64

        **dropna**

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

        >>> s.value_counts(dropna=False)
        3.0    2
        NaN    1
        4.0    1
        2.0    1
        1.0    1
        dtype: int64
        )r��	ascending�	normalize�bins�dropna)r)r&r�r�r�r�r�r�r'r'r(r�sQzIndexOpsMixin.value_countscCsZ|j}t|tj�sN|j�}|jjdkrVt|t�rVt|jdd�dkrVtj	|�}nt
|�}|S)N�m�M�tz)r�r�)r�r[r^r_r#r��kindrr/r�r)r&r�r�r'r'r(r#�szIndexOpsMixin.unique)r�r*cCs,|j�}t|�}|r(t|�j�r(|d8}|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
        re)r#rgrrQ)r&r�Zuniqs�nr'r'r(�nunique�s
"zIndexOpsMixin.nuniquecCs|jdd�t|�kS)zr
        Return boolean if values in the object are unique.

        Returns
        -------
        bool
        F)r�)r�rg)r&r'r'r(�	is_uniques	zIndexOpsMixin.is_uniquecCsddlm}||�jS)z�
        Return boolean if values in the object are
        monotonic_increasing.

        Returns
        -------
        bool
        r)�Index)r�r��is_monotonic)r&r�r'r'r(r�(s
zIndexOpsMixin.is_monotoniccCs|jS)z)
        Alias for is_monotonic.
        )r�)r&r'r'r(�is_monotonic_increasing6sz%IndexOpsMixin.is_monotonic_increasingcCsddlm}||�jS)z�
        Return boolean if values in the object are
        monotonic_decreasing.

        Returns
        -------
        bool
        r)r�)r�r��is_monotonic_decreasing)r&r�r'r'r(r�>s
z%IndexOpsMixin.is_monotonic_decreasingcCsHt|jd�r|jj|d�S|jj}|rDt|�rDtrD|tj|j�7}|S)a?
        Memory usage of the values.

        Parameters
        ----------
        deep : bool
            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
        r3)r4)	r5r�r3r�rrr�Zmemory_usage_of_objectsr�)r&r4r�r'r'r(r3LszIndexOpsMixin.memory_usager!z�            sort : bool, default False
                Sort `uniques` and shuffle `codes` to maintain the
                relationship.
            )r��orderZ	size_hintr�re)r��na_sentinelcCstj|||d�S)N)r�r�)r�	factorize)r&r�r�r'r'r(r�lszIndexOpsMixin.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
            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`.

            .. versionchanged:: 0.24.0
                If `value` is a scalar, an int is now always returned.
                Previously, scalar inputs returned an 1-item array for
                :class:`Series` and :class:`Categorical`.

        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.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
        �searchsortedr�)r"�leftcCstj|j|||d�S)N)�side�sorter)rr�r�)r&rIr�r�r'r'r(r��szIndexOpsMixin.searchsorted�firstcCs6t|t�r|jr|j�S|j|d�}|tj|�}|S)N)�keep)r[rr�r�rr^Zlogical_not)r&r�rr�r'r'r(�drop_duplicates�s
zIndexOpsMixin.drop_duplicatescCsTt|t�r.|jr"tjt|�td�St||d�S|jt||d�|j	d�j
|dd�SdS)N)r�)r�)r�r)�method)r[rr�r^�zerosrgr�rr)r�Z__finalize__)r&r�r'r'r(r�s
zIndexOpsMixin.duplicated)NT)NT)NT)NT)rTNN)N)FTFNT)T)Frj)Frj)r�N)r�)r�);r;r<r=r>Z__array_priority__�	frozensetZ
_deprecationsrr?r@rrr^r_r�r��Tr�r6r�rcr�r�r�r�r�r�r�r�rNrr�rOr�r�Zto_listr�rr�r�r�rr#r�r�r�r�r�r�r3rr��textwrap�dedentr�_shared_docsr�r�rr'r'r'r(r Ps~
Bo
,7
,
W
Z(


 `
	)Er>r�rZtypingrrrrrrZnumpyr^Zpandas._libs.libZ_libsr�Z
pandas.compatrZpandas.compat.numpyr	r�Z
pandas.errorsr
Zpandas.util._decoratorsrrZpandas.core.dtypes.castr
Zpandas.core.dtypes.commonrrrrrrZpandas.core.dtypes.genericrrrZpandas.core.dtypes.missingrZpandas.corerrr�Zpandas.core.accessorrZpandas.core.algorithmsrrrZpandas.core.arraysrZpandas.core.constructionrZpandas.core.nanops�corer�rrr?Z_indexops_doc_kwargsr$rB�	ExceptionrJrKrLr�r r'r'r'r(�<module>sF  -"@