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__/series.cpython-36.pyc
3

���hEW�@s2dZddlmZddlmZddlmZddlmZm	Z	m
Z
mZmZm
Z
mZmZmZmZddlZddlZddlmZddlmZmZmZmZdd	lmZdd
lmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%ddl&m'Z(ddl)m*Z*dd
l+m,Z,m-Z-m.Z.ddl/m0Z0m1Z1ddl2m3Z3m4Z4m5Z5ddl6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@ddlAmBZBddlCmDZDddlEmFZFmGZGmHZHmIZIddlJZKddlLmMZMmNZNmOZOmPZPmQZQddlRmSZSddlTmUZUddlVmWZWddlXmYZYddlZj[j\Z]ddl^m_Z_m`Z`maZambZbddlcmdZdddlemfZfmgZgddlhmiZiddljmkZkmlZlmmZmmnZnddloj[jpjNZqddlrmsZsddltmuZudd lvmwZwdd!lxmyZydd"lzm{Z{dd#l|m}Z}dd$l~mZdd%l�m�Z�ddl�jj�j�Z�ddl�ZJe	�r�dd&l�m�Z�dd'l�m�Z�d(gZ�e�d)d(d*d+d,d-d(d.d.d.d.d/d0�Z�d1d2�Z�Gd3d(�d(eNj�eOjd�Z�e�j��e�j��eQj�e��eQj�e��dS)4zG
Data structure for 1-dimensional cross-sectional and time series data
�)�StringIO)�get_terminal_size)�dedent)
�IO�
TYPE_CHECKING�Any�Callable�Iterable�List�Optional�Tuple�Type�UnionN)�
get_option)�lib�
properties�reshape�tslibs)�
no_default)�	ArrayLike�Axis�DtypeObj�FrameOrSeriesUnion�IndexKeyFunc�Label�ValueKeyFunc)�function)�InvalidIndexError)�Appender�Substitution�doc)�validate_bool_kwarg�validate_percentile)�convert_dtypes�maybe_cast_to_extension_array�validate_numeric_casting)
�ensure_platform_int�is_bool�is_categorical_dtype�is_dict_like�is_extension_array_dtype�
is_integer�is_iterator�is_list_like�is_object_dtype�	is_scalar)�ABCDataFrame)�is_hashable)�isna�na_value_for_dtype�notna�remove_na_arraylike)�
algorithms�base�generic�nanops�ops)�CachedAccessor)�ExtensionArray)�CategoricalAccessor)�SparseAccessor)�!create_series_with_explicit_dtype�
extract_array�
is_empty_data�sanitize_array)�NDFrame)�deprecate_ndim_indexing�
unpack_1tuple)�CombinedDatetimelikeProperties)�Float64Index�Index�
MultiIndex�ensure_index)�
DatetimeIndex)�PeriodIndex)�TimedeltaIndex)�check_bool_indexer)�SingleBlockManager)�ensure_key_mapped)�
StringMethods)�to_datetime)�	DataFrame)�
SeriesGroupBy�Series�indexz{0 or 'index'}zPaxis : {0 or 'index'}
        Parameter needed for compatibility with DataFrame.z^inplace : boolean, default False
        If True, performs operation inplace and returns None.z
np.ndarray�z
    .. versionadded:: 0.20.0
)�axes�klass�axes_single_arg�axis�inplace�unique�
duplicatedZoptional_byZoptional_mapper�optional_labels�
optional_axisZversionadded_to_excelcs �fdd�}d�j�d�|_|S)z.
    Install the scalar coercion methods.
    cs,t|�dkr�|jd�Std�����dS)N�rzcannot convert the series to )�len�iloc�	TypeError)�self)�	converter��4/tmp/pip-build-5_djhm0z/pandas/pandas/core/series.py�wrapper~sz_coerce_method.<locals>.wrapper�__)�__name__)rfrirg)rfrh�_coerce_methodysrlcs�
eZdZUdZdZedgZee	dhe
jjBZddddhZ
ejje
jjBed	d
g�BZeejjjejjjd�Zeedegdfedegdf�d,dd�Z�d-dd�Zeedd�dd��Zeedd�dd��Zedd��Z dZ!�d.e"e#dd�dd�Z$ee%d�dd��Z&ee%d�dd ��Z'eed�d!d"��Z(e(j)edd#�d$d"��Z(ed%d&��Z*ed'd(��Z+e,ejj-j�ee.d�d)d*���Z-�d/d,d-�Z/e"d�d.d/�Z0�d0dd�d0d1�Z1e2e.e3j4fZ5ee	eed2�d3d4�Z6�d1e3j4d�d5d6�Z7e8e9�Z:e8e"�Z;e8e"�Z<eee2d�d7d8��Z=e,e
jj>j��d2dd�d:d;��Z>�d3d<d=�Z?�d4e"e"d>�d?d@�Z@�d5eAe"ddA�dBdC�ZBdDdE�ZCdFdG�ZDdHdI�ZEdJdK�ZF�d6e#dL�dMdN�ZGdOdP�ZHdQdR�ZIdSdT�ZJdUdV�ZKdWdX�ZL�d7e#dL�dYdZ�ZMed[d\��ZN�d8dd�d]d^�ZO�d9d_d`�ZPe	d�dadb�ZQ�d:dedf�ZReSeTdgeUdh�di��d;eVeWe	eVe	e#eVe	dj�dkdl��ZXeYeZeefd�dmdn�Z[e,e[j�eYeZeefd�dodp��Z\e2d�dqdr�Z]e^fdsdt�Z_�d<dd�dudv�Z`�d=dd�dwdx�Zae,dy�e,e
jbdzeT�dd9dddddddecd
ddf	e#e#e#e#e#e#d{d|�d}d~���Zd�d>dd��Ze�d?dd�d�d��Zf�fd�d��Zg�d@eVdd��fd�d��
Zh�dAdd��fd�d��
Zi�dBd�d��Zj�dCd�d��Zk�dDdd�d�d��Zl�dEd�d��Zm�dFe9d�d�d��Zn�dGdeVe"eVe"e9d��d�d��ZoeSdd�deUd��d���dHe"dd��d�d���Zp�dIe9d�d�d��Zqd�d��Zrd�d��Zsd�d��ZteSejjudd���dJd�d���Zu�dKd�d��Zv�dLd�d��ZwexeyeZeyeyffeexdeZ�dMfd��d�d��Zze,d��e,e
jbd�eT��dNde{e#e#e|d���fd�d��
��Z}�dOdd�d�d��Z~dd�d�d��Zdd�d�d��Z��dPe#e	e	e#e�d��d�dÄZ��dQe#e#e	e	e#e#e�dĜd�dƄZ��dRdd�d�dȄZ��dSdd�d�d˄Z��dTdd�d�d̈́Z��dWdd�d�dЄZ�dd�d�d҄Z��dXe#ddӜd�dՄZ��dZd�dׄZ��d[dd��fd�dل
Z��d\dd�d�dۄZ�eUd܃Z�eUd݃Z�eSe
jbd�eTdgeTd�e�e�d�d��d]d�d��Z�e�Z�eSej�eTdgeTd�d��d^�fd�d�	�Z�ddffd�d�Z��d_d�d�Z�d�d�Z�d�d�Z�eSej�eTdgeTd�d��d`�fd�d�	�Z��dadddd
dd�d���fd�d��Z�e,d��e�feTd�d�d�d����e,e
jj�j��dbe{e#d���fd�d��
���Z�eSej�eTdgeTd�eTd�eTd��d��dc�f�d�d�	�Z��dddd��f�d�d�
Z�eSej�feT��deeVdd��f�d�d�
�Z�ee�d��f�d	�d
�Z�eSej�eTdgd���df�f�d�d
�	�Z�eSej�eTdgd���dgdd��f�d�d�
�Z��dh�f�d�d�	Z�dd��d�d�Z��didd��d�d�Z��dje#e#e#e#d�d��d�d�Z�eSej�eTdgd��dd��f�d�d��Z�eSej�eTdgd��dd��f�d�d��Z�eSej�eTdgd��dd��f�d�d��Z�eSej�eTdgd��dd��f�d�d ��Z��dk�d!�d"�Z��dldd��d$�d%�Z��dmdd��d&�d'�Z�dgZ�d
Z�e�e��Z�d9Z�dZ�e�j�d9�d(�d)�Z��d*�e�de��Z	e�de��Z�e�de��Z�e��d+e�j�j��Z�e�de��Z�e�j�j�Z‡Z�S(nrUa
    One-dimensional ndarray with axis labels (including time series).

    Labels need not be unique but must be a hashable type. The object
    supports both integer- and label-based indexing and provides a host of
    methods for performing operations involving the index. Statistical
    methods from ndarray have been overridden to automatically exclude
    missing data (currently represented as NaN).

    Operations between Series (+, -, /, *, **) align values based on their
    associated index values-- they need not be the same length. The result
    index will be the sorted union of the two indexes.

    Parameters
    ----------
    data : array-like, Iterable, dict, or scalar value
        Contains data stored in Series.

        .. versionchanged:: 0.23.0
           If data is a dict, argument order is maintained for Python 3.6
           and later.

    index : array-like or Index (1d)
        Values must be hashable and have the same length as `data`.
        Non-unique index values are allowed. Will default to
        RangeIndex (0, 1, 2, ..., n) if not provided. If both a dict and index
        sequence are used, the index will override the keys found in the
        dict.
    dtype : str, numpy.dtype, or ExtensionDtype, optional
        Data type for the output Series. If not specified, this will be
        inferred from `data`.
        See the :ref:`user guide <basics.dtypes>` for more usages.
    name : str, optional
        The name to give to the Series.
    copy : bool, default False
        Copy input data.
    Zseries�namerV�dt�cat�str�sparse�compressZptp)r NFcCst|t�r8|dkr8|dkr8|dkr8tj||�||_dS|rpt|t�sRtj||�}|r^|j�}|dkrl|j}�n|tj	||t
|��}t|�r�|dkr�tj
dtdd�|dk	r�t|�}|dkr�i}|dk	r�|j|�}t|t�r�td���n0t|t��r|dk	�r|j|�}n
|jj�}d}n�t|tj��r<t|j��rtd��n�t|t��rt|dk�rZ|j}n|j||d�}d}|j}n�t|��r�|j|||�\}}d}d}n|t|t��r�|dk�r�|j}n|jj |��s�|�rt!d��n>t"|��r�n2t|t#t$f��rt%d	t
|�j&�d
���n
t'j(|�}|dk�r@t)|��s0|g}tj*t|��}nVt)|��r�y4t|�t|�k�r|tdt|��dt|��d
���Wnt%k
�r�YnXt|t��r�|dk	�r�|j|d|d�}n|�r�|j�}nt+||||dd�}tj||�}t,jj||�||_|j-d|dd�dS)NFz�The default dtype for empty Series will be 'object' instead of 'float64' in a future version. Specify a dtype explicitly to silence this warning.�)�
stacklevelz8initializing a Series from a MultiIndex is not supportedzVCannot construct a Series from an ndarray with compound dtype.  Use DataFrame instead.)�copyzkCannot pass both SingleBlockManager `data` argument and a different `index` argument. `copy` must be False.�'z' type is unorderedzLength of passed values is z, index implies �.�ignore)�dtype�errorsruT)Zraise_cast_failurer)�fastpath).�
isinstancerOrC�__init__rmZ
from_arrayrurV�ibaseZmaybe_extract_name�typerA�warnings�warn�DeprecationWarningrJZ_validate_dtyperI�NotImplementedErrorrH�astype�_values�np�ndarrayrbry�
ValueErrorrU�reindex�_mgrr)�
_init_dict�equals�AssertionErrorr*�set�	frozensetrdrk�comZmaybe_iterable_to_listr-�
default_indexrBr8�	_set_axis)re�datarVryrmrur{rgrgrhr}�s�















 

zSeries.__init__cCsv|rt|j��\}}t|�}n |dk	r4t|�}|}n
gg}}t|||tjd�}|rj|dk	rj|j|dd�}|j|j	fS)a7
        Derive the "_mgr" and "index" attributes of a new Series from a
        dictionary input.

        Parameters
        ----------
        data : dict or dict-like
            Data used to populate the new Series.
        index : Index or index-like, default None
            Index for the new Series: if None, use dict keys.
        dtype : dtype, default None
            The dtype for the new Series: if None, infer from data.

        Returns
        -------
        _data : BlockManager for the new Series
        index : index for the new Series
        N)rVryZdtype_if_emptyF)ru)
�zip�items�listr3r?r�Zfloat64r�r�rV)rer�rVry�keys�values�srgrgrhr�Os

zSeries._init_dict)�returncCstS)N)rU)rergrgrh�_constructor}szSeries._constructorrScCsddlm}|S)Nr)rS)�pandas.core.framerS)rerSrgrgrh�_constructor_expanddim�szSeries._constructor_expanddimcCs|jjS)N)r��_can_hold_na)rergrgrhr��szSeries._can_hold_na)r[r{r�cCs�|st|�}|j}|r`t|tttf�s`yt|�}|rB|jj||�Wntj	t
fk
r^YnXtj|d|�|s�|jj||�dS)z�
        Override generic, we want to set the _typ here.

        This is called from the cython code when we set the `index` attribute
        directly, e.g. `series.index = [1, 2, 3]`.
        �_indexN)
rJ�is_all_datesr|rKrLrMr��set_axisrZOutOfBoundsDatetimer��object�__setattr__)rer[�labelsr{r�rgrgrhr��szSeries._set_axiscCs|jjS)zA
        Return the dtype object of the underlying data.
        )r�ry)rergrgrhry�szSeries.dtypecCs|jS)zA
        Return the dtype object of the underlying data.
        )ry)rergrgrh�dtypes�sz
Series.dtypescCs|jS)aN
        Return the name of the Series.

        The name of a Series becomes its index or column name if it is used
        to form a DataFrame. It is also used whenever displaying the Series
        using the interpreter.

        Returns
        -------
        label (hashable object)
            The name of the Series, also the column name if part of a DataFrame.

        See Also
        --------
        Series.rename : Sets the Series name when given a scalar input.
        Index.name : Corresponding Index property.

        Examples
        --------
        The Series name can be set initially when calling the constructor.

        >>> s = pd.Series([1, 2, 3], dtype=np.int64, name='Numbers')
        >>> s
        0    1
        1    2
        2    3
        Name: Numbers, dtype: int64
        >>> s.name = "Integers"
        >>> s
        0    1
        1    2
        2    3
        Name: Integers, dtype: int64

        The name of a Series within a DataFrame is its column name.

        >>> df = pd.DataFrame([[1, 2], [3, 4], [5, 6]],
        ...                   columns=["Odd Numbers", "Even Numbers"])
        >>> df
           Odd Numbers  Even Numbers
        0            1             2
        1            3             4
        2            5             6
        >>> df["Even Numbers"].name
        'Even Numbers'
        )�_name)rergrgrhrm�s0zSeries.name)�valuer�cCs"t|�std��tj|d|�dS)Nz#Series.name must be a hashable typer�)r1rdr�r�)rer�rgrgrhrm�scCs
|jj�S)a�
        Return Series as ndarray or ndarray-like depending on the dtype.

        .. warning::

           We recommend using :attr:`Series.array` or
           :meth:`Series.to_numpy`, depending on whether you need
           a reference to the underlying data or a NumPy array.

        Returns
        -------
        numpy.ndarray or ndarray-like

        See Also
        --------
        Series.array : Reference to the underlying data.
        Series.to_numpy : A NumPy array representing the underlying data.

        Examples
        --------
        >>> pd.Series([1, 2, 3]).values
        array([1, 2, 3])

        >>> pd.Series(list('aabc')).values
        array(['a', 'a', 'b', 'c'], dtype=object)

        >>> pd.Series(list('aabc')).astype('category').values
        ['a', 'a', 'b', 'c']
        Categories (3, object): ['a', 'b', 'c']

        Timezone aware datetime data is converted to UTC:

        >>> pd.Series(pd.date_range('20130101', periods=3,
        ...                         tz='US/Eastern')).values
        array(['2013-01-01T05:00:00.000000000',
               '2013-01-02T05:00:00.000000000',
               '2013-01-03T05:00:00.000000000'], dtype='datetime64[ns]')
        )r�Zexternal_values)rergrgrhr��s(z
Series.valuescCs
|jj�S)a
        Return the internal repr of this data (defined by Block.interval_values).
        This are the values as stored in the Block (ndarray or ExtensionArray
        depending on the Block class), with datetime64[ns] and timedelta64[ns]
        wrapped in ExtensionArrays to match Index._values behavior.

        Differs from the public ``.values`` for certain data types, because of
        historical backwards compatibility of the public attribute (e.g. period
        returns object ndarray and datetimetz a datetime64[ns] ndarray for
        ``.values`` while it returns an ExtensionArray for ``._values`` in those
        cases).

        Differs from ``.array`` in that this still returns the numpy array if
        the Block is backed by a numpy array (except for datetime64 and
        timedelta64 dtypes), while ``.array`` ensures to always return an
        ExtensionArray.

        Overview:

        dtype       | values        | _values       | array         |
        ----------- | ------------- | ------------- | ------------- |
        Numeric     | ndarray       | ndarray       | PandasArray   |
        Category    | Categorical   | Categorical   | Categorical   |
        dt64[ns]    | ndarray[M8ns] | DatetimeArray | DatetimeArray |
        dt64[ns tz] | ndarray[M8ns] | DatetimeArray | DatetimeArray |
        td64[ns]    | ndarray[m8ns] | TimedeltaArray| ndarray[m8ns] |
        Period      | ndarray[obj]  | PeriodArray   | PeriodArray   |
        Nullable    | EA            | EA            | EA            |

        )r�Zinternal_values)rergrgrhr�s zSeries._valuescCs|jjj�S)N)r��_blockZarray_values)rergrgrh�array>szSeries.array�CcCs|jj|d�S)a
        Return the flattened underlying data as an ndarray.

        Returns
        -------
        numpy.ndarray or ndarray-like
            Flattened data of the Series.

        See Also
        --------
        numpy.ndarray.ravel : Return a flattened array.
        )�order)r��ravel)rer�rgrgrhr�Ds
zSeries.ravelcCs
t|j�S)z2
        Return the length of the Series.
        )rbr�)rergrgrh�__len__SszSeries.__len__cCs"|j|jj|�|jd�j|dd�S)a�
        Create a new view of the Series.

        This function will return a new Series with a view of the same
        underlying values in memory, optionally reinterpreted with a new data
        type. The new data type must preserve the same size in bytes as to not
        cause index misalignment.

        Parameters
        ----------
        dtype : data type
            Data type object or one of their string representations.

        Returns
        -------
        Series
            A new Series object as a view of the same data in memory.

        See Also
        --------
        numpy.ndarray.view : Equivalent numpy function to create a new view of
            the same data in memory.

        Notes
        -----
        Series are instantiated with ``dtype=float64`` by default. While
        ``numpy.ndarray.view()`` will return a view with the same data type as
        the original array, ``Series.view()`` (without specified dtype)
        will try using ``float64`` and may fail if the original data type size
        in bytes is not the same.

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

        The 8 bit signed integer representation of `-1` is `0b11111111`, but
        the same bytes represent 255 if read as an 8 bit unsigned integer:

        >>> us = s.view('uint8')
        >>> us
        0    254
        1    255
        2      0
        3      1
        4      2
        dtype: uint8

        The views share the same underlying values:

        >>> us[0] = 128
        >>> s
        0   -128
        1     -1
        2      0
        3      1
        4      2
        dtype: int8
        )rV�view)�method)r�r�r�rV�__finalize__)reryrgrgrhr�YsBzSeries.view)�ufuncr��inputs�kwargscs�t��}tj�|�f|�|�}|tk	r*|Stjj|jf}xT|D]L}t|d�oV|j�jk}	t|d�o|t|�j|ko|t	|�j
�}
|	s�|
r>tSq>Wdd�|D�}tdd�|D��}dd�t||�D�}
t
|
�dk�r|
d	j�x|
dd�D]}�|jO�q�Wt�fd
d�t||�D��}n�j�tdd�|D��}t|��||�}t
t|��dk�rZ|d	nd�����fdd
��t|�tk�r�t�fdd�|D��S�dk�r�dS�|�SdS)N�__array_priority__�__array_ufunc__cSs g|]}t|d�rt|d��qS)rm)�hasattr�getattr)�.0�xrgrgrh�
<listcomp>�sz*Series.__array_ufunc__.<locals>.<listcomp>css|]}t|�VqdS)N)r)r�r�rgrgrh�	<genexpr>�sz)Series.__array_ufunc__.<locals>.<genexpr>cSsg|]\}}t|t�r|�qSrg)�
issubclassrU)r�r��trgrgrhr��srarc3s*|]"\}}t|t�r|j��n|VqdS)N)r�rUr�)r�r�r�)rVrgrhr��scss|]}t|dd�VqdS)T)Z
extract_numpyN)r@)r�r�rgrgrhr��scs:tj|�r|S|jdkr(�dkr$t�|S�j|��dd�S)Nra�outerF)rVrmru)rr/�ndimr�r�)�result)rVr�rmrergrh�construct_return�s

z0Series.__array_ufunc__.<locals>.construct_returnc3s|]}�|�VqdS)Nrg)r�r�)r�rgrhr��sZat)rr:Z!maybe_dispatch_ufunc_to_dunder_op�NotImplementedr�r�r�r�r�r|�_HANDLED_TYPES�tupler�rbrVr�r�)rer�r�r�r��clsr�Zno_defer�itemZhigher_priorityZhas_array_ufunc�names�typesZ	alignabler�rg)r�rVr�rmrerhr��sD





zSeries.__array_ufunc__cCstj|j|�S)a"
        Return the values as a NumPy array.

        Users should not call this directly. Rather, it is invoked by
        :func:`numpy.array` and :func:`numpy.asarray`.

        Parameters
        ----------
        dtype : str or numpy.dtype, optional
            The dtype to use for the resulting NumPy array. By default,
            the dtype is inferred from the data.

        Returns
        -------
        numpy.ndarray
            The values in the series converted to a :class:`numpy.ndarray`
            with the specified `dtype`.

        See Also
        --------
        array : Create a new array from data.
        Series.array : Zero-copy view to the array backing the Series.
        Series.to_numpy : Series method for similar behavior.

        Examples
        --------
        >>> ser = pd.Series([1, 2, 3])
        >>> np.asarray(ser)
        array([1, 2, 3])

        For timezone-aware data, the timezones may be retained with
        ``dtype='object'``

        >>> tzser = pd.Series(pd.date_range('2000', periods=2, tz="CET"))
        >>> np.asarray(tzser, 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 the values may be localized to UTC and the tzinfo discarded with
        ``dtype='datetime64[ns]'``

        >>> np.asarray(tzser, dtype="datetime64[ns]")  # doctest: +ELLIPSIS
        array(['1999-12-31T23:00:00.000000000', ...],
              dtype='datetime64[ns]')
        )r��asarrayr�)reryrgrgrh�	__array__�s/zSeries.__array__cCs|jgS)z7
        Return a list of the row axis labels.
        )rV)rergrgrhrX*szSeries.axesrcKsd|dk	rtjdtdd�tjt�|�t|�}|jj|�}|j	j|�}|j
||dd�}|j|dd�S)Nz�is_copy is deprecated and will be removed in a future version. 'take' always returns a copy, so there is no need to specify this.rs)rtT)rVr{�take)r�)r�r��
FutureWarning�nvZ
validate_taker�r&rVr�r�r�r�)re�indicesr[Zis_copyr��	new_index�
new_valuesr�rgrgrhr�4szSeries.takecCs|j||d�S)af
        Internal version of the `take` method that sets the `_is_copy`
        attribute to keep track of the parent dataframe (using in indexing
        for the SettingWithCopyWarning). For Series this does the same
        as the public take (it never sets `_is_copy`).

        See the docstring of `take` for full explanation of the parameters.
        )r�r[)r�)rer�r[rgrgrh�_take_with_is_copyFs	zSeries._take_with_is_copy)�ir[cCs
|j|S)z�
        Return the i-th value or values in the Series by location.

        Parameters
        ----------
        i : int

        Returns
        -------
        scalar (int) or Series (slice, sequence)
        )r�)rer�r[rgrgrh�_ixsQszSeries._ixs)�slobjr[r�cCs
|j|�S)N)�_get_values)rer�r[rgrgrh�_slice_sz
Series._slicecCs�tj||�}|tkr|St|�}t|ttf�r6t|�}t|�rR|j	j
�rR|j|S|r`|j|�St
|�r�y|j|�}|Sttfk
r�t|t�r�t|j	t�r�|j|�SYnXt|�r�t|�}tj|�r�t|j	|�}tj|td�}|j|�S|j|�S)N)ry)r��apply_if_callable�Ellipsisr/r|r�r�rEr+rV�_should_fallback_to_positionalr��
_get_valuer1�KeyErrorrdrI�_get_values_tupler,�is_bool_indexerrNr�r��boolr��	_get_with)re�keyZ
key_is_scalarr�rgrgrh�__getitem__ds0




zSeries.__getitem__cCs�t|t�r$|jj|dd�}|j|�St|t�r8td��n&t|t�rL|j|�St	|�s^|j
|St|ttj
tttf�s|t|�}t|t�r�|j}ntj|dd�}|dkr�|jj�s�|j
|S|j|S|j
|S)N�getitem)�kindzWIndexing a Series with DataFrame is not supported, use the appropriate DataFrame columnF)�skipna�integer)r|�slicerV�_convert_slice_indexerr�r0rdr�r�r-�locr�r�r�r<rUrH�
inferred_typer�infer_dtyper�rc)rer�r��key_typergrgrhr��s(









zSeries._get_withcCsbtj|�r$|j|�}t|dd�|St|jt�s8td��|jj|�\}}|j	|j
||d�j|�S)N�)rtz0key of type tuple not found and not a MultiIndex)rV)r�Zany_noner�rDr|rVrIr�Z
get_loc_levelr�r�r�)rer�r��indexerr�rgrgrhr��s

zSeries._get_values_tuplecCs>y|j|jj|��j|�Stk
r8tj|j�|SXdS)N)r�r�Z	get_slicer�r�r�r�r�)rer�rgrgrhr��szSeries._get_values)�takeablecCs*|r|j|S|jj|�}|jj|||�S)z�
        Quickly retrieve single value at passed index label.

        Parameters
        ----------
        label : object
        takeable : interpret the index as indexers, default False

        Returns
        -------
        scalar value
        )r�rV�get_locZ_get_values_for_loc)re�labelr�r�rgrgrhr��s

zSeries._get_valuecCsBtj||�}|j�}|tkr$td�}y|j||�Wn�ttfk
r||j}t	|�rn|j
jdkrn|||<n
||j|<Yn�t
k
�r.}z�t|t�r�t|j
t�r�td�|�tj|��rt|j
|�}tj|td�}y|j||dd�Wn tk
�r||j|<YnXdS|j||�WYdd}~XnX|�r>|j�dS)Nr�z0key of type tuple not found and not a MultiIndex)ryT)r\)r�r�Z%_check_is_chained_assignment_possibler�r��_set_with_enginer�r�r�r+rVr�r�rdr|r�rIr�rNr�r�r�Z_whererrc�	_set_with�_maybe_update_cacher)rer�r�Zcacher_needs_updatingr��errrgrgrh�__setitem__�s6
zSeries.__setitem__cCs(|jjj|�}t|j|�||j|<dS)N)rVZ_enginer�r%ryr�)rer�r�r�rgrgrhr�szSeries._set_with_enginecCs�t|t�r&|jj|dd�}|j||�St|t�s6t�t|�rD|g}t|t�r\|j	}|j
}ntj|dd�}|dkr�|jj
�s�|j||�q�|j||�n
||j|<dS)Nr�)r�F)r�r�)r|r�rVr��_set_valuesr�r�r/rHr�r�rr�r��_set_labelsr�)rer�r�r�r�rgrgrhr�s


zSeries._set_withcCsHtj|�}|jj|�}|dk}|j�r8t||�d���|j||�dS)Nraz
 not in index���)r�Zasarray_tuplesaferVZget_indexer�anyr�r�)rer�r�r��maskrgrgrhr�*s
zSeries._set_labelscCs.t|t�r|j}|jj||d�|_|j�dS)N)r�r�)r|rUr�r��setitemr�)rer�r�rgrgrhr�2s
zSeries._set_valuescCsZy6|r||j|<n"|jj|�}t|j|�||j|<Wntk
rT||j|<YnXdS)a�
        Quickly set single value at passed label.

        If label is not contained, a new object is created with the label
        placed at the end of the result index.

        Parameters
        ----------
        label : object
            Partial indexing with MultiIndex not allowed.
        value : object
            Scalar value.
        takeable : interpret the index as indexers, default False
        N)r�rVr�r%ryr�r�)rer�r�r�r�rgrgrh�
_set_value8szSeries._set_valuecCsdS)NFrg)rergrgrh�_is_mixed_typeVszSeries._is_mixed_typecCsDtjt�t|d��|jj|�}|jj|�}|j||d�j|dd�S)a�
        Repeat elements of a Series.

        Returns a new Series where each element of the current Series
        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
            Series.
        axis : None
            Must be ``None``. Has no effect but is accepted for compatibility
            with numpy.

        Returns
        -------
        Series
            Newly created Series with repeated elements.

        See Also
        --------
        Index.repeat : Equivalent function for Index.
        numpy.repeat : Similar method for :class:`numpy.ndarray`.

        Examples
        --------
        >>> s = pd.Series(['a', 'b', 'c'])
        >>> s
        0    a
        1    b
        2    c
        dtype: object
        >>> s.repeat(2)
        0    a
        0    a
        1    b
        1    b
        2    c
        2    c
        dtype: object
        >>> s.repeat([1, 2, 3])
        0    a
        1    b
        1    b
        2    c
        2    c
        2    c
        dtype: object
        )r[)rV�repeat)r�)	r�Zvalidate_repeatr��dictrVr�r�r�r�)reZrepeatsr[r�r�rgrgrhr�Zs
4z
Series.repeatcs�t|d�}|r�tjt���}|dk	rft|ttf�s8|g}�fdd�|D�}t|��jjkrf�jj	|�}|r~|�_|px�j
�_
qĈj�jj
�|d�j�dd�Sn&|r�td��n�j|�}|j||d	�SdS)
a

        Generate a new DataFrame or Series with the index reset.

        This is useful when the index needs to be treated as a column, or
        when the index is meaningless and needs to be reset to the default
        before another operation.

        Parameters
        ----------
        level : int, str, tuple, or list, default optional
            For a Series with a MultiIndex, only remove the specified levels
            from the index. Removes all levels by default.
        drop : bool, default False
            Just reset the index, without inserting it as a column in
            the new DataFrame.
        name : object, optional
            The name to use for the column containing the original Series
            values. Uses ``self.name`` by default. This argument is ignored
            when `drop` is True.
        inplace : bool, default False
            Modify the Series in place (do not create a new object).

        Returns
        -------
        Series or DataFrame
            When `drop` is False (the default), a DataFrame is returned.
            The newly created columns will come first in the DataFrame,
            followed by the original Series values.
            When `drop` is True, a `Series` is returned.
            In either case, if ``inplace=True``, no value is returned.

        See Also
        --------
        DataFrame.reset_index: Analogous function for DataFrame.

        Examples
        --------
        >>> s = pd.Series([1, 2, 3, 4], name='foo',
        ...               index=pd.Index(['a', 'b', 'c', 'd'], name='idx'))

        Generate a DataFrame with default index.

        >>> s.reset_index()
          idx  foo
        0   a    1
        1   b    2
        2   c    3
        3   d    4

        To specify the name of the new column use `name`.

        >>> s.reset_index(name='values')
          idx  values
        0   a       1
        1   b       2
        2   c       3
        3   d       4

        To generate a new Series with the default set `drop` to True.

        >>> s.reset_index(drop=True)
        0    1
        1    2
        2    3
        3    4
        Name: foo, dtype: int64

        To update the Series in place, without generating a new one
        set `inplace` to True. Note that it also requires ``drop=True``.

        >>> s.reset_index(inplace=True, drop=True)
        >>> s
        0    1
        1    2
        2    3
        3    4
        Name: foo, dtype: int64

        The `level` parameter is interesting for Series with a multi-level
        index.

        >>> arrays = [np.array(['bar', 'bar', 'baz', 'baz']),
        ...           np.array(['one', 'two', 'one', 'two'])]
        >>> s2 = pd.Series(
        ...     range(4), name='foo',
        ...     index=pd.MultiIndex.from_arrays(arrays,
        ...                                     names=['a', 'b']))

        To remove a specific level from the Index, use `level`.

        >>> s2.reset_index(level='a')
               a  foo
        b
        one  bar    0
        two  bar    1
        one  baz    2
        two  baz    3

        If `level` is not set, all levels are removed from the Index.

        >>> s2.reset_index()
             a    b  foo
        0  bar  one    0
        1  bar  two    1
        2  baz  one    2
        3  baz  two    3
        r\Ncsg|]}�jj|��qSrg)rV�_get_level_number)r��lev)rergrhr�sz&Series.reset_index.<locals>.<listcomp>)rV�reset_index)r�z<Cannot reset_index inplace on a Series to create a DataFrame)�level�drop)r!r~r�rbr|r�r�rVZnlevelsZ	droplevelrmr�r�rur�rd�to_framer)rerrrmr\r��dfrg)rerhr�s(l

zSeries.reset_indexcCsptd�}t�\}}td�dkr"|ntd�}td�dkr:|ntd�}td�}|j||j|j|||d�|j�}|S)zI
        Return a string representation for a particular Series.
        rWzdisplay.max_rowsrzdisplay.min_rowszdisplay.show_dimensions)�bufrmry�min_rows�max_rows�length)rrr�	to_stringrmry�getvalue)rer�width�heightr	rZshow_dimensionsr�rgrgrh�__repr__s 
zSeries.__repr__�NaNTcCs�tj|||||||||
|	d�
}|j�}t|t�sHtdtt|�j�����|dkrT|Sy|j	|�Wn4t
k
r�t|d��}
|
j	|�WdQRXYnXdS)a�
        Render a string representation of the Series.

        Parameters
        ----------
        buf : StringIO-like, optional
            Buffer to write to.
        na_rep : str, optional
            String representation of NaN to use, default 'NaN'.
        float_format : one-parameter function, optional
            Formatter function to apply to columns' elements if they are
            floats, default None.
        header : bool, default True
            Add the Series header (index name).
        index : bool, optional
            Add index (row) labels, default True.
        length : bool, default False
            Add the Series length.
        dtype : bool, default False
            Add the Series dtype.
        name : bool, default False
            Add the Series name if not None.
        max_rows : int, optional
            Maximum number of rows to show before truncating. If None, show
            all.
        min_rows : int, optional
            The number of rows to display in a truncated repr (when number
            of rows is above `max_rows`).

        Returns
        -------
        str or None
            String representation of Series if ``buf=None``, otherwise None.
        )	rmr
�headerrVry�na_rep�float_formatrr	z.result must be of type str, type of result is N�w)�fmtZSeriesFormatterrr|rpr��reprrrk�write�AttributeError�open)rerrrrrVr
ryrmr	r�	formatterr��frgrgrhr<s,/
zSeries.to_stringrYaa
            Examples
            --------
            >>> s = pd.Series(["elk", "pig", "dog", "quetzal"], name="animal")
            >>> print(s.to_markdown())
            |    | animal   |
            |---:|:---------|
            |  0 | elk      |
            |  1 | pig      |
            |  2 | dog      |
            |  3 | quetzal  |
            )rY�examples)r�moderVr�cKs|j�j|||f|�S)a^
        Print {klass} in Markdown-friendly format.

        .. versionadded:: 1.0.0

        Parameters
        ----------
        buf : str, Path or StringIO-like, optional, default None
            Buffer to write to. If None, the output is returned as a string.
        mode : str, optional
            Mode in which file is opened.
        index : bool, optional, default True
            Add index (row) labels.

            .. versionadded:: 1.1.0

        **kwargs
            These parameters will be passed to `tabulate                 <https://pypi.org/project/tabulate>`_.

        Returns
        -------
        str
            {klass} in Markdown-friendly format.

        Examples
        --------
        >>> s = pd.Series(["elk", "pig", "dog", "quetzal"], name="animal")
        >>> print(s.to_markdown())
        |    | animal   |
        |---:|:---------|
        |  0 | elk      |
        |  1 | pig      |
        |  2 | dog      |
        |  3 | quetzal  |

        Output markdown with a tabulate option.

        >>> print(s.to_markdown(tablefmt="grid"))
        +----+----------+
        |    | animal   |
        +====+==========+
        |  0 | elk      |
        +----+----------+
        |  1 | pig      |
        +----+----------+
        |  2 | dog      |
        +----+----------+
        |  3 | quetzal  |
        +----+----------+
        )r�to_markdown)rerrrVr�rgrgrhr�sKzSeries.to_markdowncCstt|j�t|��S)a
        Lazily iterate over (index, value) tuples.

        This method returns an iterable tuple (index, value). This is
        convenient if you want to create a lazy iterator.

        Returns
        -------
        iterable
            Iterable of tuples containing the (index, value) pairs from a
            Series.

        See Also
        --------
        DataFrame.items : Iterate over (column name, Series) pairs.
        DataFrame.iterrows : Iterate over DataFrame rows as (index, Series) pairs.

        Examples
        --------
        >>> s = pd.Series(['A', 'B', 'C'])
        >>> for index, value in s.items():
        ...     print(f"Index : {index}, Value : {value}")
        Index : 0, Value : A
        Index : 1, Value : B
        Index : 2, Value : C
        )r��iterrV)rergrgrhr��szSeries.itemscCs|j�S)N)r�)rergrgrh�	iteritems�szSeries.iteritemscCs|jS)zy
        Return alias for index.

        Returns
        -------
        Index
            Index of the Series.
        )rV)rergrgrhr��s	zSeries.keyscCstj|�}||j��S)a�
        Convert Series to {label -> value} dict or dict-like object.

        Parameters
        ----------
        into : class, default dict
            The collections.abc.Mapping subclass to use as the return
            object. Can be the actual class or an empty
            instance of the mapping type you want.  If you want a
            collections.defaultdict, you must pass it initialized.

        Returns
        -------
        collections.abc.Mapping
            Key-value representation of Series.

        Examples
        --------
        >>> s = pd.Series([1, 2, 3, 4])
        >>> s.to_dict()
        {0: 1, 1: 2, 2: 3, 3: 4}
        >>> from collections import OrderedDict, defaultdict
        >>> s.to_dict(OrderedDict)
        OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
        >>> dd = defaultdict(list)
        >>> s.to_dict(dd)
        defaultdict(<class 'list'>, {0: 1, 1: 2, 2: 3, 3: 4})
        )r�Zstandardize_mappingr�)reZintoZinto_crgrgrh�to_dicts
zSeries.to_dictcCs&|dkr|j|�}n|j||i�}|S)a
        Convert Series to DataFrame.

        Parameters
        ----------
        name : object, default None
            The passed name should substitute for the series name (if it has
            one).

        Returns
        -------
        DataFrame
            DataFrame representation of Series.

        Examples
        --------
        >>> s = pd.Series(["a", "b", "c"],
        ...               name="vals")
        >>> s.to_frame()
          vals
        0    a
        1    b
        2    c
        N)r�)rermrrgrgrhr(szSeries.to_framecCs$t|d�}|r|n|j�}||_|S)z�
        Set the Series name.

        Parameters
        ----------
        name : str
        inplace : bool
            Whether to modify `self` directly or return a copy.
        r\)r!rurm)rermr\Zserrgrgrh�	_set_nameHs

zSeries._set_namea�
Examples
--------
>>> ser = pd.Series([390., 350., 30., 20.],
...                 index=['Falcon', 'Falcon', 'Parrot', 'Parrot'], name="Max Speed")
>>> ser
Falcon    390.0
Falcon    350.0
Parrot     30.0
Parrot     20.0
Name: Max Speed, dtype: float64
>>> ser.groupby(["a", "b", "a", "b"]).mean()
a    210.0
b    185.0
Name: Max Speed, dtype: float64
>>> ser.groupby(level=0).mean()
Falcon    370.0
Parrot     25.0
Name: Max Speed, dtype: float64
>>> ser.groupby(ser > 100).mean()
Max Speed
False     25.0
True     370.0
Name: Max Speed, dtype: float64

**Grouping by Indexes**

We can groupby different levels of a hierarchical index
using the `level` parameter:

>>> arrays = [['Falcon', 'Falcon', 'Parrot', 'Parrot'],
...           ['Captive', 'Wild', 'Captive', 'Wild']]
>>> index = pd.MultiIndex.from_arrays(arrays, names=('Animal', 'Type'))
>>> ser = pd.Series([390., 350., 30., 20.], index=index, name="Max Speed")
>>> ser
Animal  Type
Falcon  Captive    390.0
        Wild       350.0
Parrot  Captive     30.0
        Wild        20.0
Name: Max Speed, dtype: float64
>>> ser.groupby(level=0).mean()
Animal
Falcon    370.0
Parrot     25.0
Name: Max Speed, dtype: float64
>>> ser.groupby(level="Type").mean()
Type
Captive    210.0
Wild       185.0
Name: Max Speed, dtype: float64

We can also choose to include `NA` in group keys or not by defining
`dropna` parameter, the default setting is `True`:

>>> ser = pd.Series([1, 2, 3, 3], index=["a", 'a', 'b', np.nan])
>>> ser.groupby(level=0).sum()
a    3
b    3
dtype: int64

>>> ser.groupby(level=0, dropna=False).sum()
a    3
b    3
NaN  3
dtype: int64

>>> arrays = ['Falcon', 'Falcon', 'Parrot', 'Parrot']
>>> ser = pd.Series([390., 350., 30., 20.], index=arrays, name="Max Speed")
>>> ser.groupby(["a", "b", "a", np.nan]).mean()
a    210.0
b    350.0
Name: Max Speed, dtype: float64

>>> ser.groupby(["a", "b", "a", np.nan], dropna=False).mean()
a    210.0
b    350.0
NaN   20.0
Name: Max Speed, dtype: float64
�groupbyrT)�as_index�sort�
group_keys�squeeze�observed�dropnar�c
Cshddlm}
|tk	r&tjdtdd�nd}|dkrB|dkrBtd��|j|�}|
||||||||||	d�
S)	Nr)rTzNThe `squeeze` parameter is deprecated and will be removed in a future version.rs)rtFz*You have to supply one of 'by' and 'level')
�objr�r[rr$r%r&r'r(r))�pandas.core.groupby.genericrTrr�r�r�rd�_get_axis_number)reZbyr[rr$r%r&r'r(r)rTrgrgrhr#Ws*_

zSeries.groupbycCs�|dkrt|j�j�St|t�r,|jj|�}|jj|}tj|jj	|ddd�}|dk}|j
�r~t|�||<}|j||j
�}|t|j�}tj|t|�p�dd�}|j||dd�j|d	d
�S)a�
        Return number of non-NA/null observations in the Series.

        Parameters
        ----------
        level : int or level name, default None
            If the axis is a MultiIndex (hierarchical), count along a
            particular level, collapsing into a smaller Series.

        Returns
        -------
        int or Series (if level specified)
            Number of non-null values in the Series.

        See Also
        --------
        DataFrame.count : Count non-NA cells for each column or row.

        Examples
        --------
        >>> s = pd.Series([0.0, 1.0, np.nan])
        >>> s.count()
        2
        NFT)Zsubokrura)Z	minlength�int64)rVry�count)r�r�)r4r��sumr|rprVr�levelsr��codesr�rb�insertZ	_na_valuer�Zbincountr�r�)rerrZlevel_codesr�ZcntZobs�outrgrgrhr.�s
zSeries.countcCstj||d�S)aw
        Return the mode(s) of the dataset.

        Always returns Series even if only one value is returned.

        Parameters
        ----------
        dropna : bool, default True
            Don't consider counts of NaN/NaT.

            .. versionadded:: 0.24.0

        Returns
        -------
        Series
            Modes of the Series in sorted order.
        )r))r6r)rer)rgrgrhrszSeries.modecst�j�}|S)a�
        Return unique values of Series object.

        Uniques are returned in order of appearance. Hash table-based unique,
        therefore does NOT sort.

        Returns
        -------
        ndarray or ExtensionArray
            The unique values returned as a NumPy array. See Notes.

        See Also
        --------
        unique : Top-level unique method for any 1-d array-like object.
        Index.unique : Return Index with unique values from an Index object.

        Notes
        -----
        Returns the unique values as a NumPy array. In case of an
        extension-array backed Series, a new
        :class:`~api.extensions.ExtensionArray` of that type with just
        the unique values is returned. This includes

            * Categorical
            * Period
            * Datetime with Timezone
            * Interval
            * Sparse
            * IntegerNA

        See Examples section.

        Examples
        --------
        >>> pd.Series([2, 1, 3, 3], name='A').unique()
        array([2, 1, 3])

        >>> pd.Series([pd.Timestamp('2016-01-01') for _ in range(3)]).unique()
        array(['2016-01-01T00:00:00.000000000'], dtype='datetime64[ns]')

        >>> pd.Series([pd.Timestamp('2016-01-01', tz='US/Eastern')
        ...            for _ in range(3)]).unique()
        <DatetimeArray>
        ['2016-01-01 00:00:00-05:00']
        Length: 1, dtype: datetime64[ns, US/Eastern]

        An unordered Categorical will return categories in the order of
        appearance.

        >>> pd.Series(pd.Categorical(list('baabc'))).unique()
        ['b', 'a', 'c']
        Categories (3, object): ['b', 'a', 'c']

        An ordered Categorical preserves the category ordering.

        >>> pd.Series(pd.Categorical(list('baabc'), categories=list('abc'),
        ...                          ordered=True)).unique()
        ['b', 'a', 'c']
        Categories (3, object): ['a' < 'b' < 'c']
        )�superr])rer�)�	__class__rgrhr]s=
z
Series.unique�firstcs2t|d�}t�j|d�}|r*|j|�dS|SdS)a�
        Return Series with duplicate values removed.

        Parameters
        ----------
        keep : {'first', 'last', ``False``}, default 'first'
            Method to handle dropping duplicates:

            - 'first' : Drop duplicates except for the first occurrence.
            - 'last' : Drop duplicates except for the last occurrence.
            - ``False`` : Drop all duplicates.

        inplace : bool, default ``False``
            If ``True``, performs operation inplace and returns None.

        Returns
        -------
        Series
            Series with duplicates dropped.

        See Also
        --------
        Index.drop_duplicates : Equivalent method on Index.
        DataFrame.drop_duplicates : Equivalent method on DataFrame.
        Series.duplicated : Related method on Series, indicating duplicate
            Series values.

        Examples
        --------
        Generate a Series with duplicated entries.

        >>> s = pd.Series(['lama', 'cow', 'lama', 'beetle', 'lama', 'hippo'],
        ...               name='animal')
        >>> s
        0      lama
        1       cow
        2      lama
        3    beetle
        4      lama
        5     hippo
        Name: animal, dtype: object

        With the 'keep' parameter, the selection behaviour of duplicated values
        can be changed. The value 'first' keeps the first occurrence for each
        set of duplicated entries. The default value of keep is 'first'.

        >>> s.drop_duplicates()
        0      lama
        1       cow
        3    beetle
        5     hippo
        Name: animal, dtype: object

        The value 'last' for parameter 'keep' keeps the last occurrence for
        each set of duplicated entries.

        >>> s.drop_duplicates(keep='last')
        1       cow
        3    beetle
        4      lama
        5     hippo
        Name: animal, dtype: object

        The value ``False`` for parameter 'keep' discards all sets of
        duplicated entries. Setting the value of 'inplace' to ``True`` performs
        the operation inplace and returns ``None``.

        >>> s.drop_duplicates(keep=False, inplace=True)
        >>> s
        1       cow
        3    beetle
        5     hippo
        Name: animal, dtype: object
        r\)�keepN)r!r4�drop_duplicates�_update_inplace)rer7r\r�)r5rgrhr8\sK

zSeries.drop_duplicatescst�j|d�S)aV
        Indicate duplicate Series values.

        Duplicated values are indicated as ``True`` values in the resulting
        Series. Either all duplicates, all except the first or all except the
        last occurrence of duplicates can be indicated.

        Parameters
        ----------
        keep : {'first', 'last', False}, default 'first'
            Method to handle dropping duplicates:

            - 'first' : Mark duplicates as ``True`` except for the first
              occurrence.
            - 'last' : Mark duplicates as ``True`` except for the last
              occurrence.
            - ``False`` : Mark all duplicates as ``True``.

        Returns
        -------
        Series
            Series indicating whether each value has occurred in the
            preceding values.

        See Also
        --------
        Index.duplicated : Equivalent method on pandas.Index.
        DataFrame.duplicated : Equivalent method on pandas.DataFrame.
        Series.drop_duplicates : Remove duplicate values from Series.

        Examples
        --------
        By default, for each set of duplicated values, the first occurrence is
        set on False and all others on True:

        >>> animals = pd.Series(['lama', 'cow', 'lama', 'beetle', 'lama'])
        >>> animals.duplicated()
        0    False
        1    False
        2     True
        3    False
        4     True
        dtype: bool

        which is equivalent to

        >>> animals.duplicated(keep='first')
        0    False
        1    False
        2     True
        3    False
        4     True
        dtype: bool

        By using 'last', the last occurrence of each set of duplicated values
        is set on False and all others on True:

        >>> animals.duplicated(keep='last')
        0     True
        1    False
        2     True
        3    False
        4    False
        dtype: bool

        By setting keep on ``False``, all duplicates are True:

        >>> animals.duplicated(keep=False)
        0     True
        1    False
        2     True
        3    False
        4     True
        dtype: bool
        )r7)r4r^)rer7)r5rgrhr^�sLzSeries.duplicatedcOs6tj|||�}tj|j|d�}|dkr,tjS|j|S)a
        Return the row label of the minimum value.

        If multiple values equal the minimum, the first row label with that
        value is returned.

        Parameters
        ----------
        axis : int, default 0
            For compatibility with DataFrame.idxmin. Redundant for application
            on Series.
        skipna : bool, default True
            Exclude NA/null values. If the entire Series is NA, the result
            will be NA.
        *args, **kwargs
            Additional arguments and keywords have no effect but might be
            accepted for compatibility with NumPy.

        Returns
        -------
        Index
            Label of the minimum value.

        Raises
        ------
        ValueError
            If the Series is empty.

        See Also
        --------
        numpy.argmin : Return indices of the minimum values
            along the given axis.
        DataFrame.idxmin : Return index of first occurrence of minimum
            over requested axis.
        Series.idxmax : Return index *label* of the first occurrence
            of maximum of values.

        Notes
        -----
        This method is the Series version of ``ndarray.argmin``. This method
        returns the label of the minimum, while ``ndarray.argmin`` returns
        the position. To get the position, use ``series.values.argmin()``.

        Examples
        --------
        >>> s = pd.Series(data=[1, None, 4, 1],
        ...               index=['A', 'B', 'C', 'D'])
        >>> s
        A    1.0
        B    NaN
        C    4.0
        D    1.0
        dtype: float64

        >>> s.idxmin()
        'A'

        If `skipna` is False and there is an NA value in the data,
        the function returns ``nan``.

        >>> s.idxmin(skipna=False)
        nan
        )r�rar�)r�Zvalidate_argmin_with_skipnar9Z	nanargminr�r��nanrV)rer[r��argsr�r�rgrgrh�idxmin�s
@z
Series.idxmincOs6tj|||�}tj|j|d�}|dkr,tjS|j|S)a1
        Return the row label of the maximum value.

        If multiple values equal the maximum, the first row label with that
        value is returned.

        Parameters
        ----------
        axis : int, default 0
            For compatibility with DataFrame.idxmax. Redundant for application
            on Series.
        skipna : bool, default True
            Exclude NA/null values. If the entire Series is NA, the result
            will be NA.
        *args, **kwargs
            Additional arguments and keywords have no effect but might be
            accepted for compatibility with NumPy.

        Returns
        -------
        Index
            Label of the maximum value.

        Raises
        ------
        ValueError
            If the Series is empty.

        See Also
        --------
        numpy.argmax : Return indices of the maximum values
            along the given axis.
        DataFrame.idxmax : Return index of first occurrence of maximum
            over requested axis.
        Series.idxmin : Return index *label* of the first occurrence
            of minimum of values.

        Notes
        -----
        This method is the Series version of ``ndarray.argmax``. This method
        returns the label of the maximum, while ``ndarray.argmax`` returns
        the position. To get the position, use ``series.values.argmax()``.

        Examples
        --------
        >>> s = pd.Series(data=[1, None, 4, 3, 4],
        ...               index=['A', 'B', 'C', 'D', 'E'])
        >>> s
        A    1.0
        B    NaN
        C    4.0
        D    3.0
        E    4.0
        dtype: float64

        >>> s.idxmax()
        'C'

        If `skipna` is False and there is an NA value in the data,
        the function returns ``nan``.

        >>> s.idxmax(skipna=False)
        nan
        )r�rar�)r�Zvalidate_argmax_with_skipnar9Z	nanargmaxr�r�r:rV)rer[r�r;r�r�rgrgrh�idxmaxCs
Az
Series.idxmaxcOs6tj||�|jj|�}|j||jd�j|dd�}|S)aa
        Round each value in a Series to the given number of decimals.

        Parameters
        ----------
        decimals : int, default 0
            Number of decimal places to round to. If decimals is negative,
            it specifies the number of positions to the left of the decimal point.
        *args, **kwargs
            Additional arguments and keywords have no effect but might be
            accepted for compatibility with NumPy.

        Returns
        -------
        Series
            Rounded values of the Series.

        See Also
        --------
        numpy.around : Round values of an np.array.
        DataFrame.round : Round values of a DataFrame.

        Examples
        --------
        >>> s = pd.Series([0.1, 1.3, 2.7])
        >>> s.round()
        0    0.0
        1    1.0
        2    3.0
        dtype: float64
        )rV�round)r�)r�Zvalidate_roundr�r>r�rVr�)reZdecimalsr;r�r�rgrgrhr>�s
 
zSeries.round��?�linearcCspt|�|j�}|j||dd�}|jdkr<|jdd�df}t|�rb|j|_|j|t|�|jd�S|jdSdS)a�
        Return value at the given quantile.

        Parameters
        ----------
        q : float or array-like, default 0.5 (50% quantile)
            The quantile(s) to compute, which can lie in range: 0 <= q <= 1.
        interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}
            This optional parameter specifies the interpolation method to use,
            when the desired quantile lies between two data points `i` and `j`:

                * linear: `i + (j - i) * fraction`, where `fraction` is the
                  fractional part of the index surrounded by `i` and `j`.
                * lower: `i`.
                * higher: `j`.
                * nearest: `i` or `j` whichever is nearest.
                * midpoint: (`i` + `j`) / 2.

        Returns
        -------
        float or Series
            If ``q`` is an array, a Series will be returned where the
            index is ``q`` and the values are the quantiles, otherwise
            a float will be returned.

        See Also
        --------
        core.window.Rolling.quantile : Calculate the rolling quantile.
        numpy.percentile : Returns the q-th percentile(s) of the array elements.

        Examples
        --------
        >>> s = pd.Series([1, 2, 3, 4])
        >>> s.quantile(.5)
        2.5
        >>> s.quantile([.25, .5, .75])
        0.25    1.75
        0.50    2.50
        0.75    3.25
        dtype: float64
        F)�q�
interpolation�numeric_onlyrsNr)rVrm)	r"r�quantiler�rcr-rmr�rG)rerArBrr�rgrgrhrD�s*
zSeries.quantile�pearsoncCs`|j|ddd�\}}t|�dkr&tjS|dks6t|�rLtj|j|j||d�Std	|�d
���dS)
a�
        Compute correlation with `other` Series, excluding missing values.

        Parameters
        ----------
        other : Series
            Series with which to compute the correlation.
        method : {'pearson', 'kendall', 'spearman'} or callable
            Method used to compute correlation:

            - pearson : Standard correlation coefficient
            - kendall : Kendall Tau correlation coefficient
            - spearman : Spearman rank correlation
            - callable: Callable with input two 1d ndarrays and returning a float.

            .. versionadded:: 0.24.0
                Note that the returned matrix from corr will have 1 along the
                diagonals and will be symmetric regardless of the callable's
                behavior.
        min_periods : int, optional
            Minimum number of observations needed to have a valid result.

        Returns
        -------
        float
            Correlation with other.

        See Also
        --------
        DataFrame.corr : Compute pairwise correlation between columns.
        DataFrame.corrwith : Compute pairwise correlation with another
            DataFrame or Series.

        Examples
        --------
        >>> def histogram_intersection(a, b):
        ...     v = np.minimum(a, b).sum().round(decimals=1)
        ...     return v
        >>> s1 = pd.Series([.2, .0, .6, .2])
        >>> s2 = pd.Series([.3, .6, .0, .1])
        >>> s1.corr(s2, method=histogram_intersection)
        0.3
        �innerF)�joinrurrE�spearman�kendall)r��min_periodszHmethod must be either 'pearson', 'spearman', 'kendall', or a callable, 'z' was suppliedN)rErHrI)	�alignrbr�r:�callabler9Znancorrr�r�)re�otherr�rJ�thisrgrgrh�corr�s,zSeries.corrra)rMrJ�ddofr�cCs<|j|ddd�\}}t|�dkr&tjStj|j|j||d�S)a�
        Compute covariance with Series, excluding missing values.

        Parameters
        ----------
        other : Series
            Series with which to compute the covariance.
        min_periods : int, optional
            Minimum number of observations needed to have a valid result.
        ddof : int, default 1
            Delta degrees of freedom.  The divisor used in calculations
            is ``N - ddof``, where ``N`` represents the number of elements.

            .. versionadded:: 1.1.0

        Returns
        -------
        float
            Covariance between Series and other normalized by N-1
            (unbiased estimator).

        See Also
        --------
        DataFrame.cov : Compute pairwise covariance of columns.

        Examples
        --------
        >>> s1 = pd.Series([0.90010907, 0.13484424, 0.62036035])
        >>> s2 = pd.Series([0.12528585, 0.26962463, 0.51111198])
        >>> s1.cov(s2)
        -0.01685762652715874
        rFF)rGrur)rJrP)rKrbr�r:r9Znancovr�)rerMrJrPrNrgrgrh�cov(	s
&z
Series.covrWa
        Difference with previous row

        >>> s = pd.Series([1, 1, 2, 3, 5, 8])
        >>> s.diff()
        0    NaN
        1    0.0
        2    1.0
        3    1.0
        4    2.0
        5    3.0
        dtype: float64

        Difference with 3rd previous row

        >>> s.diff(periods=3)
        0    NaN
        1    NaN
        2    NaN
        3    2.0
        4    4.0
        5    6.0
        dtype: float64

        Difference with following row

        >>> s.diff(periods=-1)
        0    0.0
        1   -1.0
        2   -1.0
        3   -2.0
        4   -3.0
        5    NaN
        dtype: float64

        Overflow in input dtype

        >>> s = pd.Series([1, 0], dtype=np.uint8)
        >>> s.diff()
        0      NaN
        1    255.0
        dtype: float64)rYZextra_paramsZother_klassr)�periodsr�cCs(tj|j|�}|j||jd�j|dd�S)a0
        First discrete difference of element.

        Calculates the difference of a {klass} element compared with another
        element in the {klass} (default is element in previous row).

        Parameters
        ----------
        periods : int, default 1
            Periods to shift for calculating difference, accepts negative
            values.
        {extra_params}
        Returns
        -------
        {klass}
            First differences of the Series.

        See Also
        --------
        {klass}.pct_change: Percent change over given number of periods.
        {klass}.shift: Shift index by desired number of periods with an
            optional time freq.
        {other_klass}.diff: First discrete difference of object.

        Notes
        -----
        For boolean dtypes, this uses :meth:`operator.xor` rather than
        :meth:`operator.sub`.
        The result is calculated according to current dtype in {klass},
        however dtype of the result is always float64.

        Examples
        --------
        {examples}
        )rV�diff)r�)r6rSr�r�rVr�)rerRr�rgrgrhrSU	sUzSeries.diffcCs|j|j|��S)a�
        Compute the lag-N autocorrelation.

        This method computes the Pearson correlation between
        the Series and its shifted self.

        Parameters
        ----------
        lag : int, default 1
            Number of lags to apply before performing autocorrelation.

        Returns
        -------
        float
            The Pearson correlation between self and self.shift(lag).

        See Also
        --------
        Series.corr : Compute the correlation between two Series.
        Series.shift : Shift index by desired number of periods.
        DataFrame.corr : Compute pairwise correlation of columns.
        DataFrame.corrwith : Compute pairwise correlation between rows or
            columns of two DataFrame objects.

        Notes
        -----
        If the Pearson correlation is not well defined return 'NaN'.

        Examples
        --------
        >>> s = pd.Series([0.25, 0.5, 0.2, -0.05])
        >>> s.autocorr()  # doctest: +ELLIPSIS
        0.10355...
        >>> s.autocorr(lag=2)  # doctest: +ELLIPSIS
        -0.99999...

        If the Pearson correlation is not well defined, then 'NaN' is returned.

        >>> s = pd.Series([1, 0, 0, 0])
        >>> s.autocorr()
        nan
        )rO�shift)reZlagrgrgrh�autocorr�	s+zSeries.autocorrcCs t|ttf�rr|jj|j�}t|�t|j�ks@t|�t|j�krHtd��|j|dd�}|j|dd�}|j}|j}n<|j}t	j
|�}|jd|jdkr�td|j�d|j����t|t�r�|j
t	j||�|jd�j|dd	�St|t�r�t	j||�St|t	j��r
t	j||�Std
t|�����dS)aC
        Compute the dot product between the Series and the columns of other.

        This method computes the dot product between the Series and another
        one, or the Series and each columns of a DataFrame, or the Series and
        each columns of an array.

        It can also be called using `self @ other` in Python >= 3.5.

        Parameters
        ----------
        other : Series, DataFrame or array-like
            The other object to compute the dot product with its columns.

        Returns
        -------
        scalar, Series or numpy.ndarray
            Return the dot product of the Series and other if other is a
            Series, the Series of the dot product of Series and each rows of
            other if other is a DataFrame or a numpy.ndarray between the Series
            and each columns of the numpy array.

        See Also
        --------
        DataFrame.dot: Compute the matrix product with the DataFrame.
        Series.mul: Multiplication of series and other, element-wise.

        Notes
        -----
        The Series and other has to share the same index if other is a Series
        or a DataFrame.

        Examples
        --------
        >>> s = pd.Series([0, 1, 2, 3])
        >>> other = pd.Series([-1, 2, -3, 4])
        >>> s.dot(other)
        8
        >>> s @ other
        8
        >>> df = pd.DataFrame([[0, 1], [-2, 3], [4, -5], [6, 7]])
        >>> s.dot(df)
        0    24
        1    14
        dtype: int64
        >>> arr = np.array([[0, 1], [-2, 3], [4, -5], [6, 7]])
        >>> s.dot(arr)
        array([24, 14])
        zmatrices are not alignedF)rVrurzDot product shape mismatch, z vs )rV�dot)r�zunsupported type: N)r|rUr0rV�unionrbr�r�r�r�r��shape�	Exceptionr�rV�columnsr�r�rdr)rerM�common�left�rightZlvalsZrvalsrgrgrhrV�	s,2$



z
Series.dotcCs
|j|�S)zQ
        Matrix multiplication using binary `@` operator in Python>=3.5.
        )rV)rerMrgrgrh�
__matmul__*
szSeries.__matmul__cCs|jtj|��S)zQ
        Matrix multiplication using binary `@` operator in Python>=3.5.
        )rVr�Z	transpose)rerMrgrgrh�__rmatmul__0
szSeries.__rmatmul__)rYr\cCstj|j|||d�S)N)�side�sorter)r6�searchsortedr�)rer�r`rargrgrhrb6
szSeries.searchsortedcCshddlm}t|ttf�r,|g}|j|�n||g}tdd�|dd�D��rZd}t|��||||d�S)	u�
        Concatenate two or more Series.

        Parameters
        ----------
        to_append : Series or list/tuple of Series
            Series to append with self.
        ignore_index : bool, default False
            If True, the resulting axis will be labeled 0, 1, …, n - 1.
        verify_integrity : bool, default False
            If True, raise Exception on creating index with duplicates.

        Returns
        -------
        Series
            Concatenated Series.

        See Also
        --------
        concat : General function to concatenate DataFrame or Series objects.

        Notes
        -----
        Iteratively appending to a Series can be more computationally intensive
        than a single concatenate. A better solution is to append values to a
        list and then concatenate the list with the original Series all at
        once.

        Examples
        --------
        >>> s1 = pd.Series([1, 2, 3])
        >>> s2 = pd.Series([4, 5, 6])
        >>> s3 = pd.Series([4, 5, 6], index=[3, 4, 5])
        >>> s1.append(s2)
        0    1
        1    2
        2    3
        0    4
        1    5
        2    6
        dtype: int64

        >>> s1.append(s3)
        0    1
        1    2
        2    3
        3    4
        4    5
        5    6
        dtype: int64

        With `ignore_index` set to True:

        >>> s1.append(s2, ignore_index=True)
        0    1
        1    2
        2    3
        3    4
        4    5
        5    6
        dtype: int64

        With `verify_integrity` set to True:

        >>> s1.append(s2, verify_integrity=True)
        Traceback (most recent call last):
        ...
        ValueError: Indexes have overlapping values: [0, 1, 2]
        r)�concatcss|]}t|tf�VqdS)N)r|r0)r�r�rgrgrhr��
sz Series.append.<locals>.<genexpr>raNzCto_append should be a Series or list/tuple of Series, got DataFrame)�ignore_index�verify_integrity)Zpandas.core.reshape.concatrcr|r�r��extendr�rd)reZ	to_appendrdrercZ	to_concat�msgrgrgrh�append=
sFz
Series.appendc
Cs�t|t�std��|}|jj|j�s:|j||ddd�\}}tj|j|j|�\}}t	j
dd��|||�}WdQRXtj||�}	|j||	�}
|
S)a6
        Perform generic binary operation with optional fill value.

        Parameters
        ----------
        other : Series
        func : binary operator
        fill_value : float or object
            Value to substitute for NA/null values. If both Series are NA in a
            location, the result will be NA regardless of the passed fill value.
        level : int or level name, default None
            Broadcast across a level, matching Index values on the
            passed MultiIndex level.

        Returns
        -------
        Series
        zOther operand must be Seriesr�F)rrGrurx)�allN)
r|rUr�rVr�rKr:Z
fill_binopr�r��errstate�get_op_result_name�_construct_result)rerM�funcr�
fill_valuerNZ	this_valsZ
other_valsr�rm�retrgrgrh�_binop�
s
z
Series._binop)r�rmr�cCsvt|t�rR|j|d|d�}|j|d|d�}t|t�s<t�t|t�sJt�||fS|j||jd�}|j|�}||_|S)a8
        Construct an appropriately-labelled Series from the result of an op.

        Parameters
        ----------
        result : ndarray or ExtensionArray
        name : Label

        Returns
        -------
        Series
            In the case of __divmod__ or __rdivmod__, a 2-tuple of Series.
        r)rmra)rV)	r|r�rlrUr�r�rVr�rm)rer�rmZres1Zres2r3rgrgrhrl�
s

zSeries._construct_resultax
Returns
-------
Series or DataFrame
    If axis is 0 or 'index' the result will be a Series.
    The resulting index will be a MultiIndex with 'self' and 'other'
    stacked alternately at the inner level.

    If axis is 1 or 'columns' the result will be a DataFrame.
    It will have two columns namely 'self' and 'other'.

See Also
--------
DataFrame.compare : Compare with another DataFrame and show differences.

Notes
-----
Matching NaNs will not appear as a difference.

Examples
--------
>>> s1 = pd.Series(["a", "b", "c", "d", "e"])
>>> s2 = pd.Series(["a", "a", "c", "b", "e"])

Align the differences on columns

>>> s1.compare(s2)
  self other
1    b     a
3    d     b

Stack the differences on indices

>>> s1.compare(s2, align_axis=0)
1  self     b
   other    a
3  self     d
   other    b
dtype: object

Keep all original rows

>>> s1.compare(s2, keep_shape=True)
  self other
0  NaN   NaN
1    b     a
2  NaN   NaN
3    d     b
4  NaN   NaN

Keep all original rows and also all original values

>>> s1.compare(s2, keep_shape=True, keep_equal=True)
  self other
0    a     a
1    b     a
2    c     c
3    d     b
4    e     e
�compare)rM�
align_axis�
keep_shape�
keep_equalr�cst�j||||d�S)N)rMrrrsrt)r4rq)rerMrrrsrt)r5rgrhrq�
s
FzSeries.comparec
s�|dkrt|jdd�}t�t�r�|jj�j�}tj|��}g}x�|D]D}|j||�}�j||�}	t	j
dd��|j�||	��WdQRXqDWn:|j}t	j
dd����fdd�|jD�}WdQRX|j
}t|j�r�nt|j�r�tt|j�|�}|j|||d�S)	a�
        Combine the Series with a Series or scalar according to `func`.

        Combine the Series and `other` using `func` to perform elementwise
        selection for combined Series.
        `fill_value` is assumed when value is missing at some index
        from one of the two objects being combined.

        Parameters
        ----------
        other : Series or scalar
            The value(s) to be combined with the `Series`.
        func : function
            Function that takes two scalars as inputs and returns an element.
        fill_value : scalar, optional
            The value to assume when an index is missing from
            one Series or the other. The default specifies to use the
            appropriate NaN value for the underlying dtype of the Series.

        Returns
        -------
        Series
            The result of combining the Series with the other object.

        See Also
        --------
        Series.combine_first : Combine Series values, choosing the calling
            Series' values first.

        Examples
        --------
        Consider 2 Datasets ``s1`` and ``s2`` containing
        highest clocked speeds of different birds.

        >>> s1 = pd.Series({'falcon': 330.0, 'eagle': 160.0})
        >>> s1
        falcon    330.0
        eagle     160.0
        dtype: float64
        >>> s2 = pd.Series({'falcon': 345.0, 'eagle': 200.0, 'duck': 30.0})
        >>> s2
        falcon    345.0
        eagle     200.0
        duck       30.0
        dtype: float64

        Now, to combine the two datasets and view the highest speeds
        of the birds across the two datasets

        >>> s1.combine(s2, max)
        duck        NaN
        eagle     200.0
        falcon    345.0
        dtype: float64

        In the previous example, the resulting value for duck is missing,
        because the maximum of a NaN and a float is a NaN.
        So, in the example, we set ``fill_value=0``,
        so the maximum value returned will be the value from some dataset.

        >>> s1.combine(s2, max, fill_value=0)
        duck       30.0
        eagle     200.0
        falcon    345.0
        dtype: float64
        NF)�compatrx)ricsg|]}�|���qSrgrg)r��lv)rmrMrgrhr�}sz"Series.combine.<locals>.<listcomp>)rVrm)r3ryr|rUrVrWr:rk�getr�rjrhr�rmr(r*r$rr�)
rerMrmrnr��new_namer��idxrv�rvrg)rmrMrh�combine's(C

  

zSeries.combinecCsZ|jj|j�}|j|dd�}|j|dd�}|jjdkrJ|jjdkrJt|�}|jt|�|�S)a�
        Combine Series values, choosing the calling Series's values first.

        Parameters
        ----------
        other : Series
            The value(s) to be combined with the `Series`.

        Returns
        -------
        Series
            The result of combining the Series with the other object.

        See Also
        --------
        Series.combine : Perform elementwise operation on two Series
            using a given function.

        Notes
        -----
        Result index will be the union of the two indexes.

        Examples
        --------
        >>> s1 = pd.Series([1, np.nan])
        >>> s2 = pd.Series([3, 4])
        >>> s1.combine_first(s2)
        0    1.0
        1    4.0
        dtype: float64
        F)ru�M)rVrWr�ryr�rR�wherer4)rerMr�rNrgrgrh�
combine_first�s zSeries.combine_firstcCsBt|t�st|�}|j|�}t|�}|jj||d�|_|j�dS)a�
        Modify Series in place using values from passed Series.

        Uses non-NA values from passed Series to make updates. Aligns
        on index.

        Parameters
        ----------
        other : Series, or object coercible into Series

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

        >>> s = pd.Series(['a', 'b', 'c'])
        >>> s.update(pd.Series(['d', 'e'], index=[0, 2]))
        >>> s
        0    d
        1    b
        2    e
        dtype: object

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

        If ``other`` contains NaNs the corresponding values are not updated
        in the original Series.

        >>> s = pd.Series([1, 2, 3])
        >>> s.update(pd.Series([4, np.nan, 6]))
        >>> s
        0    4
        1    2
        2    6
        dtype: int64

        ``other`` can also be a non-Series object type
        that is coercible into a Series

        >>> s = pd.Series([1, 2, 3])
        >>> s.update([4, np.nan, 6])
        >>> s
        0    4
        1    2
        2    6
        dtype: int64

        >>> s = pd.Series([1, 2, 3])
        >>> s.update({1: 9})
        >>> s
        0    1
        1    9
        2    3
        dtype: int64
        )r��newN)r|rUZreindex_liker4r�Zputmaskr�)rerMr�rgrgrh�update�sD

z
Series.update�	quicksort�last)r\r��na_positionrdr�cs�t|d�}|j|�|r&|jr&td����fdd�}|j}	tjt|�tjd�}
t	|	�}|}t
jt|��}
|||�}t|�r�t|�dkr�tdt|��d���|d	}t
|�s�td
��|s�|ddd�}|dk�r|j�}|
|||
d|�<|
||
|d�<nF|d
k�r8|j�}|
|||
|d�<|
||
d|�<ntd|����|j|	|
|j|
d�}|�rtt
jt|
��|_|�r�|j|�n|j|dd�SdS)uS
        Sort by the values.

        Sort a Series in ascending or descending order by some
        criterion.

        Parameters
        ----------
        axis : {0 or 'index'}, default 0
            Axis to direct sorting. The value 'index' is accepted for
            compatibility with DataFrame.sort_values.
        ascending : bool, default True
            If True, sort values in ascending order, otherwise descending.
        inplace : bool, default False
            If True, perform operation in-place.
        kind : {'quicksort', 'mergesort' or 'heapsort'}, default 'quicksort'
            Choice of sorting algorithm. See also :func:`numpy.sort` for more
            information. 'mergesort' is the only stable  algorithm.
        na_position : {'first' or 'last'}, default 'last'
            Argument 'first' puts NaNs at the beginning, 'last' puts NaNs at
            the end.
        ignore_index : bool, default False
            If True, the resulting axis will be labeled 0, 1, …, n - 1.

            .. versionadded:: 1.0.0

        key : callable, optional
            If not None, apply the key function to the series values
            before sorting. This is similar to the `key` argument in the
            builtin :meth:`sorted` function, with the notable difference that
            this `key` function should be *vectorized*. It should expect a
            ``Series`` and return an array-like.

            .. versionadded:: 1.1.0

        Returns
        -------
        Series
            Series ordered by values.

        See Also
        --------
        Series.sort_index : Sort by the Series indices.
        DataFrame.sort_values : Sort DataFrame by the values along either axis.
        DataFrame.sort_index : Sort DataFrame by indices.

        Examples
        --------
        >>> s = pd.Series([np.nan, 1, 3, 10, 5])
        >>> s
        0     NaN
        1     1.0
        2     3.0
        3     10.0
        4     5.0
        dtype: float64

        Sort values ascending order (default behaviour)

        >>> s.sort_values(ascending=True)
        1     1.0
        2     3.0
        4     5.0
        3    10.0
        0     NaN
        dtype: float64

        Sort values descending order

        >>> s.sort_values(ascending=False)
        3    10.0
        4     5.0
        2     3.0
        1     1.0
        0     NaN
        dtype: float64

        Sort values inplace

        >>> s.sort_values(ascending=False, inplace=True)
        >>> s
        3    10.0
        4     5.0
        2     3.0
        1     1.0
        0     NaN
        dtype: float64

        Sort values putting NAs first

        >>> s.sort_values(na_position='first')
        0     NaN
        1     1.0
        2     3.0
        4     5.0
        3    10.0
        dtype: float64

        Sort a series of strings

        >>> s = pd.Series(['z', 'b', 'd', 'a', 'c'])
        >>> s
        0    z
        1    b
        2    d
        3    a
        4    c
        dtype: object

        >>> s.sort_values()
        3    a
        1    b
        4    c
        2    d
        0    z
        dtype: object

        Sort using a key function. Your `key` function will be
        given the ``Series`` of values and should return an array-like.

        >>> s = pd.Series(['a', 'B', 'c', 'D', 'e'])
        >>> s.sort_values()
        1    B
        3    D
        0    a
        2    c
        4    e
        dtype: object
        >>> s.sort_values(key=lambda x: x.str.lower())
        0    a
        1    B
        2    c
        3    D
        4    e
        dtype: object

        NumPy ufuncs work well here. For example, we can
        sort by the ``sin`` of the value

        >>> s = pd.Series([-4, -2, 0, 2, 4])
        >>> s.sort_values(key=np.sin)
        1   -2
        4    4
        2    0
        0   -4
        3    2
        dtype: int64

        More complicated user-defined functions can be used,
        as long as they expect a Series and return an array-like

        >>> s.sort_values(key=lambda x: (np.tan(x.cumsum())))
        0   -4
        3    2
        4    4
        1   -2
        2    0
        dtype: int64
        r\zRThis Series is a view of some other array, to sort in-place you must create a copycsDt|��}t|d|�}y|j�d�Stk
r>|jdd�SXdS)Nr�)r�r�)rPr��argsortrd)�arr)r�r�rgrh�_try_kind_sort�s
z*Series.sort_values.<locals>._try_kind_sort)ryrazLength of ascending (z) must be 1 for Seriesrzascending must be booleanNr�r6zinvalid na_position: )rV�sort_values)r�r�)r!r,Z
_is_cachedr�r�r��emptyrbZint32r2r~r�r-r'r/r�rVr9r�)rer[�	ascendingr\r�r�rdr�r�r�Zsorted_index�badZgoodryZ	argsorted�nr�rg)r�r�rhr�sJ*





zSeries.sort_values)r�r\r�r��sort_remainingrdr�c
Cs&t|d�}|j|�t|j|	|d�}
|dk	rB|
j|||d�\}}ntt|
t�rtddlm}
|
j	�}|
|j
�||d�}nBddlm}|r�|
js�|r�|
j
r�|r�dS|j�S||
|||d	�}t|�}|jj|�}|j	�}|jj|�}|j||d
�}|�rtjt|��|_|�r|j|�n|j|dd�SdS)
u�
        Sort Series by index labels.

        Returns a new Series sorted by label if `inplace` argument is
        ``False``, otherwise updates the original series and returns None.

        Parameters
        ----------
        axis : int, default 0
            Axis to direct sorting. This can only be 0 for Series.
        level : int, optional
            If not None, sort on values in specified index level(s).
        ascending : bool or list of bools, default True
            Sort ascending vs. descending. When the index is a MultiIndex the
            sort direction can be controlled for each level individually.
        inplace : bool, default False
            If True, perform operation in-place.
        kind : {'quicksort', 'mergesort', 'heapsort'}, default 'quicksort'
            Choice of sorting algorithm. See also :func:`numpy.sort` for more
            information.  'mergesort' is the only stable algorithm. For
            DataFrames, this option is only applied when sorting on a single
            column or label.
        na_position : {'first', 'last'}, default 'last'
            If 'first' puts NaNs at the beginning, 'last' puts NaNs at the end.
            Not implemented for MultiIndex.
        sort_remaining : bool, default True
            If True and sorting by level and index is multilevel, sort by other
            levels too (in order) after sorting by specified level.
        ignore_index : bool, default False
            If True, the resulting axis will be labeled 0, 1, …, n - 1.

            .. versionadded:: 1.0.0

        key : callable, optional
            If not None, apply the key function to the index values
            before sorting. This is similar to the `key` argument in the
            builtin :meth:`sorted` function, with the notable difference that
            this `key` function should be *vectorized*. It should expect an
            ``Index`` and return an ``Index`` of the same shape.

            .. versionadded:: 1.1.0

        Returns
        -------
        Series
            The original Series sorted by the labels.

        See Also
        --------
        DataFrame.sort_index: Sort DataFrame by the index.
        DataFrame.sort_values: Sort DataFrame by the value.
        Series.sort_values : Sort Series by the value.

        Examples
        --------
        >>> s = pd.Series(['a', 'b', 'c', 'd'], index=[3, 2, 1, 4])
        >>> s.sort_index()
        1    c
        2    b
        3    a
        4    d
        dtype: object

        Sort Descending

        >>> s.sort_index(ascending=False)
        4    d
        3    a
        2    b
        1    c
        dtype: object

        Sort Inplace

        >>> s.sort_index(inplace=True)
        >>> s
        1    c
        2    b
        3    a
        4    d
        dtype: object

        By default NaNs are put at the end, but use `na_position` to place
        them at the beginning

        >>> s = pd.Series(['a', 'b', 'c', 'd'], index=[3, 2, 1, np.nan])
        >>> s.sort_index(na_position='first')
        NaN     d
         1.0    c
         2.0    b
         3.0    a
        dtype: object

        Specify index level to sort

        >>> arrays = [np.array(['qux', 'qux', 'foo', 'foo',
        ...                     'baz', 'baz', 'bar', 'bar']),
        ...           np.array(['two', 'one', 'two', 'one',
        ...                     'two', 'one', 'two', 'one'])]
        >>> s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8], index=arrays)
        >>> s.sort_index(level=1)
        bar  one    8
        baz  one    6
        foo  one    4
        qux  one    2
        bar  two    7
        baz  two    5
        foo  two    3
        qux  two    1
        dtype: int64

        Does not sort by remaining levels when sorting by levels

        >>> s.sort_index(level=1, sort_remaining=False)
        qux  one    2
        foo  one    4
        baz  one    6
        bar  one    8
        qux  two    1
        foo  two    3
        baz  two    5
        bar  two    7
        dtype: int64

        Apply a key function before sorting

        >>> s = pd.Series([1, 2, 3, 4], index=['A', 'b', 'C', 'd'])
        >>> s.sort_index(key=lambda x : x.str.lower())
        A    1
        b    2
        C    3
        d    4
        dtype: int64
        r\)r0N)r�r�r)�lexsort_indexer)Zordersr�)�nargsort)r�r�r�)rV�
sort_index)r�)r!r,rPrVZ	sortlevelr|rI�pandas.core.sortingr�Z_sort_levels_monotonicZ_get_codes_for_sortingr�Zis_monotonic_increasingZis_monotonic_decreasingrur&r�r�r�r~r�rbr9r�)rer[rr�r\r�r�r�rdr�rVr�r�r�r�r�r�r�rgrgrhr��s@




zSeries.sort_indexcCs�|j}t|�}|j�r`td
|j|jdd�}|}tj|||d�||<|j||jd�j	|dd�S|jtj||d�|jdd�j	|dd�Sd	S)a�
        Return the integer indices that would sort the Series values.

        Override ndarray.argsort. Argsorts the value, omitting NA/null values,
        and places the result in the same locations as the non-NA values.

        Parameters
        ----------
        axis : {0 or "index"}
            Has no effect but is accepted for compatibility with numpy.
        kind : {'mergesort', 'quicksort', 'heapsort'}, default 'quicksort'
            Choice of sorting algorithm. See np.sort for more
            information. 'mergesort' is the only stable algorithm.
        order : None
            Has no effect but is accepted for compatibility with numpy.

        Returns
        -------
        Series
            Positions of values within the sort order with -1 indicating
            nan values.

        See Also
        --------
        numpy.ndarray.argsort : Returns the indices that would sort this array.
        rar-)rVrmry)r�)rVr�)r�)rVryNr�)
r�r2r�rUrVrmr�r�r�r�)rer[r�r�r�r�r�Znotmaskrgrgrhr��
s
zSeries.argsortr�cCstj|||d�j�S)a
        Return the largest `n` elements.

        Parameters
        ----------
        n : int, default 5
            Return this many descending sorted values.
        keep : {'first', 'last', 'all'}, default 'first'
            When there are duplicate values that cannot all fit in a
            Series of `n` elements:

            - ``first`` : return the first `n` occurrences in order
                of appearance.
            - ``last`` : return the last `n` occurrences in reverse
                order of appearance.
            - ``all`` : keep all occurrences. This can result in a Series of
                size larger than `n`.

        Returns
        -------
        Series
            The `n` largest values in the Series, sorted in decreasing order.

        See Also
        --------
        Series.nsmallest: Get the `n` smallest elements.
        Series.sort_values: Sort Series by values.
        Series.head: Return the first `n` rows.

        Notes
        -----
        Faster than ``.sort_values(ascending=False).head(n)`` for small `n`
        relative to the size of the ``Series`` object.

        Examples
        --------
        >>> countries_population = {"Italy": 59000000, "France": 65000000,
        ...                         "Malta": 434000, "Maldives": 434000,
        ...                         "Brunei": 434000, "Iceland": 337000,
        ...                         "Nauru": 11300, "Tuvalu": 11300,
        ...                         "Anguilla": 11300, "Montserrat": 5200}
        >>> s = pd.Series(countries_population)
        >>> s
        Italy       59000000
        France      65000000
        Malta         434000
        Maldives      434000
        Brunei        434000
        Iceland       337000
        Nauru          11300
        Tuvalu         11300
        Anguilla       11300
        Montserrat      5200
        dtype: int64

        The `n` largest elements where ``n=5`` by default.

        >>> s.nlargest()
        France      65000000
        Italy       59000000
        Malta         434000
        Maldives      434000
        Brunei        434000
        dtype: int64

        The `n` largest elements where ``n=3``. Default `keep` value is 'first'
        so Malta will be kept.

        >>> s.nlargest(3)
        France    65000000
        Italy     59000000
        Malta       434000
        dtype: int64

        The `n` largest elements where ``n=3`` and keeping the last duplicates.
        Brunei will be kept since it is the last with value 434000 based on
        the index order.

        >>> s.nlargest(3, keep='last')
        France      65000000
        Italy       59000000
        Brunei        434000
        dtype: int64

        The `n` largest elements where ``n=3`` with all duplicates kept. Note
        that the returned Series has five elements due to the three duplicates.

        >>> s.nlargest(3, keep='all')
        France      65000000
        Italy       59000000
        Malta         434000
        Maldives      434000
        Brunei        434000
        dtype: int64
        )r�r7)r6�
SelectNSeries�nlargest)rer�r7rgrgrhr��
s`zSeries.nlargestcCstj|||d�j�S)a�
        Return the smallest `n` elements.

        Parameters
        ----------
        n : int, default 5
            Return this many ascending sorted values.
        keep : {'first', 'last', 'all'}, default 'first'
            When there are duplicate values that cannot all fit in a
            Series of `n` elements:

            - ``first`` : return the first `n` occurrences in order
                of appearance.
            - ``last`` : return the last `n` occurrences in reverse
                order of appearance.
            - ``all`` : keep all occurrences. This can result in a Series of
                size larger than `n`.

        Returns
        -------
        Series
            The `n` smallest values in the Series, sorted in increasing order.

        See Also
        --------
        Series.nlargest: Get the `n` largest elements.
        Series.sort_values: Sort Series by values.
        Series.head: Return the first `n` rows.

        Notes
        -----
        Faster than ``.sort_values().head(n)`` for small `n` relative to
        the size of the ``Series`` object.

        Examples
        --------
        >>> countries_population = {"Italy": 59000000, "France": 65000000,
        ...                         "Brunei": 434000, "Malta": 434000,
        ...                         "Maldives": 434000, "Iceland": 337000,
        ...                         "Nauru": 11300, "Tuvalu": 11300,
        ...                         "Anguilla": 11300, "Montserrat": 5200}
        >>> s = pd.Series(countries_population)
        >>> s
        Italy       59000000
        France      65000000
        Brunei        434000
        Malta         434000
        Maldives      434000
        Iceland       337000
        Nauru          11300
        Tuvalu         11300
        Anguilla       11300
        Montserrat      5200
        dtype: int64

        The `n` smallest elements where ``n=5`` by default.

        >>> s.nsmallest()
        Montserrat    5200
        Nauru        11300
        Tuvalu       11300
        Anguilla     11300
        Iceland     337000
        dtype: int64

        The `n` smallest elements where ``n=3``. Default `keep` value is
        'first' so Nauru and Tuvalu will be kept.

        >>> s.nsmallest(3)
        Montserrat   5200
        Nauru       11300
        Tuvalu      11300
        dtype: int64

        The `n` smallest elements where ``n=3`` and keeping the last
        duplicates. Anguilla and Tuvalu will be kept since they are the last
        with value 11300 based on the index order.

        >>> s.nsmallest(3, keep='last')
        Montserrat   5200
        Anguilla    11300
        Tuvalu      11300
        dtype: int64

        The `n` smallest elements where ``n=3`` with all duplicates kept. Note
        that the returned Series has four elements due to the three duplicates.

        >>> s.nsmallest(3, keep='all')
        Montserrat   5200
        Nauru       11300
        Tuvalu      11300
        Anguilla    11300
        dtype: int64
        )r�r7)r6r��	nsmallest)rer�r7rgrgrhr�Cs_zSeries.nsmallestrscCs:t|jt�st�|jj||�}|j|j||d�j|dd�S)a�
        Swap levels i and j in a :class:`MultiIndex`.

        Default is to swap the two innermost levels of the index.

        Parameters
        ----------
        i, j : int, str
            Level of the indices to be swapped. Can pass level name as string.
        copy : bool, default True
            Whether to copy underlying data.

        Returns
        -------
        Series
            Series with levels swapped in MultiIndex.
        )rVru�	swaplevel)r�)r|rVrIr�r�r�r�r�)rer��jrur�rgrgrhr��szSeries.swaplevelcCs>t|jt�std��|j�}t|jt�s,t�|jj|�|_|S)a9
        Rearrange index levels using input order.

        May not drop or duplicate levels.

        Parameters
        ----------
        order : list of int representing new level order
            Reference level by number or key.

        Returns
        -------
        type of caller (new object)
        z/Can only reorder levels on a hierarchical axis.)r|rVrIrYrur��reorder_levels)rer�r�rgrgrhr��szSeries.reorder_levels)rdr�cCsht|�st|�r|j�Stjtj|j��\}}|rFtj	t|��}n|j
j|�}|j|||j
d�}|S)u�
        Transform each element of a list-like to a row.

        .. versionadded:: 0.25.0

        Parameters
        ----------
        ignore_index : bool, default False
            If True, the resulting index will be labeled 0, 1, …, n - 1.

            .. versionadded:: 1.1.0

        Returns
        -------
        Series
            Exploded lists to rows; index will be duplicated for these rows.

        See Also
        --------
        Series.str.split : Split string values on specified separator.
        Series.unstack : Unstack, a.k.a. pivot, Series with MultiIndex
            to produce DataFrame.
        DataFrame.melt : Unpivot a DataFrame from wide format to long format.
        DataFrame.explode : Explode a DataFrame from list-like
            columns to long format.

        Notes
        -----
        This routine will explode list-likes including lists, tuples,
        Series, and np.ndarray. The result dtype of the subset rows will
        be object. Scalars will be returned unchanged. Empty list-likes will
        result in a np.nan for that row.

        Examples
        --------
        >>> s = pd.Series([[1, 2, 3], 'foo', [], [3, 4]])
        >>> s
        0    [1, 2, 3]
        1          foo
        2           []
        3       [3, 4]
        dtype: object

        >>> s.explode()
        0      1
        0      2
        0      3
        1    foo
        2    NaN
        3      3
        3      4
        dtype: object
        )rVrm)rbr.rur�exploder�r�r�r~r�rVr�r�rm)rerdr��countsrVr�rgrgrhr��s6zSeries.explodecCsddlm}||||�S)a�
        Unstack, also known as pivot, Series with MultiIndex to produce DataFrame.

        Parameters
        ----------
        level : int, str, or list of these, default last level
            Level(s) to unstack, can pass level name.
        fill_value : scalar value, default None
            Value to use when replacing NaN values.

        Returns
        -------
        DataFrame
            Unstacked Series.

        Examples
        --------
        >>> s = pd.Series([1, 2, 3, 4],
        ...               index=pd.MultiIndex.from_product([['one', 'two'],
        ...                                                 ['a', 'b']]))
        >>> s
        one  a    1
             b    2
        two  a    3
             b    4
        dtype: int64

        >>> s.unstack(level=-1)
             a  b
        one  1  2
        two  3  4

        >>> s.unstack(level=0)
           one  two
        a    1    3
        b    2    4
        r)�unstack)Zpandas.core.reshape.reshaper�)rerrnr�rgrgrhr�s&zSeries.unstackcs*t�j||d�}|j||jd�j|dd�S)a�
        Map values of Series according to input correspondence.

        Used for substituting each value in a Series with another value,
        that may be derived from a function, a ``dict`` or
        a :class:`Series`.

        Parameters
        ----------
        arg : function, collections.abc.Mapping subclass or Series
            Mapping correspondence.
        na_action : {None, 'ignore'}, default None
            If 'ignore', propagate NaN values, without passing them to the
            mapping correspondence.

        Returns
        -------
        Series
            Same index as caller.

        See Also
        --------
        Series.apply : For applying more complex functions on a Series.
        DataFrame.apply : Apply a function row-/column-wise.
        DataFrame.applymap : Apply a function elementwise on a whole DataFrame.

        Notes
        -----
        When ``arg`` is a dictionary, values in Series that are not in the
        dictionary (as keys) are converted to ``NaN``. However, if the
        dictionary is a ``dict`` subclass that defines ``__missing__`` (i.e.
        provides a method for default values), then this default is used
        rather than ``NaN``.

        Examples
        --------
        >>> s = pd.Series(['cat', 'dog', np.nan, 'rabbit'])
        >>> s
        0      cat
        1      dog
        2      NaN
        3   rabbit
        dtype: object

        ``map`` accepts a ``dict`` or a ``Series``. Values that are not found
        in the ``dict`` are converted to ``NaN``, unless the dict has a default
        value (e.g. ``defaultdict``):

        >>> s.map({'cat': 'kitten', 'dog': 'puppy'})
        0   kitten
        1    puppy
        2      NaN
        3      NaN
        dtype: object

        It also accepts a function:

        >>> s.map('I am a {}'.format)
        0       I am a cat
        1       I am a dog
        2       I am a nan
        3    I am a rabbit
        dtype: object

        To avoid applying the function to missing values (and keep them as
        ``NaN``) ``na_action='ignore'`` can be used:

        >>> s.map('I am a {}'.format, na_action='ignore')
        0     I am a cat
        1     I am a dog
        2            NaN
        3  I am a rabbit
        dtype: object
        )�	na_action)rV�map)r�)r4Z_map_valuesr�rVr�)re�argr�r�)r5rgrhr�DsKz
Series.mapcCs|S)a
        Sub-classes to define. Return a sliced object.

        Parameters
        ----------
        key : string / list of selections
        ndim : 1,2
            Requested ndim of result.
        subset : object, default None
            Subset to act on.
        rg)rer�r�Zsubsetrgrgrh�_gotitem�szSeries._gotitemz�
    See Also
    --------
    Series.apply : Invoke function on a Series.
    Series.transform : Transform function producing a Series with like indexes.
    z�
    Examples
    --------
    >>> s = pd.Series([1, 2, 3, 4])
    >>> s
    0    1
    1    2
    2    3
    3    4
    dtype: int64

    >>> s.agg('min')
    1

    >>> s.agg(['min', 'max'])
    min   1
    max   4
    dtype: int64
    �	aggregater[z
.. versionadded:: 0.20.0
)rYr[Zsee_alsorZversionaddedc
Os�|j|�|dkrt|j��}|j|f|�|�\}}|dkr�|jdd�|jdd�y|j|f|�|�}Wn*tttfk
r�||f|�|�}YnX|S)NZ_axisZ_level)	r,r�r�Z
_aggregate�pop�applyr�rrd)rermr[r;r�r��howrgrgrhr��s


zSeries.aggregate)rYr[cs|j|�t�j|f|�|�S)N)r,r4�	transform)rermr[r;r�)r5rgrhr��s
zSeries.transformcsJt|�dkr(|j|j|jd�j|dd�St�ttf�rH|j�f����St�t	�rd|j
�f����S�sz�r�t�tj�r����fdd�}n�}tj
dd��Zt|tj�r�||�St|j�r�t|jd	�r�|jj|�}n|jt�j}tj|||d
�}WdQRXt|��r,t|dt��r,|jtj|�|jd�S|j||jd�j|dd�SdS)
a
        Invoke function on values of Series.

        Can be ufunc (a NumPy function that applies to the entire Series)
        or a Python function that only works on single values.

        Parameters
        ----------
        func : function
            Python function or NumPy ufunc to apply.
        convert_dtype : bool, default True
            Try to find better dtype for elementwise function results. If
            False, leave as dtype=object.
        args : tuple
            Positional arguments passed to func after the series value.
        **kwds
            Additional keyword arguments passed to func.

        Returns
        -------
        Series or DataFrame
            If func returns a Series object the result will be a DataFrame.

        See Also
        --------
        Series.map: For element-wise operations.
        Series.agg: Only perform aggregating type operations.
        Series.transform: Only perform transforming type operations.

        Examples
        --------
        Create a series with typical summer temperatures for each city.

        >>> s = pd.Series([20, 21, 12],
        ...               index=['London', 'New York', 'Helsinki'])
        >>> s
        London      20
        New York    21
        Helsinki    12
        dtype: int64

        Square the values by defining a function and passing it as an
        argument to ``apply()``.

        >>> def square(x):
        ...     return x ** 2
        >>> s.apply(square)
        London      400
        New York    441
        Helsinki    144
        dtype: int64

        Square the values by passing an anonymous function as an
        argument to ``apply()``.

        >>> s.apply(lambda x: x ** 2)
        London      400
        New York    441
        Helsinki    144
        dtype: int64

        Define a custom function that needs additional positional
        arguments and pass these additional arguments using the
        ``args`` keyword.

        >>> def subtract_custom_value(x, custom_value):
        ...     return x - custom_value

        >>> s.apply(subtract_custom_value, args=(5,))
        London      15
        New York    16
        Helsinki     7
        dtype: int64

        Define a custom function that takes keyword arguments
        and pass these arguments to ``apply``.

        >>> def add_custom_values(x, **kwargs):
        ...     for month in kwargs:
        ...         x += kwargs[month]
        ...     return x

        >>> s.apply(add_custom_values, june=30, july=20, august=25)
        London      95
        New York    96
        Helsinki    87
        dtype: int64

        Use a function from the Numpy library.

        >>> s.apply(np.log)
        London      2.995732
        New York    3.044522
        Helsinki    2.484907
        dtype: float64
        r)ryrVr�)r�cs�|f����S)Nrg)r�)r;rm�kwdsrgrhreszSeries.apply.<locals>.frx)rir�)�convertN)rV)rbr�ryrVr�r|r�r�r�rpZ_try_aggregate_string_functionr�r�rjr*r�r�r�r�r�rZ	map_inferrUr��pdr�)rermZ
convert_dtyper;r�rZmappedr�rg)r;rmr�rhr��s*a

zSeries.applyc	Ksx|j}|dk	r|j|�t|t�r8|j|fd|i|��S|rLtd|�d���tjdd��||fd|i|��SQRXdS)z�
        Perform a reduction operation.

        If we have an ndarray as a value, then simply perform the operation,
        otherwise delegate to the object.
        Nr�zSeries.z! does not implement numeric_only.rx)ri)r�r,r|r<�_reducer�r�rj)	re�oprmr[r�rCZfilter_typer�Zdelegatergrgrhr��s	

zSeries._reducecCs:|dkr|r|j�S|Stj|j|ddd�}|j||d�S)NT)Z
allow_fillrn)rV)rur6Ztake_1dr�r�)rer�r�rur�rgrgrh�_reindex_indexer�szSeries._reindex_indexercCsdS)zc
        Check if we do need a multi reindex; this is for compat with
        higher dims.
        Frg)rerXr�rrgrgrh�_needs_reindex_multi�szSeries._needs_reindex_multirZ)rYrZr�cs t�j|||||||||	|
d�
S)N)	rGr[rrurnr��limit�	fill_axis�broadcast_axis)r4rK)rerMrGr[rrurnr�r�r�r�)r5rgrhrK�szSeries.alignrx)r[rur\rrzcs8t|�st|�r&t�j|||||d�S|j||d�SdS)a�
        Alter Series index labels or name.

        Function / dict values must be unique (1-to-1). Labels not contained in
        a dict / Series will be left as-is. Extra labels listed don't throw an
        error.

        Alternatively, change ``Series.name`` with a scalar value.

        See the :ref:`user guide <basics.rename>` for more.

        Parameters
        ----------
        axis : {0 or "index"}
            Unused. Accepted for compatibility with DataFrame method only.
        index : scalar, hashable sequence, dict-like or function, optional
            Functions or dict-like are transformations to apply to
            the index.
            Scalar or hashable sequence-like will alter the ``Series.name``
            attribute.

        **kwargs
            Additional keyword arguments passed to the function. Only the
            "inplace" keyword is used.

        Returns
        -------
        Series
            Series with index labels or name altered.

        See Also
        --------
        DataFrame.rename : Corresponding DataFrame method.
        Series.rename_axis : Set the name of the axis.

        Examples
        --------
        >>> s = pd.Series([1, 2, 3])
        >>> s
        0    1
        1    2
        2    3
        dtype: int64
        >>> s.rename("my_name")  # scalar, changes Series.name
        0    1
        1    2
        2    3
        Name: my_name, dtype: int64
        >>> s.rename(lambda x: x ** 2)  # function, changes labels
        0    1
        1    2
        4    3
        dtype: int64
        >>> s.rename({1: 3, 2: 5})  # mapping, changes labels
        0    1
        3    2
        5    3
        dtype: int64
        )rur\rrz)r\N)rLr)r4�renamer")rerVr[rur\rrz)r5rgrhr��sEz
Series.renamea
        Examples
        --------
        >>> s = pd.Series([1, 2, 3])
        >>> s
        0    1
        1    2
        2    3
        dtype: int64

        >>> s.set_axis(['a', 'b', 'c'], axis=0)
        a    1
        b    2
        c    3
        dtype: int64
    )Zextended_summary_subZaxis_description_subZsee_also_sub)r[r\cst�j|||d�S)N)r[r\)r4r�)rer�r[r\)r5rgrhr�szSeries.set_axisrXr_r`)rYrXr_r`cst�jfd|i|��S)NrV)r4r�)rerVr�)r5rgrhr�4szSeries.reindex�raisec	st�j|||||||d�S)aE
        Return Series with specified index labels removed.

        Remove elements of a Series based on specifying the index labels.
        When using a multi-index, labels on different levels can be removed
        by specifying the level.

        Parameters
        ----------
        labels : single label or list-like
            Index labels to drop.
        axis : 0, default 0
            Redundant for application on Series.
        index : single label or list-like
            Redundant for application on Series, but 'index' can be used instead
            of 'labels'.
        columns : single label or list-like
            No change is made to the Series; use 'index' or 'labels' instead.
        level : int or level name, optional
            For MultiIndex, level for which the labels will be removed.
        inplace : bool, default False
            If True, do operation inplace and return None.
        errors : {'ignore', 'raise'}, default 'raise'
            If 'ignore', suppress error and only existing labels are dropped.

        Returns
        -------
        Series
            Series with specified index labels removed.

        Raises
        ------
        KeyError
            If none of the labels are found in the index.

        See Also
        --------
        Series.reindex : Return only specified index labels of Series.
        Series.dropna : Return series without null values.
        Series.drop_duplicates : Return Series with duplicate values removed.
        DataFrame.drop : Drop specified labels from rows or columns.

        Examples
        --------
        >>> s = pd.Series(data=np.arange(3), index=['A', 'B', 'C'])
        >>> s
        A  0
        B  1
        C  2
        dtype: int64

        Drop labels B en C

        >>> s.drop(labels=['B', 'C'])
        A  0
        dtype: int64

        Drop 2nd level label in MultiIndex Series

        >>> midx = pd.MultiIndex(levels=[['lama', 'cow', 'falcon'],
        ...                              ['speed', 'weight', 'length']],
        ...                      codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2],
        ...                             [0, 1, 2, 0, 1, 2, 0, 1, 2]])
        >>> s = pd.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1, 0.3],
        ...               index=midx)
        >>> s
        lama    speed      45.0
                weight    200.0
                length      1.2
        cow     speed      30.0
                weight    250.0
                length      1.5
        falcon  speed     320.0
                weight      1.0
                length      0.3
        dtype: float64

        >>> s.drop(labels='weight', level=1)
        lama    speed      45.0
                length      1.2
        cow     speed      30.0
                length      1.5
        falcon  speed     320.0
                length      0.3
        dtype: float64
        )r�r[rVrZrr\rz)r4r)rer�r[rVrZrr\rz)r5rgrhr>s`zSeries.dropcst�j||||||d�S)N)r�r�r[r\r��downcast)r4�fillna)rer�r�r[r\r�r�)r5rgrhr��s
z
Series.fillna)r�r�cst�j|d�S)a�
        Return item and drops from series. Raise KeyError if not found.

        Parameters
        ----------
        item : label
            Index of the element that needs to be removed.

        Returns
        -------
        Value that is popped from series.

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

        >>> ser.pop(0)
        1

        >>> ser
        1    2
        2    3
        dtype: int64
        )r�)r4r�)rer�)r5rgrhr��sz
Series.pop�padcst�j||||||d�S)N)�
to_replacer�r\r��regexr�)r4�replace)rer�r�r\r�r�r�)r5rgrhr��s
zSeries.replacecst�j||||d�S)N)rR�freqr[rn)r4rT)rerRr�r[rn)r5rgrhrT�szSeries.shiftcs(t�j|d�}|r$||jj|d�7}|S)aP
        Return the memory usage of the Series.

        The memory usage can optionally include the contribution of
        the index and of elements of `object` dtype.

        Parameters
        ----------
        index : bool, default True
            Specifies whether to include the memory usage of the Series index.
        deep : bool, default False
            If True, introspect the data deeply by interrogating
            `object` dtypes for system-level memory consumption, and include
            it in the returned value.

        Returns
        -------
        int
            Bytes of memory consumed.

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

        Examples
        --------
        >>> s = pd.Series(range(3))
        >>> s.memory_usage()
        152

        Not including the index gives the size of the rest of the data, which
        is necessarily smaller:

        >>> s.memory_usage(index=False)
        24

        The memory footprint of `object` values is ignored by default:

        >>> s = pd.Series(["a", "b"])
        >>> s.values
        array(['a', 'b'], dtype=object)
        >>> s.memory_usage()
        144
        >>> s.memory_usage(deep=True)
        260
        )�deep)r4�memory_usagerV)rerVr��v)r5rgrhr��s1zSeries.memory_usagecCs&tj||�}|j||jd�j|dd�S)a}
        Whether elements in Series are contained in `values`.

        Return a boolean Series showing whether each element in the Series
        matches an element in the passed sequence of `values` exactly.

        Parameters
        ----------
        values : set or list-like
            The sequence of values to test. Passing in a single string will
            raise a ``TypeError``. Instead, turn a single string into a
            list of one element.

        Returns
        -------
        Series
            Series of booleans indicating if each element is in values.

        Raises
        ------
        TypeError
          * If `values` is a string

        See Also
        --------
        DataFrame.isin : Equivalent method on DataFrame.

        Examples
        --------
        >>> s = pd.Series(['lama', 'cow', 'lama', 'beetle', 'lama',
        ...                'hippo'], name='animal')
        >>> s.isin(['cow', 'lama'])
        0     True
        1     True
        2     True
        3    False
        4     True
        5    False
        Name: animal, dtype: bool

        Passing a single string as ``s.isin('lama')`` will raise an error. Use
        a list of one element instead:

        >>> s.isin(['lama'])
        0     True
        1    False
        2     True
        3    False
        4     True
        5    False
        Name: animal, dtype: bool
        )rV�isin)r�)r6r�r�rVr�)rer�r�rgrgrhr�%s5zSeries.isincCs.|r||k}||k}n||k}||k}||@S)a�
        Return boolean Series equivalent to left <= series <= right.

        This function returns a boolean vector containing `True` wherever the
        corresponding Series element is between the boundary values `left` and
        `right`. NA values are treated as `False`.

        Parameters
        ----------
        left : scalar or list-like
            Left boundary.
        right : scalar or list-like
            Right boundary.
        inclusive : bool, default True
            Include boundaries.

        Returns
        -------
        Series
            Series representing whether each element is between left and
            right (inclusive).

        See Also
        --------
        Series.gt : Greater than of series and other.
        Series.lt : Less than of series and other.

        Notes
        -----
        This function is equivalent to ``(left <= ser) & (ser <= right)``

        Examples
        --------
        >>> s = pd.Series([2, 0, 4, 8, np.nan])

        Boundary values are included by default:

        >>> s.between(1, 4)
        0     True
        1    False
        2     True
        3    False
        4    False
        dtype: bool

        With `inclusive` set to ``False`` boundary values are excluded:

        >>> s.between(1, 4, inclusive=False)
        0     True
        1    False
        2    False
        3    False
        4    False
        dtype: bool

        `left` and `right` can be any scalar value:

        >>> s = pd.Series(['Alice', 'Bob', 'Carol', 'Eve'])
        >>> s.between('Anna', 'Daniel')
        0    False
        1     True
        2     True
        3    False
        dtype: bool
        rg)rer\r]Z	inclusiveZlmaskZrmaskrgrgrh�between_sB
zSeries.between)�
infer_objects�convert_string�convert_integer�convert_booleanr�cCsv|}|r |j�}t|�r |j�}|s,|s,|rjt|j|||�}y|j|�}Wqrtk
rf|j�}YqrXn|j�}|S)N)r�r.rur#r�r�rd)rer�r�r�r�Zinput_seriesZinferred_dtyper�rgrgrh�_convert_dtypes�szSeries._convert_dtypescs
t�j�S)N)r4r2)re)r5rgrhr2�szSeries.isnacs
t�j�S)N)r4�isnull)re)r5rgrhr��sz
Series.isnullcs
t�j�S)N)r4r4)re)r5rgrhr4�szSeries.notnacs
t�j�S)N)r4�notnull)re)r5rgrhr��szSeries.notnullcCsNt|d�}|j|pd�|jr<t|�}|r6|j|�qJ|Sn|rBn|j�SdS)a
        Return a new Series with missing values removed.

        See the :ref:`User Guide <missing_data>` for more on which values are
        considered missing, and how to work with missing data.

        Parameters
        ----------
        axis : {0 or 'index'}, default 0
            There is only one axis to drop values from.
        inplace : bool, default False
            If True, do operation inplace and return None.
        how : str, optional
            Not in use. Kept for compatibility.

        Returns
        -------
        Series
            Series with NA entries dropped from it.

        See Also
        --------
        Series.isna: Indicate missing values.
        Series.notna : Indicate existing (non-missing) values.
        Series.fillna : Replace missing values.
        DataFrame.dropna : Drop rows or columns which contain NA values.
        Index.dropna : Drop missing indices.

        Examples
        --------
        >>> ser = pd.Series([1., 2., np.nan])
        >>> ser
        0    1.0
        1    2.0
        2    NaN
        dtype: float64

        Drop NA values from a Series.

        >>> ser.dropna()
        0    1.0
        1    2.0
        dtype: float64

        Keep the Series with valid entries in the same variable.

        >>> ser.dropna(inplace=True)
        >>> ser
        0    1.0
        1    2.0
        dtype: float64

        Empty strings are not considered NA values. ``None`` is considered an
        NA value.

        >>> ser = pd.Series([np.NaN, 2, pd.NaT, '', None, 'I stay'])
        >>> ser
        0       NaN
        1         2
        2       NaT
        3
        4      None
        5    I stay
        dtype: object
        >>> ser.dropna()
        1         2
        3
        5    I stay
        dtype: object
        r\rN)r!r,r�r5r9ru)rer[r\r�r�rgrgrhr)�sG
z
Series.dropna�startcCs\|j}|r|j�}t|jt�s4tdt|j�j����|jj||d�}|j	||d�j
|dd�S)a�
        Cast to DatetimeIndex of Timestamps, at *beginning* of period.

        Parameters
        ----------
        freq : str, default frequency of PeriodIndex
            Desired frequency.
        how : {'s', 'e', 'start', 'end'}
            Convention for converting period to timestamp; start of period
            vs. end.
        copy : bool, default True
            Whether or not to return a copy.

        Returns
        -------
        Series with DatetimeIndex
        zunsupported Type )r�r�)rV�to_timestamp)r�)r�rur|rVrLrdrrkr�r�r�)rer�r�rur�r�rgrgrhr�1szSeries.to_timestampcCsZ|j}|r|j�}t|jt�s4tdt|j�j����|jj|d�}|j	||d�j
|dd�S)ay
        Convert Series from DatetimeIndex to PeriodIndex.

        Parameters
        ----------
        freq : str, default None
            Frequency associated with the PeriodIndex.
        copy : bool, default True
            Whether or not to return a copy.

        Returns
        -------
        Series
            Series with index converted to PeriodIndex.
        zunsupported Type )r�)rV�	to_period)r�)r�rur|rVrKrdrrkr�r�r�)rer�rur�r�rgrgrhr�NszSeries.to_periodz&The index (axis labels) of the Series.)r[r rH�plot)NNNNFF)NN)F)r�)N)N)rN)r)r)r)F)F)N)NFNF)
NrNTTFFFNN)NNT)N)F)N)T)r6F)r6)rT)rT)r)r?r@)rEN)Nra)ra)ra)r\N)FF)NN)rUrU)raFF)N)rTFr�r�FN)	rNTFr�r�TFN)rr�N)r�r6)r�r6���r�)r�r�T)Fr�)r�N)N)N)Nr)r)rTNN)	r�NNTNNNrN)N)rF)N)NrNNNFr�)NNNFNN)NNFNFr�)raNrN)TF)T)TTTT)rFN)Nr�T)NT)�rk�
__module__�__qualname__�__doc__Z_typrr�Z	_metadatar
rpr8rCZ_internal_names_setZ
_accessorsr7�
IndexOpsMixinZ
_deprecationsr��propertyZhasnansrmrOr�rr�divZrdivr}r�r
r�r�r�r��intr�r�rryr�rm�setterr�r�rr�r<r�r�r�rHr�r�r�r�r�rl�float�	__float__Z__long__�__int__rXr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rrrr �_shared_doc_kwargsrrrrr	rr�r r�r�r!rr"Z_shared_docsrr#r.rr]r8r^r<r=r>rDrOrQrSrUrVr^r_rbrhrprrrlrrrqr{r~r�rr�rr�r�r�r�r�r�r�r�r�r�Z_agg_see_also_docZ_agg_examples_docr�Zaggr�r�r�r�r�rKr�rr�r�rr�r�r�rTr�r�r�r�r2r�r4r�r)r�r�Z_AXIS_ORDERSZ_AXIS_REVERSEDrbZ	_AXIS_LENZ_info_axis_numberZ_info_axis_namerZAxisPropertyrVr;rQrFrnr=ro�pandasZplottingZPlotAccessorr�r>rqZhist_series�hist�
__classcell__rgrg)r5rhrU�s@
%.1*"HJ5	((	';
 B8! P%-@SNFG(;>(*)-NT%#<b(Rh@*baD-P

D
a
6:P[



)�r��ior�shutilr�textwraprZtypingrrrrr	r
rrr
rr�Znumpyr�Zpandas._configrZpandas._libsrrrrZpandas._libs.librZpandas._typingrrrrrrrZpandas.compat.numpyrr�Z
pandas.errorsrZpandas.util._decoratorsrrr Zpandas.util._validatorsr!r"Zpandas.core.dtypes.castr#r$r%Zpandas.core.dtypes.commonr&r'r(r)r*r+r,r-r.r/Zpandas.core.dtypes.genericr0Zpandas.core.dtypes.inferencer1Zpandas.core.dtypes.missingr2r3r4r5r�r�Zpandas.corer6r7r8r9r:Zpandas.core.accessorr;Zpandas.core.arraysr<Zpandas.core.arrays.categoricalr=Zpandas.core.arrays.sparser>Zpandas.core.common�corer[r�Zpandas.core.constructionr?r@rArBZpandas.core.genericrCZpandas.core.indexersrDrEZpandas.core.indexes.accessorsrFZpandas.core.indexes.apirGrHrIrJZpandas.core.indexes.base�indexesr~Zpandas.core.indexes.datetimesrKZpandas.core.indexes.periodrLZpandas.core.indexes.timedeltasrMZpandas.core.indexingrNZpandas.core.internalsrOr�rPZpandas.core.stringsrQZpandas.core.tools.datetimesrRZpandas.io.formats.format�formats�formatrZpandas.plottingr�rSr+rT�__all__r�r�rlr�rUZ_add_numeric_operationsZ#_add_series_or_dataframe_operationsZadd_flex_arithmetic_methodsZadd_special_arithmetic_methodsrgrgrgrh�<module>s�0$	0