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

���h#��@sVddlZddlmZddlZddlZddlZddlZddlZddlZddl	m
Z
ddlmZm
Z
mZmZmZmZmZmZmZmZmZmZmZmZddlZddlZddlZddlmZddl m!Z!ddl"m#Z#m$Z$m%Z%ddl&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0dd	l1m2Z2dd
l3m4Z4ddl5m6Z7ddl8m9Z9m:Z:dd
l;m<Z<m=Z=m>Z>m?Z?ddl@mAZAmBZBmCZCddlDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVddlWmXZXmYZYddlZm[Z[ddl\m]Z]m^Z^ddl_Z`ddlambZbmcZcddldjejfZgddlhmiZimjZjddlkjejlZmddlnmoZoddlpmqZqmrZrmsZsmtZtddlumvZvddlwmxZxmyZyddlzjej{Z{ddl|m}Z}ddl~mZddl�m�Z�ddl�m�Z�ddl�m�Z�ddl�m�Z�m�Z�ddl�m�Z�e�r�dd l�m�Z�dd!l�m�Z�e�d"d#d$d%d&d'�Z�d(d)�Z�e�Z�Gd*d+�d+eieje{j��Z�d,d-�Z�d.Z�d/Z�d0Z�d1Z�d2Z�d3Z�d4Z�d5Z�d6Z�d7Z�d8Z�d9Z�d:Z�d;Z�d<e�d=<e�d=j�d>d?d@dAdBdC�Z�e�dD7Z�e�d=j�dEdFdBdGdBdC�Z�e�d=j�dHdIddJddC�Z�dKZ�dLZ�dMZ�d]e�e�e�e�e�ee�e�edO�	dPdQ�Z�d^e�e�e�e�e�ee�e�edO�	dRdS�Z�e�e�e�e�e�eedT�dUdV�Z�e�e�e�e�e�ee�e�edW�	dXdY�Z�e�e�e�e�e�ee�e�e�edZ�
d[d\�Z�dS)_�N)�	timedelta)�dedent)�
TYPE_CHECKING�Any�Callable�Dict�	FrozenSet�Hashable�List�Mapping�Optional�Sequence�Set�Tuple�Type�Union)�config)�lib)�Tick�	Timestamp�	to_offset)
�Axis�FilePathOrBuffer�
FrameOrSeries�JSONSerializable�Label�Level�Renamer�TimedeltaConvertibleTypes�TimestampConvertibleTypes�ValueKeyFunc)�set_function_name)�import_optional_dependency)�function)�AbstractMethodError�InvalidIndexError)�Appender�Substitution�doc�rewrite_axis_style_signature)�validate_bool_kwarg�validate_fillna_kwargs�validate_percentile)�ensure_int64�
ensure_object�
ensure_str�is_bool�
is_bool_dtype�is_datetime64_any_dtype�is_datetime64tz_dtype�is_dict_like�is_extension_array_dtype�is_float�is_list_like�	is_number�is_numeric_dtype�is_object_dtype�is_re_compilable�	is_scalar�is_timedelta64_dtype�pandas_dtype)�ABCDataFrame�	ABCSeries)�is_hashable)�isna�notna)�missing�nanops)�PandasObject�SelectionMixin)�!create_series_with_explicit_dtype)�Index�
MultiIndex�
RangeIndex�ensure_index)�
DatetimeIndex)�Period�PeriodIndex)�BlockManager)�find_valid_index)�_align_method_FRAME)�_shared_docs)�format)�DataFrameFormatter�format_percentiles)�pprint_thing)�	Resampler)�Serieszkeywords for axeszSeries/DataFramezint or labels for objectz)axes to permute (int or label for object)zM
        by : str or list of str
            Name or list of names to sort by)�axes�klassZaxes_single_argZargs_transposeZoptional_byc
Cs�|jdkr*td|�d|�dt|�j����|j}|r8|n|j�}tj|�}tj|j	|�}||j	||d�}	|	j|krz|rzdSt
j|	|j|jd�j
|�}|r�|j|�dS|S)z�
    Replaces values in a Series using the fill method specified when no
    replacement value is given in the replace method
    �zcannot replace z
 with method z on a )�limit�maskN)�index�dtype)�ndim�	TypeError�type�__name__r`�copyrDZ
get_fill_funcZmask_missing�values�pdrYr_�__finalize__�_update_inplace)
�self�
to_replace�method�inplacer]Z
orig_dtype�resultZfill_fr^rf�ro�5/tmp/pip-build-5_djhm0z/pandas/pandas/core/generic.py�_single_replace{s


rqcseZdZUdZdddddddd	d
ddd
dg
Zeeee�Ze	ee�Z
e	e
eddg�Ze
egZeedZeeeeefe�d�eeeeeeefd�dd�Ze�d�eed�dd��Zeeeeefd�dd��Zejeeeefdd�dd��Zedd��Z ee!e"e!d �d!d"��Z#ed#d$��Z$ed%d&��Z%ed'd(��Z&d)Z'd*Z(dZ)ee*d)d)d)d+�Z+ee,e-f+e.e-/e0e-1eeee-fd�d,d-��Z2eee-efd�d.d/��Z3�d�d0d1�Z4e�d�ed2�d3d4��Z5ee,e-d5�d6d7��Z6ee,ed5�d8d9��Z7e,e8d5�d:d;�Z9ee,e-d5�d<d=��Z:eeee;fd5�d>d?�Z<eee;fd�d@dA�Z=eee;fd�dBdC�Z>ee8d�dDdE��Z?ee8d�dFdG��Z@eeAe-dHfd�dIdJ��ZBeee8d�dKdL��ZCee-d�dMdN��ZDee-d�dOdP��ZEee!e!d �dQdR��ZFee!e!d �dSdT��ZG�d�e,edU�dVdW�ZHe-e8ddX�dYdZ�ZI�d�e!e!d �d\d]�ZJ�d�e!e!d �d^d_�ZKeLeMd`efda�dbdc�ZN�d�ddde�ZO�d�dddd[dddfdg�e!eePeePeePee,eeeeQeee!dh�
didj�ZReSdk�d��d�g�eTjUfdndo��ZV�d�dpdq�ZWed�drds�ZXdtdu�ZYdvdw�ZZdxdy�Z[dzd{�Z\d|d}�Z]e]Z^d~d�Ze!e!d �d�d��Z_�d�e!e-e!d��d�d��Z`�d�d�d��Za�d�ebd�d�d��Zc�d�ee-ebd��d�d��Zd�d�e-dd5�d�d��Ze�dee-efjgd��d�d��Zh�de-d��d�d��Zid�d��Zjd�d��Zkd�d��Zld�d��Zmenem�d�d���Zoe-d�d�d��Zpebd�d�d��Zqeebd�d�d���Zrd�Zs�defjgd�d�d��Zt�dd�d��Zueeefd�d�d��Zvd�d��Zwed�d�d��Zxd�d��Zyd�d��Zzend�d���ddd�d�d���Z{�dee|eeeee-ebeee}ege~febeeebee-eed��d�d��Z�deeee-eeebeeebeeMe-eee-ffeebeeMebeefeeddœ
d�dĄZ��deeebddƜd�dȄZ�d�e�j�feee-ddɜd�d˄Z��debeedd̜d�d΄Z�d�dЄZ�e�e�j�dэ�d	d�dՄ�Z��d
ee|eeeeee�eLeMebeefebeeMebee�eLfeeeeeMeeeeffee-eeeee-eeebeeeeeeedٜd�dۄZ�dd�d�d݄Z�dd�d�d߄Z�dd�d�d�Z�eebd�d�d��Z�d�d�Z��debebdd�d�d�Z�dd�d�d�Z��de!eebe!d�d�d�Z��d
e!e!d �d�d�Z��debd�d�d�Z�d�d�Z�d�d��Z��de!e�e!d��d�d��Z�e-dd��d�d��Z�dd�d�d��Z��debdd�d��d�Z�ebd��d�d�Z��d�d�d�Z�dd��d�d�Z��d�d	�d
�Z�eebd��d�d��Z��de!eeebe!�d
��d�d�Z��debe�d��d�d�Z��de!ee!�d��d�d�Z��debd�d��d�d�Z�e!ee!�d��d�d�Z�e!ee!�d��d�d�Z��debeeebe��d"��d#�d$�Z�ene��d%e��d&d�d��d'�e!e!d ��d(�d)��Z�e!e!d ��d*�d+�Z�ebd��d,�d-�Z��d.�d/�Z��de!ebebe!�d0��d1�d2�Z��de!eeeee!�d3��d4�d5�Z��de!e-e!�d7��d8�d9�Z��de!e-e!�d7��d:�d;�Z��de!e!d ��d<�d=�Z�ene��d%d���d>�d?��Z�e��d@�e��dA<�de!eee!�dB��dC�dD�Z�e�dE��dF�dG�Z�ed�dH��dI�dJ�Z��f�dK�dL�Z��dM�dN�Z�dd��dO�dP�Z��deb�dQ��dR�dS�Z�eebd��dT�dU��Z�ebd��dV�dW�Z��dX�dY�Z��dZ�d[�Z�eefjgd��d\�d]��Z�eefjgd��d^�d_��Z�e�d`�da��ZŐdeb�db��dc�dd�ZƐd e!ebee!�de��df�dg�Zǐd!e!ebe!�dh��di�dj�ZȐd"e!ebe!�dh��dk�dl�Zɐd#e!e!d ��dm�dn�Zʐd$e!ebebebebe!�do��dp�dq�Z�e!e!d ��dr�ds�Z̐d%e!ebebebebe!�dt��du�dv�Z�enfe���d&e!ebee!�dw��dx�dy��Zΐd'e!ebee!�dw��dz�d{�Z�e�ZАd(e!ebee!�dw��d|�d}�Z�e�Z�ene��d%d���d)�d�d���ZӐd*e!ee,ee-ebeeeeeeee!�d��	�d��d��ZԐd+�d��d��Z�ene��d%d��e!e!d ��d��d���Z�ene�e��d%d��e!e!d ��d��d���Z�ene��d%d��e!e!d ��d��d���Z�ene�e��d%d��e!e!d ��d��d���Zِd,eb�dQ��d��d��Zڐd��d��Zېd-e!ebe!�dw��d��d��Zܐd�e��d�<�d.e!eeebe!�d���d��d��Zݐd/e!ebe!�d���d��d��Zސd0e!ebebe!�d���d��d��Zߐd1eeeeeeeee-eMee�fee��d��d���d��d��Z�e!e!d ��d��d��Z�e!e!d ��d��d��Z�d2e!eeebeebebe!�d���d��d��Z�d�e��d�<e�e��d�e���d3e,ebeb�d���d��d���Z�enfe���d4�d��d���Z�d5eb�db��d��d��Z�d6eb�db��d��d��Z�efj�ddd�ddf�d��d��Z�ene��d%�d��d��d��d��defj�ddd�ddf�dÐdĄ�Z�ene�e��d%�d��d��d��d��defj�ddd�ddf�dŐdƄ�Z�ene��d%d���d7e!e!d ��dǐdȄ�Z�d8e!e-e!�dɜ�dʐd˄Z�d9e!e-e,e!�d̜�d͐d΄Z�d:e!ebe!�dϜ�dАdфZ�d;e!ebe!�dϜ�dҐdӄZ�d<e!ebee!�dԜ�dՐdքZ�e!e!d ��dאd؄Z��d=e!e!d ��dِdڄZ��d>e!e!d ��dېd܄Z��d?�dݐdބZ�e�dߐd��Z�e�d�d��Z�ene��d%d��d��d�d��Z�e�d��d�d�Z�en�d�e��d%�d��d�d��Z�ene��d!e��d%�d��d�d��Z��Z�S(@�NDFramez�
    N-dimensional analogue of DataFrame. Store multi-dimensional in a
    size-mutable, labeled data structure

    Parameters
    ----------
    data : BlockManager
    axes : list
    copy : bool, default False
    �_mgr�_cacher�_item_cache�_cache�_is_copyZ_subtyp�_name�_indexZ
_default_kindZ_default_fill_value�	_metadataZ__array_struct__Z__array_interface__Z
get_values�tshiftNF)�datare�attrscCsRtj|dd�tj|d|�tj|di�|dkr8i}nt|�}tj|d|�dS)Nrwrsru�_attrs)�object�__setattr__�dict)rjr|rer}rororp�__init__�szNDFrame.__init__)re�returncCs�x>|j�D]2\}}|dk	r
t|�}|j|�}|j||dd�}q
W|rL|j�}|dk	r�t|j�dkst|jdjj|kr�|j	|d�}|S)z" passed a manager and a axes dict NF)�axisrer\r)r`)
�itemsrL�_get_block_manager_axisZreindex_axisre�len�blocksrfr`�astype)�clsZmgrrZr`re�aZaxeZbm_axisrororp�	_init_mgr�s
 zNDFrame._init_mgr)r�cCs|jdkri|_|jS)z�
        Dictionary of global attributes on this object.

        .. warning::

           attrs is experimental and may change without warning.
        N)r~)rjrororpr}�s	
z
NDFrame.attrs)�valuer�cCst|�|_dS)N)r�r~)rjr�rororpr}�scCs0|dk	r,t|�}|jdkr,td|j�d���|S)z validate the passed dtype N�Vz+compound dtypes are not implemented in the z constructor)r>�kind�NotImplementedErrorrd)r�r`rororp�_validate_dtype�s
zNDFrame._validate_dtype)rjr�cCst|��dS)zb
        Used when a manipulation result has the same dimensions as the
        original.
        N)r$)rjrororp�_constructorszNDFrame._constructorcCst|��dS)z�
        Used when a manipulation result has one lower dimension(s) as the
        original, such as DataFrame single columns slicing.
        N)r$)rjrororp�_constructor_slicedszNDFrame._constructor_slicedcCst�dS)z}
        Used when a manipulation result has one higher dimension as the
        original, such as Series.to_frame()
        N)r�)rjrororp�_constructor_expanddimszNDFrame._constructor_expanddimcCs|jS)N)rs)rjrororp�_data&sz
NDFrame._datarr_)rr_ZrowscCstjdtdd�ddiS)z.. deprecated:: 1.1.0z"_AXIS_NUMBERS has been deprecated.�)�
stacklevelr_r)�warnings�warn�
FutureWarning)rjrororp�
_AXIS_NUMBERS8szNDFrame._AXIS_NUMBERScCstjdtdd�ddiS)z.. deprecated:: 1.1.0z _AXIS_NAMES has been deprecated.r�)r�rr_)r�r�r�)rjrororp�_AXIS_NAMES@szNDFrame._AXIS_NAMEScs&�fdd�|p�jD�}|j|�|S)z%Return an axes dictionary for myself.csi|]}�j|�|�qSro)�	_get_axis)�.0r�)rjrorp�
<dictcomp>Jsz0NDFrame._construct_axes_dict.<locals>.<dictcomp>)�_AXIS_ORDERS�update)rjrZ�kwargs�dro)rjrp�_construct_axes_dictHs
zNDFrame._construct_axes_dict)�require_allcs�t|�}xZ|jD]P}|�kry|jd��|<Wqtk
r^}z|rNtd�|�WYdd}~XqXqW��fdd�|jD�}|�fS)a~
        Construct and returns axes if supplied in args/kwargs.

        If require_all, raise if all axis arguments are not supplied
        return a tuple of (axes, kwargs).

        sentinel specifies the default parameter when an axis is not
        supplied; useful to distinguish when a user explicitly passes None
        in scenarios where None has special meaning.
        rz)not enough/duplicate arguments specified!Ncsi|]}�j|��|�qSro)�pop)r�r�)r��sentinelrorpr�jsz:NDFrame._construct_axes_from_arguments.<locals>.<dictcomp>)�listr�r��
IndexErrorrb)r��argsr�r�r�r��errrZro)r�r�rp�_construct_axes_from_argumentsNsz&NDFrame._construct_axes_from_arguments)r�r�cCs:y
|j|Stk
r4td|�d|j����YnXdS)NzNo axis named z for object type )�_AXIS_TO_AXIS_NUMBER�KeyError�
ValueErrorrd)r�r�rororp�_get_axis_numberms
zNDFrame._get_axis_numbercCs|j|�}|j|S)N)r�r�)r�r��axis_numberrororp�_get_axis_namets
zNDFrame._get_axis_namecCs*|j|�}|dkst�|dkr$|jS|jS)Nrr\>rr\)r��AssertionErrorr_�columns)rjr�r�rororpr�ys
zNDFrame._get_axiscCs&|j|�}|jr"|jd}||S|S)z'Map the axis to the block_manager axis.r\)r��_AXIS_REVERSED�	_AXIS_LEN)r�r��mrororpr�~s


zNDFrame._get_block_manager_axiscCs�t||�}t�}|d}xZt|j�D]L\}}|dk	r>|}}n|�d|��}|}|j|�}	|	j�}
||
_|
||<q$Wt|t�r�|}n|j�}|||<|S)NrZlevel_)	�getattrr��	enumerate�names�get_level_valuesZ	to_seriesr_�
isinstancerJ)rjr�Z
axis_indexr��prefix�i�name�key�levelZlevel_values�sZdindexrororp�_get_axis_resolvers�s"



zNDFrame._get_axis_resolverscsFddlm�i}x|jD]}|j|j|��qW�fdd�|j�D�S)Nr)�clean_column_namecs$i|]\}}t|t�s|�|��qSro)r��int)r��k�v)r�rorpr��sz0NDFrame._get_index_resolvers.<locals>.<dictcomp>)�pandas.core.computation.parsingr�r�r�r�r�)rjr��	axis_namero)r�rp�_get_index_resolvers�s
zNDFrame._get_index_resolverscs:ddlm�t|t�r$�|j�|iS�fdd�|j�D�S)z�
        Return the special character free column resolvers of a dataframe.

        Column names with special characters are 'cleaned up' so that they can
        be referred to by backtick quoting.
        Used in :meth:`DataFrame.eval`.
        r)r�cs$i|]\}}t|t�s|�|��qSro)r�r�)r�r�r�)r�rorpr��sz9NDFrame._get_cleaned_column_resolvers.<locals>.<dictcomp>)r�r�r�r@r�r�)rjro)r�rp�_get_cleaned_column_resolvers�s


z%NDFrame._get_cleaned_column_resolverscCst||j�S)N)r��_info_axis_name)rjrororp�
_info_axis�szNDFrame._info_axiscCst||j�S)N)r��_stat_axis_name)rjrororp�
_stat_axis�szNDFrame._stat_axis.cst�fdd��jD��S)z3
        Return a tuple of axis dimensions
        c3s|]}t�j|��VqdS)N)r�r�)r�r�)rjrorp�	<genexpr>�sz NDFrame.shape.<locals>.<genexpr>)�tupler�)rjro)rjrp�shape�sz
NDFrame.shapecs�fdd��jD�S)z?
        Return index label(s) of the internal NDFrame
        csg|]}�j|��qSro)r�)r�r�)rjrorp�
<listcomp>�sz NDFrame.axes.<locals>.<listcomp>)r�)rjro)rjrprZ�szNDFrame.axescCs|jjS)a�
        Return an int representing the number of axes / array dimensions.

        Return 1 if Series. Otherwise return 2 if DataFrame.

        See Also
        --------
        ndarray.ndim : Number of array dimensions.

        Examples
        --------
        >>> s = pd.Series({'a': 1, 'b': 2, 'c': 3})
        >>> s.ndim
        1

        >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
        >>> df.ndim
        2
        )rsra)rjrororpra�szNDFrame.ndimcCstj|j�S)a
        Return an int representing the number of elements in this object.

        Return the number of rows if Series. Otherwise return the number of
        rows times number of columns if DataFrame.

        See Also
        --------
        ndarray.size : Number of elements in the array.

        Examples
        --------
        >>> s = pd.Series({'a': 1, 'b': 2, 'c': 3})
        >>> s.size
        3

        >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
        >>> df.size
        4
        )�np�prodr�)rjrororp�size�szNDFrame.sizecCs|S)z% internal compat with SelectionMixin ro)rjrororp�
_selected_objszNDFrame._selected_objcCs|S)z% internal compat with SelectionMixin ro)rjrororp�_obj_with_exclusionsszNDFrame._obj_with_exclusions)r�rmcCs8|rt||j|�|�n|j�}|j||dd�|SdS)a
        Assign desired index to given axis.

        Indexes for%(extended_summary_sub)s row labels can be changed by assigning
        a list-like or Index.

        Parameters
        ----------
        labels : list-like, Index
            The values for the new index.

        axis : %(axes_single_arg)s, default 0
            The axis to update. The value 0 identifies the rows%(axis_description_sub)s.

        inplace : bool, default False
            Whether to return a new %(klass)s instance.

        Returns
        -------
        renamed : %(klass)s or None
            An object of type %(klass)s if inplace=False, None otherwise.

        See Also
        --------
        %(klass)s.rename_axis : Alter the name of the index%(see_also_sub)s.
        T)r�rmN)�setattrr�re�set_axis)rj�labelsr�rm�objrororpr�s
zNDFrame.set_axis)r�r�r�cCs"t|�}|jj||�|j�dS)N)rLrsr��_clear_item_cache)rjr�r�rororp�	_set_axis2szNDFrame._set_axisTcs��j|�}�j|�}||kr,|r(�j�S�S||||i���fdd�t�j�D�}�jj||�}|rl|j�}�j|f|��j�dd�S)z�
        Interchange axes and swap values axes appropriately.

        Returns
        -------
        y : same as input
        c3s |]}�j�j||��VqdS)N)r��get)r�r�)�mappingrjrorpr�Isz#NDFrame.swapaxes.<locals>.<genexpr>�swapaxes)rl)r�re�ranger�rfr�r�rh)rjZaxis1Zaxis2rer��jZnew_axes�
new_valuesro)r�rjrpr�7s

zNDFrame.swapaxescCs(|j|�}|j|�}|j||dd�}|S)a�
        Return DataFrame with requested index / column level(s) removed.

        .. versionadded:: 0.24.0

        Parameters
        ----------
        level : int, str, or list-like
            If a string is given, must be the name of a level
            If list-like, elements must be names or positional indexes
            of levels.

        axis : {0 or 'index', 1 or 'columns'}, default 0
            Axis along which the level(s) is removed:

            * 0 or 'index': remove level(s) in column.
            * 1 or 'columns': remove level(s) in row.

        Returns
        -------
        DataFrame
            DataFrame with requested index / column level(s) removed.

        Examples
        --------
        >>> df = pd.DataFrame([
        ...     [1, 2, 3, 4],
        ...     [5, 6, 7, 8],
        ...     [9, 10, 11, 12]
        ... ]).set_index([0, 1]).rename_axis(['a', 'b'])

        >>> df.columns = pd.MultiIndex.from_tuples([
        ...     ('c', 'e'), ('d', 'f')
        ... ], names=['level_1', 'level_2'])

        >>> df
        level_1   c   d
        level_2   e   f
        a b
        1 2      3   4
        5 6      7   8
        9 10    11  12

        >>> df.droplevel('a')
        level_1   c   d
        level_2   e   f
        b
        2        3   4
        6        7   8
        10      11  12

        >>> df.droplevel('level_2', axis=1)
        level_1   c   d
        a b
        1 2      3   4
        5 6      7   8
        9 10    11  12
        F)r�rm)r��	droplevelr�)rjr�r�r�Z
new_labelsrnrororpr�Ts;

zNDFrame.droplevelrY)�itemr�cCs$||}||=|jdkr |j�|S)N�)ra�
_reset_cacher)rjr�rnrororpr��s

zNDFrame.popcs@�dkrt|j�n
|j��f�|jt�fdd�t|j�D��S)a�

        Squeeze 1 dimensional axis objects into scalars.

        Series or DataFrames with a single element are squeezed to a scalar.
        DataFrames with a single column or a single row are squeezed to a
        Series. Otherwise the object is unchanged.

        This method is most useful when you don't know if your
        object is a Series or DataFrame, but you do know it has just a single
        column. In that case you can safely call `squeeze` to ensure you have a
        Series.

        Parameters
        ----------
        axis : {0 or 'index', 1 or 'columns', None}, default None
            A specific axis to squeeze. By default, all length-1 axes are
            squeezed.

        Returns
        -------
        DataFrame, Series, or scalar
            The projection after squeezing `axis` or all the axes.

        See Also
        --------
        Series.iloc : Integer-location based indexing for selecting scalars.
        DataFrame.iloc : Integer-location based indexing for selecting Series.
        Series.to_frame : Inverse of DataFrame.squeeze for a
            single-column DataFrame.

        Examples
        --------
        >>> primes = pd.Series([2, 3, 5, 7])

        Slicing might produce a Series with a single value:

        >>> even_primes = primes[primes % 2 == 0]
        >>> even_primes
        0    2
        dtype: int64

        >>> even_primes.squeeze()
        2

        Squeezing objects with more than one value in every axis does nothing:

        >>> odd_primes = primes[primes % 2 == 1]
        >>> odd_primes
        1    3
        2    5
        3    7
        dtype: int64

        >>> odd_primes.squeeze()
        1    3
        2    5
        3    7
        dtype: int64

        Squeezing is even more effective when used with DataFrames.

        >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])
        >>> df
           a  b
        0  1  2
        1  3  4

        Slicing a single column will produce a DataFrame with the columns
        having only one value:

        >>> df_a = df[['a']]
        >>> df_a
           a
        0  1
        1  3

        So the columns can be squeezed down, resulting in a Series:

        >>> df_a.squeeze('columns')
        0    1
        1    3
        Name: a, dtype: int64

        Slicing a single row from a single column will produce a single
        scalar DataFrame:

        >>> df_0a = df.loc[df.index < 1, ['a']]
        >>> df_0a
           a
        0  1

        Squeezing the rows produces a single scalar Series:

        >>> df_0a.squeeze('rows')
        a    1
        Name: 0, dtype: int64

        Squeezing all axes will project directly into a scalar:

        >>> df_0a.squeeze()
        1
        Nc3s2|]*\}}|�kr"t|�dkr"dntd�VqdS)r\rN)r��slice)r�r�r�)r�rorpr�sz"NDFrame.squeeze.<locals>.<genexpr>)r�r�r��ilocr�r�rZ)rjr�ro)r�rp�squeeze�s
g
zNDFrame.squeeze�ignore)r_r�r�rermr��errors)
rj�mapperr_r�r�rermr�r�r�csj|dkr |dkr |dkr td��|dk	s0|dk	rT|dk	rBtd��qp|dk	rptd��n|rl|j|�dkrl|}n|}|rx|n
|j|d�}	x�t||f�D]�\}
}|dkr�q�|j|
�}tj|�}
|dk	r�|j|�}t|��s|j	|��|dko�t
��dk��r�fdd	�t|�D�}t|�d
���|j|
|�}|	j
||
dd�|	j�q�W|�rX|j|	�dS|	j|d
d�SdS)a�
        Alter axes input function or functions. 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 (Series only).

        Parameters
        ----------
        %(axes)s : scalar, list-like, dict-like or function, optional
            Scalar or list-like will alter the ``Series.name`` attribute,
            and raise on DataFrame.
            dict-like or functions are transformations to apply to
            that axis' values
        copy : bool, default True
            Also copy underlying data.
        inplace : bool, default False
            Whether to return a new {klass}. If True then value of copy is
            ignored.
        level : int or level name, default None
            In case of a MultiIndex, only rename labels in the specified
            level.
        errors : {'ignore', 'raise'}, default 'ignore'
            If 'raise', raise a `KeyError` when a dict-like `mapper`, `index`,
            or `columns` contains labels that are not present in the Index
            being transformed.
            If 'ignore', existing keys will be renamed and extra keys will be
            ignored.

        Returns
        -------
        renamed : {klass} (new object)

        Raises
        ------
        KeyError
            If any of the labels is not found in the selected axis and
            "errors='raise'".

        See Also
        --------
        NDFrame.rename_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

        Since ``DataFrame`` doesn't have a ``.name`` attribute,
        only mapping-type arguments are allowed.

        >>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
        >>> df.rename(2)
        Traceback (most recent call last):
        ...
        TypeError: 'int' object is not callable

        ``DataFrame.rename`` supports two calling conventions

        * ``(index=index_mapper, columns=columns_mapper, ...)``
        * ``(mapper, axis={'index', 'columns'}, ...)``

        We *highly* recommend using keyword arguments to clarify your
        intent.

        >>> df.rename(index=str, columns={"A": "a", "B": "c"})
           a  c
        0  1  4
        1  2  5
        2  3  6

        >>> df.rename(index=str, columns={"A": "a", "C": "c"})
           a  B
        0  1  4
        1  2  5
        2  3  6

        Using axis-style parameters

        >>> df.rename(str.lower, axis='columns')
           a  b
        0  1  4
        1  2  5
        2  3  6

        >>> df.rename({1: 2, 2: 4}, axis='index')
           A  B
        0  1  4
        2  2  5
        4  3  6

        See the :ref:`user guide <basics.rename>` for more.
        Nzmust pass an index to renamez:Cannot specify both 'axis' and any of 'index' or 'columns'z<Cannot specify both 'mapper' and any of 'index' or 'columns'r\)�deep�raisecs g|]\}}�|dkr|�qS)r\���ro)r�r_�label)�indexerrorpr��sz"NDFrame.rename.<locals>.<listcomp>z not found in axisT)r�rm�rename)rlr�)rbr�rer�r��com�get_rename_function�_get_level_number�callable�get_indexer_forr�r�Z_transform_indexr�r�rirh)rjr�r_r�r�rermr�r�rnZaxis_no�replacements�ax�fZmissing_labels�	new_indexro)r�rpr�sB{






zNDFrame.renamer�rermcsl|jf|tjd�\}}|jdd�}|jdd�}|jdd�}|dk	rL|j|�}|rltd	t|j��d�d
���t|d�}|tjk	r�t	|�p�t
|�o�t|�}|r�|j|||d�St
d��n�|r�|n
|j|d
�}x�t|j�D]�}|j|j|��}	|	tjkr�q�t	|	��pt
|	��ot|	�}|�r"|	}
n(tj|	��|j|�j}�fdd�|D�}
|j|
|dd�q�W|�sh|SdS)ag
        Set the name of the axis for the index or columns.

        Parameters
        ----------
        mapper : scalar, list-like, optional
            Value to set the axis name attribute.
        index, columns : scalar, list-like, dict-like or function, optional
            A scalar, list-like, dict-like or functions transformations to
            apply to that axis' values.
            Note that the ``columns`` parameter is not allowed if the
            object is a Series. This parameter only apply for DataFrame
            type objects.

            Use either ``mapper`` and ``axis`` to
            specify the axis to target with ``mapper``, or ``index``
            and/or ``columns``.

            .. versionchanged:: 0.24.0

        axis : {0 or 'index', 1 or 'columns'}, default 0
            The axis to rename.
        copy : bool, default True
            Also copy underlying data.
        inplace : bool, default False
            Modifies the object directly, instead of creating a new Series
            or DataFrame.

        Returns
        -------
        Series, DataFrame, or None
            The same type as the caller or None if `inplace` is True.

        See Also
        --------
        Series.rename : Alter Series index labels or name.
        DataFrame.rename : Alter DataFrame index labels or name.
        Index.rename : Set new names on index.

        Notes
        -----
        ``DataFrame.rename_axis`` supports two calling conventions

        * ``(index=index_mapper, columns=columns_mapper, ...)``
        * ``(mapper, axis={'index', 'columns'}, ...)``

        The first calling convention will only modify the names of
        the index and/or the names of the Index object that is the columns.
        In this case, the parameter ``copy`` is ignored.

        The second calling convention will modify the names of the
        the corresponding index if mapper is a list or a scalar.
        However, if mapper is dict-like or a function, it will use the
        deprecated behavior of modifying the axis *labels*.

        We *highly* recommend using keyword arguments to clarify your
        intent.

        Examples
        --------
        **Series**

        >>> s = pd.Series(["dog", "cat", "monkey"])
        >>> s
        0       dog
        1       cat
        2    monkey
        dtype: object
        >>> s.rename_axis("animal")
        animal
        0    dog
        1    cat
        2    monkey
        dtype: object

        **DataFrame**

        >>> df = pd.DataFrame({"num_legs": [4, 4, 2],
        ...                    "num_arms": [0, 0, 2]},
        ...                   ["dog", "cat", "monkey"])
        >>> df
                num_legs  num_arms
        dog            4         0
        cat            4         0
        monkey         2         2
        >>> df = df.rename_axis("animal")
        >>> df
                num_legs  num_arms
        animal
        dog            4         0
        cat            4         0
        monkey         2         2
        >>> df = df.rename_axis("limbs", axis="columns")
        >>> df
        limbs   num_legs  num_arms
        animal
        dog            4         0
        cat            4         0
        monkey         2         2

        **MultiIndex**

        >>> df.index = pd.MultiIndex.from_product([['mammal'],
        ...                                        ['dog', 'cat', 'monkey']],
        ...                                       names=['type', 'name'])
        >>> df
        limbs          num_legs  num_arms
        type   name
        mammal dog            4         0
               cat            4         0
               monkey         2         2

        >>> df.rename_axis(index={'type': 'class'})
        limbs          num_legs  num_arms
        class  name
        mammal dog            4         0
               cat            4         0
               monkey         2         2

        >>> df.rename_axis(columns=str.upper)
        LIMBS          num_legs  num_arms
        type   name
        mammal dog            4         0
               cat            4         0
               monkey         2         2
        )r�reTrmFr�rNz2rename_axis() got an unexpected keyword argument "�")r�rmz,Use `.rename` to alter labels with a mapper.)r�csg|]}�|��qSroro)r�r�)r�rorpr�fsz'NDFrame.rename_axis.<locals>.<listcomp>)r�r�
no_defaultr�r�rbr��keysr*r<r7r4�_set_axis_namer�rer�r�r�r�r�r�r�r�)rjr�r�rZrermr�Z
non_mapperrnr�ZnewnamesZcurnamesro)r�rp�rename_axis�s@





zNDFrame.rename_axiscCsP|j|�}|j|�j|�}t|d�}|r,|n|j�}|j||dd�|sL|SdS)a4
        Set the name(s) of the axis.

        Parameters
        ----------
        name : str or list of str
            Name(s) to set.
        axis : {0 or 'index', 1 or 'columns'}, default 0
            The axis to set the label. The value 0 or 'index' specifies index,
            and the value 1 or 'columns' specifies columns.
        inplace : bool, default False
            If `True`, do operation inplace and return None.

        Returns
        -------
        Series, DataFrame, or None
            The same type as the caller or `None` if `inplace` is `True`.

        See Also
        --------
        DataFrame.rename : Alter the axis labels of :class:`DataFrame`.
        Series.rename : Alter the index labels or set the index name
            of :class:`Series`.
        Index.rename : Set the name of :class:`Index` or :class:`MultiIndex`.

        Examples
        --------
        >>> df = pd.DataFrame({"num_legs": [4, 4, 2]},
        ...                   ["dog", "cat", "monkey"])
        >>> df
                num_legs
        dog            4
        cat            4
        monkey         2
        >>> df._set_axis_name("animal")
                num_legs
        animal
        dog            4
        cat            4
        monkey         2
        >>> df.index = pd.MultiIndex.from_product(
        ...                [["mammal"], ['dog', 'cat', 'monkey']])
        >>> df._set_axis_name(["type", "name"])
                       num_legs
        type   name
        mammal dog        4
               cat        4
               monkey     2
        rmT)r�rmN)r�r�Z	set_namesr*rer�)rjr�r�rm�idxZrenamedrororprks2

zNDFrame._set_axis_namecst��fdd��jD��S)Nc3s$|]}�j|�j�j|��VqdS)N)r��equals)r�r�)�otherrjrorpr��sz(NDFrame._indexed_same.<locals>.<genexpr>)�allr�)rjrro)rrjrp�
_indexed_same�szNDFrame._indexed_samecCs.t|t|��pt|t|��s dS|jj|j�S)a%
        Test whether two objects contain the same elements.

        This function allows two Series or DataFrames to be compared against
        each other to see if they have the same shape and elements. NaNs in
        the same location are considered equal. The column headers do not
        need to have the same type, but the elements within the columns must
        be the same dtype.

        Parameters
        ----------
        other : Series or DataFrame
            The other Series or DataFrame to be compared with the first.

        Returns
        -------
        bool
            True if all elements are the same in both objects, False
            otherwise.

        See Also
        --------
        Series.eq : Compare two Series objects of the same length
            and return a Series where each element is True if the element
            in each Series is equal, False otherwise.
        DataFrame.eq : Compare two DataFrame objects of the same shape and
            return a DataFrame where each element is True if the respective
            element in each DataFrame is equal, False otherwise.
        testing.assert_series_equal : Raises an AssertionError if left and
            right are not equal. Provides an easy interface to ignore
            inequality in dtypes, indexes and precision among others.
        testing.assert_frame_equal : Like assert_series_equal, but targets
            DataFrames.
        numpy.array_equal : Return True if two arrays have the same shape
            and elements, False otherwise.

        Notes
        -----
        This function requires that the elements have the same dtype as their
        respective elements in the other Series or DataFrame. However, the
        column labels do not need to have the same type, as long as they are
        still considered equal.

        Examples
        --------
        >>> df = pd.DataFrame({1: [10], 2: [20]})
        >>> df
            1   2
        0  10  20

        DataFrames df and exactly_equal have the same types and values for
        their elements and column labels, which will return True.

        >>> exactly_equal = pd.DataFrame({1: [10], 2: [20]})
        >>> exactly_equal
            1   2
        0  10  20
        >>> df.equals(exactly_equal)
        True

        DataFrames df and different_column_type have the same element
        types and values, but have different types for the column labels,
        which will still return True.

        >>> different_column_type = pd.DataFrame({1.0: [10], 2.0: [20]})
        >>> different_column_type
           1.0  2.0
        0   10   20
        >>> df.equals(different_column_type)
        True

        DataFrames df and different_data_type have different types for the
        same values for their elements, and will return False even though
        their column labels are the same values and types.

        >>> different_data_type = pd.DataFrame({1: [10.0], 2: [20.0]})
        >>> different_data_type
              1     2
        0  10.0  20.0
        >>> df.equals(different_data_type)
        False
        F)r�rcrsr)rjrrororpr�sSzNDFrame.equalscCsX|j}t|�rtj|�}n4t|�s2t|�s2t|�r>tj|�}ntd|j	����|j
|�S)Nz*Unary negative expects numeric dtype, not )�_valuesr1�operator�invr9r=r:�negrbr`�__array_wrap__)rjrf�arrrororp�__neg__szNDFrame.__neg__cCsR|j}t|�r|}n4t|�s,t|�s,t|�r8tj|�}ntd|j����|j	|�S)NzBUnary plus expects bool, numeric, timedelta, or object dtype, not )
rr1r9r=r:r	�posrbr`r)rjrfr
rororp�__pos__szNDFrame.__pos__cCs0|js
|S|jjtj�}|j|�j|dd�}|S)N�
__invert__)rl)r�rs�applyr	�invertr�rh)rj�new_datarnrororpr's
zNDFrame.__invert__cCstdt|�j�d���dS)NzThe truth value of a zC is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().)r�rcrd)rjrororp�__nonzero__0szNDFrame.__nonzero__cCsH|j�}t|ttjf�r t|�St|�r<tdt|�j����|j	�dS)a"
        Return the bool of a single element Series or DataFrame.

        This must be a boolean scalar value, either True or False. It will raise a
        ValueError if the Series or DataFrame does not have exactly 1 element, or that
        element is not boolean (integer values 0 and 1 will also raise an exception).

        Returns
        -------
        bool
            The value in the Series or DataFrame.

        See Also
        --------
        Series.astype : Change the data type of a Series, including to boolean.
        DataFrame.astype : Change the data type of a DataFrame, including to boolean.
        numpy.bool_ : NumPy boolean data type, used by pandas for boolean values.

        Examples
        --------
        The method will only work for single element objects with a boolean value:

        >>> pd.Series([True]).bool()
        True
        >>> pd.Series([False]).bool()
        False

        >>> pd.DataFrame({'col': [True]}).bool()
        True
        >>> pd.DataFrame({'col': [False]}).bool()
        False
        z0bool cannot act on a non-boolean single element N)
r�r��boolr��bool_r<r�rcrdr)rjr�rororpr8s!zNDFrame.boolcCs|j�S)N)�abs)rjrororp�__abs__dszNDFrame.__abs__)rj�decimalsr�cCs
|j|�S)N)�round)rjrrororp�	__round__gszNDFrame.__round__cCs:|j|�}|dk	o8t|�o8||j|jko8|j||d�S)aw
        Test whether a key is a level reference for a given axis.

        To be considered a level reference, `key` must be a string that:
          - (axis=0): Matches the name of an index level and does NOT match
            a column label.
          - (axis=1): Matches the name of a column level and does NOT match
            an index label.

        Parameters
        ----------
        key : str
            Potential level name for the given axis
        axis : int, default 0
            Axis that levels are associated with (0 for index, 1 for columns)

        Returns
        -------
        is_level : bool
        N)r�)r�rArZr��_is_label_reference)rjr�r�rororp�_is_level_referencers

zNDFrame._is_level_referencecsJ�j����fdd�t�j�D�}�dk	oHt��oHt��fdd�|D��S)a8
        Test whether a key is a label reference for a given axis.

        To be considered a label reference, `key` must be a string that:
          - (axis=0): Matches a column label
          - (axis=1): Matches an index label

        Parameters
        ----------
        key: str
            Potential label name
        axis: int, default 0
            Axis perpendicular to the axis that labels are associated with
            (0 means search for column labels, 1 means search for index labels)

        Returns
        -------
        is_label: bool
        c3s|]}|�kr|VqdS)Nro)r�r�)r�rorpr��sz.NDFrame._is_label_reference.<locals>.<genexpr>Nc3s|]}��j|kVqdS)N)rZ)r�r�)r�rjrorpr��s)r�r�r�rA�any)rjr�r��
other_axesro)r�r�rjrpr�s

zNDFrame._is_label_reference)r�r�r�cCs|j||d�p|j||d�S)aD
        Test whether a key is a label or level reference for a given axis.

        To be considered either a label or a level reference, `key` must be a
        string that:
          - (axis=0): Matches a column label or an index level
          - (axis=1): Matches an index label or a column level

        Parameters
        ----------
        key: str
            Potential label or level name
        axis: int, default 0
            Axis that levels are associated with (0 for index, 1 for columns)

        Returns
        -------
        is_label_or_level: bool
        )r�)rr)rjr�r�rororp�_is_label_or_level_reference�sz$NDFrame._is_label_or_level_referencec	s��j����fdd�t�j�D�}�dk	r�t��r���j�jkr�t��fdd�|D��r��dkrfdnd\}}�dkrzdnd\}}d
��d|�d|�d
|�d|�d�}t|��dS)a�
        Check whether `key` is ambiguous.

        By ambiguous, we mean that it matches both a level of the input
        `axis` and a label of the other axis.

        Parameters
        ----------
        key: str or object
            Label or level name.
        axis: int, default 0
            Axis that levels are associated with (0 for index, 1 for columns).

        Raises
        ------
        ValueError: `key` is ambiguous
        c3s|]}|�kr|VqdS)Nro)r�r�)r�rorpr��sz:NDFrame._check_label_or_level_ambiguity.<locals>.<genexpr>Nc3s|]}��j|kVqdS)N)rZ)r�r�)r�rjrorpr��sr�anr_r��column�'z
' is both � z level and z label, which is ambiguous.)r"r_)r�r#)r�r#)r"r_)r�r�r�rArZr�rr�)	rjr�r�r Z
level_articleZ
level_typeZ
label_articleZ
label_type�msgro)r�r�rjrp�_check_label_or_level_ambiguity�s
$z'NDFrame._check_label_or_level_ambiguitycs�|j����fdd�t|j�D�}|j|�d�rT|j|�d�|j||dd�j}n*|j|�d�rv|j�j	|�j}nt
|��|jdkr�|r�t|j
|d�t�r�d}nd}�dkr�dnd	}td
|�d|�d|����|S)
a
        Return a 1-D array of values associated with `key`, a label or level
        from the given `axis`.

        Retrieval logic:
          - (axis=0): Return column values if `key` matches a column label.
            Otherwise return index level values if `key` matches an index
            level.
          - (axis=1): Return row values if `key` matches an index label.
            Otherwise return column level values if 'key' matches a column
            level

        Parameters
        ----------
        key: str
            Label or level name.
        axis: int, default 0
            Axis that levels are associated with (0 for index, 1 for columns)

        Returns
        -------
        values: np.ndarray

        Raises
        ------
        KeyError
            if `key` matches neither a label nor a level
        ValueError
            if `key` matches multiple labels
        FutureWarning
            if `key` is ambiguous. This will become an ambiguity error in a
            future version
        csg|]}|�kr|�qSroro)r�r�)r�rorpr�sz6NDFrame._get_label_or_level_values.<locals>.<listcomp>)r�rr\zX
For a multi-index, the label must be a tuple with elements corresponding to each level.�r#r_zThe z label 'z' is not unique.)r�r�r�rr'�xsrrrZr�r�rar�r�rJr�)rjr�r�r rfZ
multi_messageZlabel_axis_namero)r�rp�_get_label_or_level_values�s "

z"NDFrame._get_label_or_level_values)r�cs��j���tj|�}��fdd�|D�}|r@td��d|������fdd�|D�}��fdd�|D�}�j�}�dkr�|r�|j|ddd	�|r�|j|d
dd�nB|r�t|jt	�r�|jj
|�|_nt|jj�|_|r�|j|ddd�|S)a
        Drop labels and/or levels for the given `axis`.

        For each key in `keys`:
          - (axis=0): If key matches a column label then drop the column.
            Otherwise if key matches an index level then drop the level.
          - (axis=1): If key matches an index label then drop the row.
            Otherwise if key matches a column level then drop the level.

        Parameters
        ----------
        keys: str or list of str
            labels or levels to drop
        axis: int, default 0
            Axis that levels are associated with (0 for index, 1 for columns)

        Returns
        -------
        dropped: DataFrame

        Raises
        ------
        ValueError
            if any `keys` match neither a label nor a level
        csg|]}�j|�d�s|�qS))r�)r!)r�r�)r�rjrorpr�Rsz2NDFrame._drop_labels_or_levels.<locals>.<listcomp>z;The following keys are not valid labels or levels for axis z: csg|]}�j|�d�r|�qS))r�)r)r�r�)r�rjrorpr�^scsg|]}�j|�d�s|�qS))r�)r)r�r�)r�rjrorpr�`srT)�droprmr\)r�rm)
r�r�Zmaybe_make_listr�reZreset_indexr+r�r�rJr�rKr�)rjrr�Zinvalid_keysZlevels_to_dropZlabels_to_dropZdroppedro)r�rjrp�_drop_labels_or_levels3s*

zNDFrame._drop_labels_or_levelscCsttt|�j��d���dS)Nz0 objects are mutable, thus they cannot be hashed)rb�reprrcrd)rjrororp�__hash__�szNDFrame.__hash__cCs
t|j�S)z~
        Iterate over info axis.

        Returns
        -------
        iterator
            Info axis as iterator.
        )�iterr�)rjrororp�__iter__�s	zNDFrame.__iter__cCs|jS)z�
        Get the 'info axis' (see Indexing for more).

        This is index for Series, columns for DataFrame.

        Returns
        -------
        Index
            Info axis.
        )r�)rjrororpr�szNDFrame.keysccs"x|jD]}|||fVqWdS)z�
        Iterate over (label, values) on info axis

        This is index for Series and columns for DataFrame.

        Returns
        -------
        Generator
        N)r�)rj�hrororpr��s
z
NDFrame.itemscCs|j�S)N)r�)rjrororp�	iteritems�szNDFrame.iteritemscCs
t|j�S)zReturns length of info axis)r�r�)rjrororp�__len__�szNDFrame.__len__cCs
||jkS)z#True if the key is in the info axis)r�)rjr�rororp�__contains__�szNDFrame.__contains__cst�fdd��jD��S)a�
        Indicator whether DataFrame is empty.

        True if DataFrame is entirely empty (no items), meaning any of the
        axes are of length 0.

        Returns
        -------
        bool
            If DataFrame is empty, return True, if not return False.

        See Also
        --------
        Series.dropna : Return series without null values.
        DataFrame.dropna : Return DataFrame with labels on given axis omitted
            where (all or any) data are missing.

        Notes
        -----
        If DataFrame contains only NaNs, it is still not considered empty. See
        the example below.

        Examples
        --------
        An example of an actual empty DataFrame. Notice the index is empty:

        >>> df_empty = pd.DataFrame({'A' : []})
        >>> df_empty
        Empty DataFrame
        Columns: [A]
        Index: []
        >>> df_empty.empty
        True

        If we only have NaNs in our DataFrame, it is not considered empty! We
        will need to drop the NaNs to make the DataFrame empty:

        >>> df = pd.DataFrame({'A' : [np.nan]})
        >>> df
            A
        0 NaN
        >>> df.empty
        False
        >>> df.dropna().empty
        True
        c3s |]}t�j|��dkVqdS)rN)r�r�)r�r�)rjrorpr��sz NDFrame.empty.<locals>.<genexpr>)rr�)rjro)rjrp�empty�s0z
NDFrame.emptyi�cCstj|j|d�S)N)r`)r��asarrayr)rjr`rororp�	__array__�szNDFrame.__array__cCs>tj|�}t|�r|S|j|jdd�}|j|f|�j|dd�S)NF)rer)rl)rZitem_from_zerodimr<r�r�r�rh)rjrn�contextr�rororpr�s
zNDFrame.__array_wrap__cs4�fdd��jD�}tf�j�j�j�jd�|��S)Ncsi|]}t�|d�|�qS)N)r�)r�r�)rjrorpr�sz(NDFrame.__getstate__.<locals>.<dictcomp>)rs�_typrzr})rzr�rsr9r})rj�metaro)rjrp�__getstate__
szNDFrame.__getstate__cCs�t|t�r||_n�t|t�r�d|kr:d|kr:|jd�|d<|jd�}|dk	r�|jdi�}tj|d|�t|j	|j
�}x.t|�D]"}||kr�||}tj|||�q�Wx4|j�D]\}}||kr�tj|||�q�Wq�t
d��nt|�dkr�t
d��i|_dS)Nr�rsr9r~z(Pre-0.12 pickles are no longer supportedr�)r�rPrsr�r�r�rr��set�_internal_namesrzr�r�r�r�ru)rj�state�typr}r:r�r�rororp�__setstate__s*



zNDFrame.__setstate__cCs.ddjtt|���d�}t|�j�d|�d�S)N�[�,�]�(�))�join�maprWrcrd)rjZpreprrororp�__repr__<szNDFrame.__repr__cCstjd�r|j�SdSdS)z�
        Returns a LaTeX representation for a particular object.
        Mainly for use with nbconvert (jupyter notebook conversion to pdf).
        zdisplay.latex.reprN)r�
get_option�to_latex)rjrororp�_repr_latex_Bs
zNDFrame._repr_latex_cCs:tjd�r6|jtjd��}tj|jdd�tjd�}|SdS)zh
        Not a real Jupyter special repr method, but we use the same
        naming convention.
        zdisplay.html.table_schemazdisplay.max_rows�table)�orient)�object_pairs_hookN)rrI�head�json�loads�to_json�collections�OrderedDict)rjr|�payloadrororp�_repr_data_resource_Ls

zNDFrame._repr_data_resource_r)r[�Sheet1r(�infcCsVt|t�r|n|j�}ddlm}||||||||||d�	}|j|||	|
||d�dS)a�
        Write {klass} to an Excel sheet.

        To write a single {klass} to an Excel .xlsx file it is only necessary to
        specify a target file name. To write to multiple sheets it is necessary to
        create an `ExcelWriter` object with a target file name, and specify a sheet
        in the file to write to.

        Multiple sheets may be written to by specifying unique `sheet_name`.
        With all data written to the file it is necessary to save the changes.
        Note that creating an `ExcelWriter` object with a file name that already
        exists will result in the contents of the existing file being erased.

        Parameters
        ----------
        excel_writer : str or ExcelWriter object
            File path or existing ExcelWriter.
        sheet_name : str, default 'Sheet1'
            Name of sheet which will contain DataFrame.
        na_rep : str, default ''
            Missing data representation.
        float_format : str, optional
            Format string for floating point numbers. For example
            ``float_format="%.2f"`` will format 0.1234 to 0.12.
        columns : sequence or list of str, optional
            Columns to write.
        header : bool or list of str, default True
            Write out the column names. If a list of string is given it is
            assumed to be aliases for the column names.
        index : bool, default True
            Write row names (index).
        index_label : str or sequence, optional
            Column label for index column(s) if desired. If not specified, and
            `header` and `index` are True, then the index names are used. A
            sequence should be given if the DataFrame uses MultiIndex.
        startrow : int, default 0
            Upper left cell row to dump data frame.
        startcol : int, default 0
            Upper left cell column to dump data frame.
        engine : str, optional
            Write engine to use, 'openpyxl' or 'xlsxwriter'. You can also set this
            via the options ``io.excel.xlsx.writer``, ``io.excel.xls.writer``, and
            ``io.excel.xlsm.writer``.
        merge_cells : bool, default True
            Write MultiIndex and Hierarchical Rows as merged cells.
        encoding : str, optional
            Encoding of the resulting excel file. Only necessary for xlwt,
            other writers support unicode natively.
        inf_rep : str, default 'inf'
            Representation for infinity (there is no native representation for
            infinity in Excel).
        verbose : bool, default True
            Display more information in the error logs.
        freeze_panes : tuple of int (length 2), optional
            Specifies the one-based bottommost row and rightmost column that
            is to be frozen.

        See Also
        --------
        to_csv : Write DataFrame to a comma-separated values (csv) file.
        ExcelWriter : Class for writing DataFrame objects into excel sheets.
        read_excel : Read an Excel file into a pandas DataFrame.
        read_csv : Read a comma-separated values (csv) file into DataFrame.

        Notes
        -----
        For compatibility with :meth:`~DataFrame.to_csv`,
        to_excel serializes lists and dicts to strings before writing.

        Once a workbook has been saved it is not possible write further data
        without rewriting the whole workbook.

        Examples
        --------

        Create, write to and save a workbook:

        >>> df1 = pd.DataFrame([['a', 'b'], ['c', 'd']],
        ...                    index=['row 1', 'row 2'],
        ...                    columns=['col 1', 'col 2'])
        >>> df1.to_excel("output.xlsx")  # doctest: +SKIP

        To specify the sheet name:

        >>> df1.to_excel("output.xlsx",
        ...              sheet_name='Sheet_name_1')  # doctest: +SKIP

        If you wish to write to more than one sheet in the workbook, it is
        necessary to specify an ExcelWriter object:

        >>> df2 = df1.copy()
        >>> with pd.ExcelWriter('output.xlsx') as writer:  # doctest: +SKIP
        ...     df1.to_excel(writer, sheet_name='Sheet_name_1')
        ...     df2.to_excel(writer, sheet_name='Sheet_name_2')

        ExcelWriter can also be used to append to an existing Excel file:

        >>> with pd.ExcelWriter('output.xlsx',
        ...                     mode='a') as writer:  # doctest: +SKIP
        ...     df.to_excel(writer, sheet_name='Sheet_name_3')

        To set the library that is used to write the Excel file,
        you can pass the `engine` keyword (the default engine is
        automatically chosen depending on the file extension):

        >>> df1.to_excel('output1.xlsx', engine='xlsxwriter')  # doctest: +SKIP
        r)�ExcelFormatter)�na_rep�cols�header�float_formatr_�index_label�merge_cells�inf_rep)�
sheet_name�startrow�startcol�freeze_panes�engineN)r�r?�to_frameZpandas.io.formats.excelrY�write)rjZexcel_writerrarZr]r�r\r_r^rbrcrer_�encodingr`�verboserd�dfrY�	formatterrororp�to_excel[s(zNDFrame.to_excel�
�ms�infer)�path_or_bufrM�date_format�double_precision�force_ascii�	date_unit�default_handler�lines�compressionr_�indentr�c
Csbddlm}|dkr"|dkr"d}n|dkr.d}tj|�|p>d}|j||||||||||	|
|d�S)a�
        Convert the object to a JSON string.

        Note NaN's and None will be converted to null and datetime objects
        will be converted to UNIX timestamps.

        Parameters
        ----------
        path_or_buf : str or file handle, optional
            File path or object. If not specified, the result is returned as
            a string.
        orient : str
            Indication of expected JSON string format.

            * Series:

                - default is 'index'
                - allowed values are: {'split','records','index','table'}.

            * DataFrame:

                - default is 'columns'
                - allowed values are: {'split', 'records', 'index', 'columns',
                  'values', 'table'}.

            * The format of the JSON string:

                - 'split' : dict like {'index' -> [index], 'columns' -> [columns],
                  'data' -> [values]}
                - 'records' : list like [{column -> value}, ... , {column -> value}]
                - 'index' : dict like {index -> {column -> value}}
                - 'columns' : dict like {column -> {index -> value}}
                - 'values' : just the values array
                - 'table' : dict like {'schema': {schema}, 'data': {data}}

                Describing the data, where data component is like ``orient='records'``.

            .. versionchanged:: 0.20.0

        date_format : {None, 'epoch', 'iso'}
            Type of date conversion. 'epoch' = epoch milliseconds,
            'iso' = ISO8601. The default depends on the `orient`. For
            ``orient='table'``, the default is 'iso'. For all other orients,
            the default is 'epoch'.
        double_precision : int, default 10
            The number of decimal places to use when encoding
            floating point values.
        force_ascii : bool, default True
            Force encoded string to be ASCII.
        date_unit : str, default 'ms' (milliseconds)
            The time unit to encode to, governs timestamp and ISO8601
            precision.  One of 's', 'ms', 'us', 'ns' for second, millisecond,
            microsecond, and nanosecond respectively.
        default_handler : callable, default None
            Handler to call if object cannot otherwise be converted to a
            suitable format for JSON. Should receive a single argument which is
            the object to convert and return a serialisable object.
        lines : bool, default False
            If 'orient' is 'records' write out line delimited json format. Will
            throw ValueError if incorrect 'orient' since others are not list
            like.

        compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}

            A string representing the compression to use in the output file,
            only used when the first argument is a filename. By default, the
            compression is inferred from the filename.

            .. versionchanged:: 0.24.0
               'infer' option added and set to default
        index : bool, default True
            Whether to include the index values in the JSON string. Not
            including the index (``index=False``) is only supported when
            orient is 'split' or 'table'.

            .. versionadded:: 0.23.0

        indent : int, optional
           Length of whitespace used to indent each record.

           .. versionadded:: 1.0.0

        Returns
        -------
        None or str
            If path_or_buf is None, returns the resulting json format as a
            string. Otherwise returns None.

        See Also
        --------
        read_json : Convert a JSON string to pandas object.

        Notes
        -----
        The behavior of ``indent=0`` varies from the stdlib, which does not
        indent the output but does insert newlines. Currently, ``indent=0``
        and the default ``indent=None`` are equivalent in pandas, though this
        may change in a future release.

        Examples
        --------
        >>> import json
        >>> df = pd.DataFrame(
        ...     [["a", "b"], ["c", "d"]],
        ...     index=["row 1", "row 2"],
        ...     columns=["col 1", "col 2"],
        ... )

        >>> result = df.to_json(orient="split")
        >>> parsed = json.loads(result)
        >>> json.dumps(parsed, indent=4)  # doctest: +SKIP
        {
            "columns": [
                "col 1",
                "col 2"
            ],
            "index": [
                "row 1",
                "row 2"
            ],
            "data": [
                [
                    "a",
                    "b"
                ],
                [
                    "c",
                    "d"
                ]
            ]
        }

        Encoding/decoding a Dataframe using ``'records'`` formatted JSON.
        Note that index labels are not preserved with this encoding.

        >>> result = df.to_json(orient="records")
        >>> parsed = json.loads(result)
        >>> json.dumps(parsed, indent=4)  # doctest: +SKIP
        [
            {
                "col 1": "a",
                "col 2": "b"
            },
            {
                "col 1": "c",
                "col 2": "d"
            }
        ]

        Encoding/decoding a Dataframe using ``'index'`` formatted JSON:

        >>> result = df.to_json(orient="index")
        >>> parsed = json.loads(result)
        >>> json.dumps(parsed, indent=4)  # doctest: +SKIP
        {
            "row 1": {
                "col 1": "a",
                "col 2": "b"
            },
            "row 2": {
                "col 1": "c",
                "col 2": "d"
            }
        }

        Encoding/decoding a Dataframe using ``'columns'`` formatted JSON:

        >>> result = df.to_json(orient="columns")
        >>> parsed = json.loads(result)
        >>> json.dumps(parsed, indent=4)  # doctest: +SKIP
        {
            "col 1": {
                "row 1": "a",
                "row 2": "c"
            },
            "col 2": {
                "row 1": "b",
                "row 2": "d"
            }
        }

        Encoding/decoding a Dataframe using ``'values'`` formatted JSON:

        >>> result = df.to_json(orient="values")
        >>> parsed = json.loads(result)
        >>> json.dumps(parsed, indent=4)  # doctest: +SKIP
        [
            [
                "a",
                "b"
            ],
            [
                "c",
                "d"
            ]
        ]

        Encoding with Table Schema:

        >>> result = df.to_json(orient="table")
        >>> parsed = json.loads(result)
        >>> json.dumps(parsed, indent=4)  # doctest: +SKIP
        {
            "schema": {
                "fields": [
                    {
                        "name": "index",
                        "type": "string"
                    },
                    {
                        "name": "col 1",
                        "type": "string"
                    },
                    {
                        "name": "col 2",
                        "type": "string"
                    }
                ],
                "primaryKey": [
                    "index"
                ],
                "pandas_version": "0.20.0"
            },
            "data": [
                {
                    "index": "row 1",
                    "col 1": "a",
                    "col 2": "b"
                },
                {
                    "index": "row 2",
                    "col 1": "c",
                    "col 2": "d"
                }
            ]
        }
        r)rPNrLZiso�epoch)rpr�rMrqrrrsrtrurvrwr_rx)�	pandas.iorPrZis_nonnegative_intrR)
rjrprMrqrrrsrtrurvrwr_rxrPrororprR�s*|
zNDFrame.to_jsonr��strict�UTF-8)
r��mode�	complevel�complib�appendrTr_�min_itemsize�dropna�data_columnsr�rhr�cCs8ddlm}|j||||||||||	|
|||
|d�dS)a�
        Write the contained data to an HDF5 file using HDFStore.

        Hierarchical Data Format (HDF) is self-describing, allowing an
        application to interpret the structure and contents of a file with
        no outside information. One HDF file can hold a mix of related objects
        which can be accessed as a group or as individual objects.

        In order to add another DataFrame or Series to an existing HDF file
        please use append mode and a different a key.

        For more information see the :ref:`user guide <io.hdf5>`.

        Parameters
        ----------
        path_or_buf : str or pandas.HDFStore
            File path or HDFStore object.
        key : str
            Identifier for the group in the store.
        mode : {'a', 'w', 'r+'}, default 'a'
            Mode to open file:

            - 'w': write, a new file is created (an existing file with
              the same name would be deleted).
            - 'a': append, an existing file is opened for reading and
              writing, and if the file does not exist it is created.
            - 'r+': similar to 'a', but the file must already exist.
        complevel : {0-9}, optional
            Specifies a compression level for data.
            A value of 0 disables compression.
        complib : {'zlib', 'lzo', 'bzip2', 'blosc'}, default 'zlib'
            Specifies the compression library to be used.
            As of v0.20.2 these additional compressors for Blosc are supported
            (default if no compressor specified: 'blosc:blosclz'):
            {'blosc:blosclz', 'blosc:lz4', 'blosc:lz4hc', 'blosc:snappy',
            'blosc:zlib', 'blosc:zstd'}.
            Specifying a compression library which is not available issues
            a ValueError.
        append : bool, default False
            For Table formats, append the input data to the existing.
        format : {'fixed', 'table', None}, default 'fixed'
            Possible values:

            - 'fixed': Fixed format. Fast writing/reading. Not-appendable,
              nor searchable.
            - 'table': Table format. Write as a PyTables Table structure
              which may perform worse but allow more flexible operations
              like searching / selecting subsets of the data.
            - If None, pd.get_option('io.hdf.default_format') is checked,
              followed by fallback to "fixed"
        errors : str, default 'strict'
            Specifies how encoding and decoding errors are to be handled.
            See the errors argument for :func:`open` for a full list
            of options.
        encoding : str, default "UTF-8"
        min_itemsize : dict or int, optional
            Map column names to minimum string sizes for columns.
        nan_rep : Any, optional
            How to represent null values as str.
            Not allowed with append=True.
        data_columns : list of columns or True, optional
            List of columns to create as indexed data columns for on-disk
            queries, or True to use all columns. By default only the axes
            of the object are indexed. See :ref:`io.hdf5-query-data-columns`.
            Applicable only to format='table'.

        See Also
        --------
        DataFrame.read_hdf : Read from HDF file.
        DataFrame.to_parquet : Write a DataFrame to the binary parquet format.
        DataFrame.to_sql : Write to a sql table.
        DataFrame.to_feather : Write out feather-format for DataFrames.
        DataFrame.to_csv : Write out to a csv file.

        Examples
        --------
        >>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]},
        ...                   index=['a', 'b', 'c'])
        >>> df.to_hdf('data.h5', key='df', mode='w')

        We can add another object to the same file:

        >>> s = pd.Series([1, 2, 3, 4])
        >>> s.to_hdf('data.h5', key='s')

        Reading from HDF file:

        >>> pd.read_hdf('data.h5', 'df')
        A  B
        a  1  4
        b  2  5
        c  3  6
        >>> pd.read_hdf('data.h5', 's')
        0    1
        1    2
        2    3
        3    4
        dtype: int64

        Deleting file with data:

        >>> import os
        >>> os.remove('data.h5')
        r)�pytables)r}r~rr�rTr_r��nan_repr�r�r�rhN)rzr��to_hdf)rjrpr�r}r~rr�rTr_r�r�r�r�r�rhr�rororpr�	s"yzNDFrame.to_hdf�fail)r��	if_existsr_r�c
Cs.ddlm}
|
j||||||||||	d�
dS)a`
        Write records stored in a DataFrame to a SQL database.

        Databases supported by SQLAlchemy [1]_ are supported. Tables can be
        newly created, appended to, or overwritten.

        Parameters
        ----------
        name : str
            Name of SQL table.
        con : sqlalchemy.engine.(Engine or Connection) or sqlite3.Connection
            Using SQLAlchemy makes it possible to use any DB supported by that
            library. Legacy support is provided for sqlite3.Connection objects. The user
            is responsible for engine disposal and connection closure for the SQLAlchemy
            connectable See `here                 <https://docs.sqlalchemy.org/en/13/core/connections.html>`_.

        schema : str, optional
            Specify the schema (if database flavor supports this). If None, use
            default schema.
        if_exists : {'fail', 'replace', 'append'}, default 'fail'
            How to behave if the table already exists.

            * fail: Raise a ValueError.
            * replace: Drop the table before inserting new values.
            * append: Insert new values to the existing table.

        index : bool, default True
            Write DataFrame index as a column. Uses `index_label` as the column
            name in the table.
        index_label : str or sequence, default None
            Column label for index column(s). If None is given (default) and
            `index` is True, then the index names are used.
            A sequence should be given if the DataFrame uses MultiIndex.
        chunksize : int, optional
            Specify the number of rows in each batch to be written at a time.
            By default, all rows will be written at once.
        dtype : dict or scalar, optional
            Specifying the datatype for columns. If a dictionary is used, the
            keys should be the column names and the values should be the
            SQLAlchemy types or strings for the sqlite3 legacy mode. If a
            scalar is provided, it will be applied to all columns.
        method : {None, 'multi', callable}, optional
            Controls the SQL insertion clause used:

            * None : Uses standard SQL ``INSERT`` clause (one per row).
            * 'multi': Pass multiple values in a single ``INSERT`` clause.
            * callable with signature ``(pd_table, conn, keys, data_iter)``.

            Details and a sample callable implementation can be found in the
            section :ref:`insert method <io.sql.method>`.

            .. versionadded:: 0.24.0

        Raises
        ------
        ValueError
            When the table already exists and `if_exists` is 'fail' (the
            default).

        See Also
        --------
        read_sql : Read a DataFrame from a table.

        Notes
        -----
        Timezone aware datetime columns will be written as
        ``Timestamp with timezone`` type with SQLAlchemy if supported by the
        database. Otherwise, the datetimes will be stored as timezone unaware
        timestamps local to the original timezone.

        .. versionadded:: 0.24.0

        References
        ----------
        .. [1] https://docs.sqlalchemy.org
        .. [2] https://www.python.org/dev/peps/pep-0249/

        Examples
        --------
        Create an in-memory SQLite database.

        >>> from sqlalchemy import create_engine
        >>> engine = create_engine('sqlite://', echo=False)

        Create a table from scratch with 3 rows.

        >>> df = pd.DataFrame({'name' : ['User 1', 'User 2', 'User 3']})
        >>> df
             name
        0  User 1
        1  User 2
        2  User 3

        >>> df.to_sql('users', con=engine)
        >>> engine.execute("SELECT * FROM users").fetchall()
        [(0, 'User 1'), (1, 'User 2'), (2, 'User 3')]

        An `sqlalchemy.engine.Connection` can also be passed to to `con`:
        >>> with engine.begin() as connection:
        ...     df1 = pd.DataFrame({'name' : ['User 4', 'User 5']})
        ...     df1.to_sql('users', con=connection, if_exists='append')

        This is allowed to support operations that require that the same
        DBAPI connection is used for the entire operation.

        >>> df2 = pd.DataFrame({'name' : ['User 6', 'User 7']})
        >>> df2.to_sql('users', con=engine, if_exists='append')
        >>> engine.execute("SELECT * FROM users").fetchall()
        [(0, 'User 1'), (1, 'User 2'), (2, 'User 3'),
         (0, 'User 4'), (1, 'User 5'), (0, 'User 6'),
         (1, 'User 7')]

        Overwrite the table with just ``df2``.

        >>> df2.to_sql('users', con=engine, if_exists='replace',
        ...            index_label='id')
        >>> engine.execute("SELECT * FROM users").fetchall()
        [(0, 'User 6'), (1, 'User 7')]

        Specify the dtype (especially useful for integers with missing values).
        Notice that while pandas is forced to store the data as floating point,
        the database supports nullable integers. When fetching the data with
        Python, we get back integer scalars.

        >>> df = pd.DataFrame({"A": [1, None, 2]})
        >>> df
             A
        0  1.0
        1  NaN
        2  2.0

        >>> from sqlalchemy.types import Integer
        >>> df.to_sql('integers', con=engine, index=False,
        ...           dtype={"A": Integer()})

        >>> engine.execute("SELECT * FROM integers").fetchall()
        [(1,), (None,), (2,)]
        r)�sql)�schemar�r_r^�	chunksizer`rlN)rzr��to_sql)rjr��conr�r�r_r^r�r`rlr�rororpr��	szNDFrame.to_sql)rw�protocolr�cCs ddlm}|||||d�dS)a�
        Pickle (serialize) object to file.

        Parameters
        ----------
        path : str
            File path where the pickled object will be stored.
        compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None},         default 'infer'
            A string representing the compression to use in the output file. By
            default, infers from the file extension in specified path.
        protocol : int
            Int which indicates which protocol should be used by the pickler,
            default HIGHEST_PROTOCOL (see [1]_ paragraph 12.1.2). The possible
            values are 0, 1, 2, 3, 4. A negative value for the protocol
            parameter is equivalent to setting its value to HIGHEST_PROTOCOL.

            .. [1] https://docs.python.org/3/library/pickle.html.

        See Also
        --------
        read_pickle : Load pickled pandas object (or any object) from file.
        DataFrame.to_hdf : Write DataFrame to an HDF5 file.
        DataFrame.to_sql : Write DataFrame to a SQL database.
        DataFrame.to_parquet : Write a DataFrame to the binary parquet format.

        Examples
        --------
        >>> original_df = pd.DataFrame({"foo": range(5), "bar": range(5, 10)})
        >>> original_df
           foo  bar
        0    0    5
        1    1    6
        2    2    7
        3    3    8
        4    4    9
        >>> original_df.to_pickle("./dummy.pkl")

        >>> unpickled_df = pd.read_pickle("./dummy.pkl")
        >>> unpickled_df
           foo  bar
        0    0    5
        1    1    6
        2    2    7
        3    3    8
        4    4    9

        >>> import os
        >>> os.remove("./dummy.pkl")
        r)�	to_pickle)rwr�N)Zpandas.io.pickler�)rj�pathrwr�r�rororpr�:
s8zNDFrame.to_pickle)�excel�sepr�cKs(ddlm}|j|f||d�|��dS)an
        Copy object to the system clipboard.

        Write a text representation of object to the system clipboard.
        This can be pasted into Excel, for example.

        Parameters
        ----------
        excel : bool, default True
            Produce output in a csv format for easy pasting into excel.

            - True, use the provided separator for csv pasting.
            - False, write a string representation of the object to the clipboard.

        sep : str, default ``'\t'``
            Field delimiter.
        **kwargs
            These parameters will be passed to DataFrame.to_csv.

        See Also
        --------
        DataFrame.to_csv : Write a DataFrame to a comma-separated values
            (csv) file.
        read_clipboard : Read text from clipboard and pass to read_table.

        Notes
        -----
        Requirements for your platform.

          - Linux : `xclip`, or `xsel` (with `PyQt4` modules)
          - Windows : none
          - OS X : none

        Examples
        --------
        Copy the contents of a DataFrame to the clipboard.

        >>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=['A', 'B', 'C'])

        >>> df.to_clipboard(sep=',')  # doctest: +SKIP
        ... # Wrote the following to the system clipboard:
        ... # ,A,B,C
        ... # 0,1,2,3
        ... # 1,4,5,6

        We can omit the index by passing the keyword `index` and setting
        it to false.

        >>> df.to_clipboard(sep=',', index=False)  # doctest: +SKIP
        ... # Wrote the following to the system clipboard:
        ... # A,B,C
        ... # 1,2,3
        ... # 4,5,6
        r)�
clipboards)r�r�N)rzr��to_clipboard)rjr�r�r�r�rororpr�v
s9zNDFrame.to_clipboardcCs.td�}|jdkr|jj|�S|jj|�SdS)a*
        Return an xarray object from the pandas object.

        Returns
        -------
        xarray.DataArray or xarray.Dataset
            Data in the pandas structure converted to Dataset if the object is
            a DataFrame, or a DataArray if the object is a Series.

        See Also
        --------
        DataFrame.to_hdf : Write DataFrame to an HDF5 file.
        DataFrame.to_parquet : Write a DataFrame to the binary parquet format.

        Notes
        -----
        See the `xarray docs <https://xarray.pydata.org/en/stable/>`__

        Examples
        --------
        >>> df = pd.DataFrame([('falcon', 'bird', 389.0, 2),
        ...                    ('parrot', 'bird', 24.0, 2),
        ...                    ('lion', 'mammal', 80.5, 4),
        ...                    ('monkey', 'mammal', np.nan, 4)],
        ...                   columns=['name', 'class', 'max_speed',
        ...                            'num_legs'])
        >>> df
             name   class  max_speed  num_legs
        0  falcon    bird      389.0         2
        1  parrot    bird       24.0         2
        2    lion  mammal       80.5         4
        3  monkey  mammal        NaN         4

        >>> df.to_xarray()
        <xarray.Dataset>
        Dimensions:    (index: 4)
        Coordinates:
          * index      (index) int64 0 1 2 3
        Data variables:
            name       (index) object 'falcon' 'parrot' 'lion' 'monkey'
            class      (index) object 'bird' 'bird' 'mammal' 'mammal'
            max_speed  (index) float64 389.0 24.0 80.5 nan
            num_legs   (index) int64 2 2 4 4

        >>> df['max_speed'].to_xarray()
        <xarray.DataArray 'max_speed' (index: 4)>
        array([389. ,  24. ,  80.5,   nan])
        Coordinates:
          * index    (index) int64 0 1 2 3

        >>> dates = pd.to_datetime(['2018-01-01', '2018-01-01',
        ...                         '2018-01-02', '2018-01-02'])
        >>> df_multiindex = pd.DataFrame({'date': dates,
        ...                               'animal': ['falcon', 'parrot',
        ...                                          'falcon', 'parrot'],
        ...                               'speed': [350, 18, 361, 15]})
        >>> df_multiindex = df_multiindex.set_index(['date', 'animal'])

        >>> df_multiindex
                           speed
        date       animal
        2018-01-01 falcon    350
                   parrot     18
        2018-01-02 falcon    361
                   parrot     15

        >>> df_multiindex.to_xarray()
        <xarray.Dataset>
        Dimensions:  (animal: 2, date: 2)
        Coordinates:
          * date     (date) datetime64[ns] 2018-01-01 2018-01-02
          * animal   (animal) object 'falcon' 'parrot'
        Data variables:
            speed    (date, animal) int64 350 18 361 15
        �xarrayr\N)r"raZ	DataArrayZfrom_seriesZDatasetZfrom_dataframe)rjr�rororp�	to_xarray�
sL
zNDFrame.to_xarray)Zreturns�NaN�.cCs�|jdkr|j�}|
dkr$tjd�}
|dkr6tjd�}|dkrHtjd�}|dkrZtjd�}|dkrltjd�}t||||||||||	|
||d�
}|j|||
||||||d	�	S)
aW
        Render object to a LaTeX tabular, longtable, or nested table/tabular.

        Requires ``\usepackage{booktabs}``.  The output can be copy/pasted
        into a main LaTeX document or read from an external file
        with ``\input{table.tex}``.

        .. versionchanged:: 0.20.2
           Added to Series.

        .. versionchanged:: 1.0.0
           Added caption and label arguments.

        Parameters
        ----------
        buf : str, Path or StringIO-like, optional, default None
            Buffer to write to. If None, the output is returned as a string.
        columns : list of label, optional
            The subset of columns to write. Writes all columns by default.
        col_space : int, optional
            The minimum width of each column.
        header : bool or list of str, default True
            Write out the column names. If a list of strings is given,
            it is assumed to be aliases for the column names.
        index : bool, default True
            Write row names (index).
        na_rep : str, default 'NaN'
            Missing data representation.
        formatters : list of functions or dict of {str: function}, optional
            Formatter functions to apply to columns' elements by position or
            name. The result of each function must be a unicode string.
            List must be of length equal to the number of columns.
        float_format : one-parameter function or str, optional, default None
            Formatter for floating point numbers. For example
            ``float_format="%%.2f"`` and ``float_format="{:0.2f}".format`` will
            both result in 0.1234 being formatted as 0.12.
        sparsify : bool, optional
            Set to False for a DataFrame with a hierarchical index to print
            every multiindex key at each row. By default, the value will be
            read from the config module.
        index_names : bool, default True
            Prints the names of the indexes.
        bold_rows : bool, default False
            Make the row labels bold in the output.
        column_format : str, optional
            The columns format as specified in `LaTeX table format
            <https://en.wikibooks.org/wiki/LaTeX/Tables>`__ e.g. 'rcl' for 3
            columns. By default, 'l' will be used for all columns except
            columns of numbers, which default to 'r'.
        longtable : bool, optional
            By default, the value will be read from the pandas config
            module. Use a longtable environment instead of tabular. Requires
            adding a \usepackage{longtable} to your LaTeX preamble.
        escape : bool, optional
            By default, the value will be read from the pandas config
            module. When set to False prevents from escaping latex special
            characters in column names.
        encoding : str, optional
            A string representing the encoding to use in the output file,
            defaults to 'utf-8'.
        decimal : str, default '.'
            Character recognized as decimal separator, e.g. ',' in Europe.
        multicolumn : bool, default True
            Use \multicolumn to enhance MultiIndex columns.
            The default will be read from the config module.
        multicolumn_format : str, default 'l'
            The alignment for multicolumns, similar to `column_format`
            The default will be read from the config module.
        multirow : bool, default False
            Use \multirow to enhance MultiIndex rows. Requires adding a
            \usepackage{multirow} to your LaTeX preamble. Will print
            centered labels (instead of top-aligned) across the contained
            rows, separating groups via clines. The default will be read
            from the pandas config module.
        caption : str, optional
            The LaTeX caption to be placed inside ``\caption{}`` in the output.

            .. versionadded:: 1.0.0

        label : str, optional
            The LaTeX label to be placed inside ``\label{}`` in the output.
            This is used with ``\ref{}`` in the main ``.tex`` file.

            .. versionadded:: 1.0.0
        %(returns)s
        See Also
        --------
        DataFrame.to_string : Render a DataFrame to a console-friendly
            tabular output.
        DataFrame.to_html : Render a DataFrame as an HTML table.

        Examples
        --------
        >>> df = pd.DataFrame({'name': ['Raphael', 'Donatello'],
        ...                    'mask': ['red', 'purple'],
        ...                    'weapon': ['sai', 'bo staff']})
        >>> print(df.to_latex(index=False))  # doctest: +NORMALIZE_WHITESPACE
        \begin{tabular}{lll}
         \toprule
               name &    mask &    weapon \\
         \midrule
            Raphael &     red &       sai \\
          Donatello &  purple &  bo staff \\
        \bottomrule
        \end{tabular}
        r\Nzdisplay.latex.longtablezdisplay.latex.escapezdisplay.latex.multicolumnz display.latex.multicolumn_formatzdisplay.latex.multirow)r��	col_spacerZr\r_�
formattersr]�	bold_rows�sparsify�index_names�escape�decimal)	�buf�
column_format�	longtablerh�multicolumn�multicolumn_format�multirow�captionr�)rarfrrIrUrJ)rjr�r�r�r\r_rZr�r]r�r�r�r�r�r�rhr�r�r�r�r�r�rkrororprJsJ





zNDFrame.to_latexrB�wr�)rpr�rZr]r�r\r_r^r}rhrw�quoting�	quotechar�line_terminatorr�rq�doublequote�
escapecharr�r�r�cCsrt|t�r|n|j�}ddlm}||||||
||||||||||	||
||||d�}|j�|dkrn|jj�SdS)a�
        Write object to a comma-separated values (csv) file.

        .. versionchanged:: 0.24.0
            The order of arguments for Series was changed.

        Parameters
        ----------
        path_or_buf : str or file handle, default None
            File path or object, if None is provided the result is returned as
            a string.  If a file object is passed it should be opened with
            `newline=''`, disabling universal newlines.

            .. versionchanged:: 0.24.0

               Was previously named "path" for Series.

        sep : str, default ','
            String of length 1. Field delimiter for the output file.
        na_rep : str, default ''
            Missing data representation.
        float_format : str, default None
            Format string for floating point numbers.
        columns : sequence, optional
            Columns to write.
        header : bool or list of str, default True
            Write out the column names. If a list of strings is given it is
            assumed to be aliases for the column names.

            .. versionchanged:: 0.24.0

               Previously defaulted to False for Series.

        index : bool, default True
            Write row names (index).
        index_label : str or sequence, or False, default None
            Column label for index column(s) if desired. If None is given, and
            `header` and `index` are True, then the index names are used. A
            sequence should be given if the object uses MultiIndex. If
            False do not print fields for index names. Use index_label=False
            for easier importing in R.
        mode : str
            Python write mode, default 'w'.
        encoding : str, optional
            A string representing the encoding to use in the output file,
            defaults to 'utf-8'.
        compression : str or dict, default 'infer'
            If str, represents compression mode. If dict, value at 'method' is
            the compression mode. Compression mode may be any of the following
            possible values: {'infer', 'gzip', 'bz2', 'zip', 'xz', None}. If
            compression mode is 'infer' and `path_or_buf` is path-like, then
            detect compression mode from the following extensions: '.gz',
            '.bz2', '.zip' or '.xz'. (otherwise no compression). If dict given
            and mode is one of {'zip', 'gzip', 'bz2'}, or inferred as
            one of the above, other entries passed as
            additional compression options.

            .. versionchanged:: 1.0.0

               May now be a dict with key 'method' as compression mode
               and other entries as additional compression options if
               compression mode is 'zip'.

            .. versionchanged:: 1.1.0

               Passing compression options as keys in dict is
               supported for compression modes 'gzip' and 'bz2'
               as well as 'zip'.

        quoting : optional constant from csv module
            Defaults to csv.QUOTE_MINIMAL. If you have set a `float_format`
            then floats are converted to strings and thus csv.QUOTE_NONNUMERIC
            will treat them as non-numeric.
        quotechar : str, default '\"'
            String of length 1. Character used to quote fields.
        line_terminator : str, optional
            The newline character or character sequence to use in the output
            file. Defaults to `os.linesep`, which depends on the OS in which
            this method is called ('\n' for linux, '\r\n' for Windows, i.e.).

            .. versionchanged:: 0.24.0
        chunksize : int or None
            Rows to write at a time.
        date_format : str, default None
            Format string for datetime objects.
        doublequote : bool, default True
            Control quoting of `quotechar` inside a field.
        escapechar : str, default None
            String of length 1. Character used to escape `sep` and `quotechar`
            when appropriate.
        decimal : str, default '.'
            Character recognized as decimal separator. E.g. use ',' for
            European data.
        errors : str, default 'strict'
            Specifies how encoding and decoding errors are to be handled.
            See the errors argument for :func:`open` for a full list
            of options.

            .. versionadded:: 1.1.0

        Returns
        -------
        None or str
            If path_or_buf is None, returns the resulting csv format as a
            string. Otherwise returns None.

        See Also
        --------
        read_csv : Load a CSV file into a DataFrame.
        to_excel : Write DataFrame to an Excel file.

        Examples
        --------
        >>> df = pd.DataFrame({'name': ['Raphael', 'Donatello'],
        ...                    'mask': ['red', 'purple'],
        ...                    'weapon': ['sai', 'bo staff']})
        >>> df.to_csv(index=False)
        'name,mask,weapon\nRaphael,red,sai\nDonatello,purple,bo staff\n'

        Create 'out.zip' containing 'out.csv'

        >>> compression_opts = dict(method='zip',
        ...                         archive_name='out.csv')  # doctest: +SKIP
        >>> df.to_csv('out.zip', index=False,
        ...           compression=compression_opts)  # doctest: +SKIP
        r)�CSVFormatter)r�r�rhr�rwr�rZr]r[r\r_r^r}r�r�rqr�r�r�N)r�r?rfZpandas.io.formats.csvsr��saverp�getvalue)rjrpr�rZr]r�r\r_r^r}rhrwr�r�r�r�rqr�r�r�r�rjr�rkrororp�to_csv�s:
zNDFrame.to_csvcCs|tj|�f|_dS)zc
        Set the _cacher attribute on the calling object with a weakref to
        cacher.
        N)�weakref�refrt)rjr��cacherrororp�_set_as_cachedlszNDFrame._set_as_cachedcCst|d�r|`dS)z#
        Reset the cacher.
        rtN)�hasattrrt)rjrororpr�ss
zNDFrame._reset_cachercCs|jj|�}|jj||�dS)zO
        The object has called back to us saying maybe it has changed.
        N)r��get_locrs�iset)rjr�r��locrororp�_maybe_cache_changedzszNDFrame._maybe_cache_changedcCst|dd�dk	S)z3Return boolean indicating if self is cached or not.rtN)r�)rjrororp�
_is_cached�szNDFrame._is_cachedcCs"t|dd�}|dk	r|d�}|S)zreturn my cacher or NonertNr\)r�)rjr�rororp�_get_cacher�s
zNDFrame._get_cacher)�clear�verify_is_copyr�cCs�t|dd�}|dk	r`|d�}|dkr,|`n4t|�t|�krN|j|d|�n|jj|dd�|rr|jddd�|r~|j�dS)a!
        See if we need to update our parent cacher if clear, then clear our
        cache.

        Parameters
        ----------
        clear : bool, default False
            Clear the item cache.
        verify_is_copy : bool, default True
            Provide is_copy checks.
        rtNr\r��referant)r��t)r�rtr�r�rur��_check_setitem_copyr�)rjr�r�r�r�rororp�_maybe_update_cacher�s
zNDFrame._maybe_update_cachercCs|jj�dS)N)rur�)rjrororpr��szNDFrame._clear_item_cache)rj�is_copyr�cKsZ|dk	rtjdtdd�tjt�|�|j�|jj||j	|�dd�}|j
|�j|dd�S)	a�
        Return the elements in the given *positional* indices along an axis.

        This means that we are not indexing according to actual values in
        the index attribute of the object. We are indexing according to the
        actual position of the element in the object.

        Parameters
        ----------
        indices : array-like
            An array of ints indicating which positions to take.
        axis : {0 or 'index', 1 or 'columns', None}, default 0
            The axis on which to select elements. ``0`` means that we are
            selecting rows, ``1`` means that we are selecting columns.
        is_copy : bool
            Before pandas 1.0, ``is_copy=False`` can be specified to ensure
            that the return value is an actual copy. Starting with pandas 1.0,
            ``take`` always returns a copy, and the keyword is therefore
            deprecated.

            .. deprecated:: 1.0.0
        **kwargs
            For compatibility with :meth:`numpy.take`. Has no effect on the
            output.

        Returns
        -------
        taken : same type as caller
            An array-like containing the elements taken from the object.

        See Also
        --------
        DataFrame.loc : Select a subset of a DataFrame by labels.
        DataFrame.iloc : Select a subset of a DataFrame by positions.
        numpy.take : Take elements from an array along an axis.

        Examples
        --------
        >>> df = pd.DataFrame([('falcon', 'bird', 389.0),
        ...                    ('parrot', 'bird', 24.0),
        ...                    ('lion', 'mammal', 80.5),
        ...                    ('monkey', 'mammal', np.nan)],
        ...                   columns=['name', 'class', 'max_speed'],
        ...                   index=[0, 2, 3, 1])
        >>> df
             name   class  max_speed
        0  falcon    bird      389.0
        2  parrot    bird       24.0
        3    lion  mammal       80.5
        1  monkey  mammal        NaN

        Take elements at positions 0 and 3 along the axis 0 (default).

        Note how the actual indices selected (0 and 1) do not correspond to
        our selected indices 0 and 3. That's because we are selecting the 0th
        and 3rd rows, not rows whose indices equal 0 and 3.

        >>> df.take([0, 3])
             name   class  max_speed
        0  falcon    bird      389.0
        1  monkey  mammal        NaN

        Take elements at indices 1 and 2 along the axis 1 (column selection).

        >>> df.take([1, 2], axis=1)
            class  max_speed
        0    bird      389.0
        2    bird       24.0
        3  mammal       80.5
        1  mammal        NaN

        We may take elements using negative integers for positive indices,
        starting from the end of the object, just like with Python lists.

        >>> df.take([-1, -2])
             name   class  max_speed
        1  monkey  mammal        NaN
        3    lion  mammal       80.5
        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.r�)r�T)r��verify�take)rl)r�r�r��nvZ
validate_taker��_consolidate_inplacersr�r�r�rh)rj�indicesr�r�r�rrororpr��sRzNDFrame.takecCs2|j||d�}|j|�j|j|��s.|j|�|S)a
        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).

        See the docstring of `take` for full explanation of the parameters.
        )r�r�)r�r�r�_set_is_copy)rjr�r�rnrororp�_take_with_is_copy
s
zNDFrame._take_with_is_copy)�
drop_levelcCs�|j|�}|j|�}|dk	r�t|t�s.td��|j|||d�\}}td�g|j}|||<t|�}	|j	|	}
t
|
|
j|�|�|
S|dkr�||S|j�|j
}t|t�r�|j
j||d�\}}nb|j
j|�}t|tj��r|jtjk�r|j�\}
|j|
|d�S|j||d�St|��s"|j
|}t|��rl|jdk�rB|j|S|jj|�}|j||j|j
||jd�}
n|j	|}
||
_
|
j||
jd�|
S)	aL

        Return cross-section from the Series/DataFrame.

        This method takes a `key` argument to select data at a particular
        level of a MultiIndex.

        Parameters
        ----------
        key : label or tuple of label
            Label contained in the index, or partially in a MultiIndex.
        axis : {0 or 'index', 1 or 'columns'}, default 0
            Axis to retrieve cross-section on.
        level : object, defaults to first n levels (n=1 or len(key))
            In case of a key partially contained in a MultiIndex, indicate
            which levels are used. Levels can be referred by label or position.
        drop_level : bool, default True
            If False, returns object with same levels as self.

        Returns
        -------
        Series or DataFrame
            Cross-section from the original Series or DataFrame
            corresponding to the selected index levels.

        See Also
        --------
        DataFrame.loc : Access a group of rows and columns
            by label(s) or a boolean array.
        DataFrame.iloc : Purely integer-location based indexing
            for selection by position.

        Notes
        -----
        `xs` can not be used to set values.

        MultiIndex Slicers is a generic way to get/set values on
        any level or levels.
        It is a superset of `xs` functionality, see
        :ref:`MultiIndex Slicers <advanced.mi_slicers>`.

        Examples
        --------
        >>> d = {'num_legs': [4, 4, 2, 2],
        ...      'num_wings': [0, 0, 2, 2],
        ...      'class': ['mammal', 'mammal', 'mammal', 'bird'],
        ...      'animal': ['cat', 'dog', 'bat', 'penguin'],
        ...      'locomotion': ['walks', 'walks', 'flies', 'walks']}
        >>> df = pd.DataFrame(data=d)
        >>> df = df.set_index(['class', 'animal', 'locomotion'])
        >>> df
                                   num_legs  num_wings
        class  animal  locomotion
        mammal cat     walks              4          0
               dog     walks              4          0
               bat     flies              2          2
        bird   penguin walks              2          2

        Get values at specified index

        >>> df.xs('mammal')
                           num_legs  num_wings
        animal locomotion
        cat    walks              4          0
        dog    walks              4          0
        bat    flies              2          2

        Get values at several indexes

        >>> df.xs(('mammal', 'dog'))
                    num_legs  num_wings
        locomotion
        walks              4          0

        Get values at specified index and level

        >>> df.xs('cat', level=1)
                           num_legs  num_wings
        class  locomotion
        mammal walks              4          0

        Get values at several indexes and levels

        >>> df.xs(('bird', 'walks'),
        ...       level=[0, 'locomotion'])
                 num_legs  num_wings
        animal
        penguin         2          2

        Get values at specified column and axis

        >>> df.xs('num_wings', axis=1)
        class   animal   locomotion
        mammal  cat      walks         0
                dog      walks         0
                bat      flies         2
        bird    penguin  walks         2
        Name: num_wings, dtype: int64
        NzIndex must be a MultiIndex)r�r�r\)r�)r�)r_r�r`)re)r�r�r�rJrbZ
get_loc_levelr�rar�r�r�r�r�r_r�r��ndarrayr`rZnonzeror�r<rrsZfast_xsr�r�r��_is_view)rjr�r�r�r�r�r��new_axZ_indexerr�rnr_r�Zindsr�rororpr))
sNc










z
NDFrame.xscCst|��dS)N)r$)rjr�rororp�__getitem__�
szNDFrame.__getitem__cCs\|j}|j|�}|dkrX|jj|�}|jj|�}|j||�}|||<|j||�|j|_|S)z8Return the cached item, item represents a label indexer.N)	rur�r�r�rs�igetZ_box_col_valuesr�rw)rjr��cache�resr�rfrororp�_get_item_cache�
s
zNDFrame._get_item_cache)rj�slobjr�cCs`t|t�stt|���|j|�}|j|jj||d��}|j|�}|dkpL|j	}|j
||d�|S)zp
        Construct a slice of this container.

        Slicing with this method is *always* positional.
        )r�r)re)r�r�r�rcr�r�rsZ	get_slicerhr�r�)rjr�r�rnr�rororp�_slice�
s

zNDFrame._slice)r�r�cCs|jj||�|j�dS)N)rsr�r�)rjr�r�rororp�
_iset_item�
szNDFrame._iset_itemcCsNy|jj|�}Wn*tk
r:|jjt|j�||�dSXtj|||�dS)N)r�r�r�rs�insertr�rrr�)rjr�r�r�rororp�	_set_item�
szNDFrame._set_itemcCs(|sd|_n|dk	st�tj|�|_dS)N)rwr�r�r�)rjr�rerororpr�szNDFrame._set_is_copycCsN|jr6|jr6|j�}|dk	r2|jr2|jdddd�dS|jrJ|jddd�dS)aV
        Check if we are a view, have a cacher, and are of mixed type.
        If so, then force a setitem_copy check.

        Should be called just near setting a value

        Will return a boolean if it we are a view and are cached, but a
        single-dtype meaning that the cacher should be updated following
        setting.
        N�r�T)r�r��force)r�r�F)r�r�r��_is_mixed_typer�rw)rjr�rororp�%_check_is_chained_assignment_possiblesz-NDFrame._check_is_chained_assignment_possibler��settingcCs�|p|jsdStjd�}|dkr$dS|jdk	rft|jt�rf|j�}tj|�s\|j|jkrfd|_dSt|jt�rz|j}n|dkr�d}nd}|dkr�tj	|��n|dkr�t
j|tj|d�dS)	ar

        Parameters
        ----------
        stacklevel : int, default 4
           the level to show of the stack when the error is output
        t : str, the type of setting error
        force : bool, default False
           If True, then force showing an error.

        validate if we are doing a setitem on a chained copy.

        If you call this function, be sure to set the stacklevel such that the
        user will see the error *at the level of setting*

        It is technically possible to figure out that we are setting on
        a copy even WITH a multi-dtyped pandas object. In other words, some
        blocks may be views while other are not. Currently _is_view will ALWAYS
        return False for multi-blocks to avoid having to handle this case.

        df = DataFrame(np.arange(0,9), columns=['count'])
        df['group'] = 'b'

        # This technically need not raise SettingWithCopy if both are view
        # (which is not # generally guaranteed but is usually True.  However,
        # this is in general not a good practice and we recommend using .loc.
        df.iloc[0:5]['group'] = 'a'

        Nzmode.chained_assignmentr�z�
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copya
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copyr�r�)r�)
rwrrIr��str�gcZ
get_referentsr�r�ZSettingWithCopyErrorr�r�ZSettingWithCopyWarning)rjr�r�r�r��rrororpr�s&


	zNDFrame._check_setitem_copycCs�d}d}|jdkrDt|jt�rDy||jjk}Wntk
rBYnX|r�t|t�sX|f}x6|jD],}t|t�r`|dt|��|kr`||=d}q`W|s�|jdj	|�}|j
j|�y|j|=Wnt
k
r�YnXdS)z
        Delete item
        Fr�NTr\r�)rar�r�rJZ_enginerbr�r�rZr�rsZideleterur�)rjr�ZdeletedZmaybe_shortcut�colr�rororp�__delitem__gs*
zNDFrame.__delitem__c
Cs(y||Stttfk
r"|SXdS)a

        Get item from object for given key (ex: DataFrame column).

        Returns default value if not found.

        Parameters
        ----------
        key : object

        Returns
        -------
        value : same type as items contained in object
        N)r�r�r�)rjr��defaultrororpr��szNDFrame.getcCs|jjS)z;Return boolean indicating if self is view of another array )rsZis_view)rjrororpr��szNDFrame._is_view)rjrlrer�cCs"|j|j||||d�}|jf|�S)a
        Return an object with matching indices as other object.

        Conform the object to the same index on all axes. Optional
        filling logic, placing NaN in locations having no value
        in the previous index. A new object is produced unless the
        new index is equivalent to the current one and copy=False.

        Parameters
        ----------
        other : Object of the same data type
            Its row and column indices are used to define the new indices
            of this object.
        method : {None, 'backfill'/'bfill', 'pad'/'ffill', 'nearest'}
            Method to use for filling holes in reindexed DataFrame.
            Please note: this is only applicable to DataFrames/Series with a
            monotonically increasing/decreasing index.

            * None (default): don't fill gaps
            * pad / ffill: propagate last valid observation forward to next
              valid
            * backfill / bfill: use next valid observation to fill gap
            * nearest: use nearest valid observations to fill gap.

        copy : bool, default True
            Return a new object, even if the passed indexes are the same.
        limit : int, default None
            Maximum number of consecutive labels to fill for inexact matches.
        tolerance : optional
            Maximum distance between original and new labels for inexact
            matches. The values of the index at the matching locations most
            satisfy the equation ``abs(index[indexer] - target) <= tolerance``.

            Tolerance may be a scalar value, which applies the same tolerance
            to all values, or list-like, which applies variable tolerance per
            element. List-like includes list, tuple, array, Series, and must be
            the same size as the index and its dtype must exactly match the
            index's type.

        Returns
        -------
        Series or DataFrame
            Same type as caller, but with changed indices on each axis.

        See Also
        --------
        DataFrame.set_index : Set row labels.
        DataFrame.reset_index : Remove row labels or move them to new columns.
        DataFrame.reindex : Change to new indices or expand indices.

        Notes
        -----
        Same as calling
        ``.reindex(index=other.index, columns=other.columns,...)``.

        Examples
        --------
        >>> df1 = pd.DataFrame([[24.3, 75.7, 'high'],
        ...                     [31, 87.8, 'high'],
        ...                     [22, 71.6, 'medium'],
        ...                     [35, 95, 'medium']],
        ...                    columns=['temp_celsius', 'temp_fahrenheit',
        ...                             'windspeed'],
        ...                    index=pd.date_range(start='2014-02-12',
        ...                                        end='2014-02-15', freq='D'))

        >>> df1
                    temp_celsius  temp_fahrenheit windspeed
        2014-02-12          24.3             75.7      high
        2014-02-13          31.0             87.8      high
        2014-02-14          22.0             71.6    medium
        2014-02-15          35.0             95.0    medium

        >>> df2 = pd.DataFrame([[28, 'low'],
        ...                     [30, 'low'],
        ...                     [35.1, 'medium']],
        ...                    columns=['temp_celsius', 'windspeed'],
        ...                    index=pd.DatetimeIndex(['2014-02-12', '2014-02-13',
        ...                                            '2014-02-15']))

        >>> df2
                    temp_celsius windspeed
        2014-02-12          28.0       low
        2014-02-13          30.0       low
        2014-02-15          35.1    medium

        >>> df2.reindex_like(df1)
                    temp_celsius  temp_fahrenheit windspeed
        2014-02-12          28.0              NaN       low
        2014-02-13          30.0              NaN       low
        2014-02-14           NaN              NaN       NaN
        2014-02-15          35.1              NaN    medium
        )rZrlrer]�	tolerance)r�r��reindex)rjrrlrer]r�r�rororp�reindex_like�sezNDFrame.reindex_liker�)rmr�cCs�t|d�}|dk	r>|dk	s"|dk	r*td��|j|�}||i}	n.|dk	sN|dk	rd|j||fi�\}	}
ntd��|}x.|	j�D]"\}}|dk	rz|j||||d�}qzW|r�|j|�n|SdS)Nrmz2Cannot specify both 'labels' and 'index'/'columns'z>Need to specify at least one of 'labels', 'index' or 'columns')r�r�)r*r�r�r�r��
_drop_axisri)rjr�r�r_r�r�rmr�r�rZ�_r�rororpr+s"


zNDFrame.drop)rjr�r�cCs4|j|�}|j|�}|j|�}|jrp|dk	rPt|t�s>td��|j|||d�}n|j||d�}|jf||i�}n�t	t
j|��}|dk	r�t|t�s�td��|j|�j
|�}|dkr�|j�r�t|�d���n:|j
|�}|j|�dkj�}	|dko�|	�rt|�d���td�g|j}
||
|j|�<|jt|
�}|S)	a�
        Drop labels from specified axis. Used in the ``drop`` method
        internally.

        Parameters
        ----------
        labels : single label or list-like
        axis : int or axis name
        level : int or level name, default None
            For MultiIndex
        errors : {'ignore', 'raise'}, default 'raise'
            If 'ignore', suppress error and existing labels are dropped.

        Nzaxis must be a MultiIndex)r�r�)r�r�z not found in axisr\r�)r�r�r�Z	is_uniquer�rJr�r+r�r.r�Zindex_labels_to_arrayr��isinrr�r�rr�rar�r�)rjr�r�r�r�r�Znew_axisrnr�Zlabels_missing�slicerrororpr�8s2




zNDFrame._drop_axis)r�r�cCs(|j�|j�|j|_|j|d�dS)z�
        Replace self internals with result.

        Parameters
        ----------
        result : same type as self
        verify_is_copy : bool, default True
            Provide is_copy checks.
        )r�N)�_reset_cacher�rsr�)rjrnr�rororprioszNDFrame._update_inplace)rjr�r�cCs&tjdj|d�}|j|i}|jf|�S)a�
        Prefix labels with string `prefix`.

        For Series, the row labels are prefixed.
        For DataFrame, the column labels are prefixed.

        Parameters
        ----------
        prefix : str
            The string to add before each label.

        Returns
        -------
        Series or DataFrame
            New Series or DataFrame with updated labels.

        See Also
        --------
        Series.add_suffix: Suffix row labels with string `suffix`.
        DataFrame.add_suffix: Suffix column labels with string `suffix`.

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

        >>> s.add_prefix('item_')
        item_0    1
        item_1    2
        item_2    3
        item_3    4
        dtype: int64

        >>> df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]})
        >>> df
           A  B
        0  1  3
        1  2  4
        2  3  5
        3  4  6

        >>> df.add_prefix('col_')
             col_A  col_B
        0       1       3
        1       2       4
        2       3       5
        3       4       6
        z
{prefix}{})r�)�	functools�partialrTr�r�)rjr�r�r�rororp�
add_prefix�s6
zNDFrame.add_prefix)rj�suffixr�cCs&tjdj|d�}|j|i}|jf|�S)a�
        Suffix labels with string `suffix`.

        For Series, the row labels are suffixed.
        For DataFrame, the column labels are suffixed.

        Parameters
        ----------
        suffix : str
            The string to add after each label.

        Returns
        -------
        Series or DataFrame
            New Series or DataFrame with updated labels.

        See Also
        --------
        Series.add_prefix: Prefix row labels with string `prefix`.
        DataFrame.add_prefix: Prefix column labels with string `prefix`.

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

        >>> s.add_suffix('_item')
        0_item    1
        1_item    2
        2_item    3
        3_item    4
        dtype: int64

        >>> df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]})
        >>> df
           A  B
        0  1  3
        1  2  4
        2  3  5
        3  4  6

        >>> df.add_suffix('_col')
             A_col  B_col
        0       1       3
        1       2       4
        2       3       5
        3       4       6
        z
{}{suffix})r�)r�r�rTr�r�)rjr�r�r�rororp�
add_suffix�s6
zNDFrame.add_suffix�	quicksort�last)rmr��na_position�ignore_indexr�cCst|��dS)u�
        Sort by the values along either axis.

        Parameters
        ----------%(optional_by)s
        axis : %(axes_single_arg)s, default 0
             Axis to be sorted.
        ascending : bool or list of bool, default True
             Sort ascending vs. descending. Specify list for multiple sort
             orders.  If this is a list of bools, must match the length of
             the by.
        inplace : bool, default False
             If True, perform operation in-place.
        kind : {'quicksort', 'mergesort', 'heapsort'}, default 'quicksort'
             Choice of sorting algorithm. See also ndarray.np.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'
             Puts NaNs at the beginning if `first`; `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
            Apply the key function to the 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 a Series with the same shape as the input.
            It will be applied to each column in `by` independently.

            .. versionadded:: 1.1.0

        Returns
        -------
        DataFrame or None
            DataFrame with sorted values if inplace=False, None otherwise.

        See Also
        --------
        DataFrame.sort_index : Sort a DataFrame by the index.
        Series.sort_values : Similar method for a Series.

        Examples
        --------
        >>> df = pd.DataFrame({
        ...     'col1': ['A', 'A', 'B', np.nan, 'D', 'C'],
        ...     'col2': [2, 1, 9, 8, 7, 4],
        ...     'col3': [0, 1, 9, 4, 2, 3],
        ...     'col4': ['a', 'B', 'c', 'D', 'e', 'F']
        ... })
        >>> df
          col1  col2  col3 col4
        0    A     2     0    a
        1    A     1     1    B
        2    B     9     9    c
        3  NaN     8     4    D
        4    D     7     2    e
        5    C     4     3    F

        Sort by col1

        >>> df.sort_values(by=['col1'])
          col1  col2  col3 col4
        0    A     2     0    a
        1    A     1     1    B
        2    B     9     9    c
        5    C     4     3    F
        4    D     7     2    e
        3  NaN     8     4    D

        Sort by multiple columns

        >>> df.sort_values(by=['col1', 'col2'])
          col1  col2  col3 col4
        1    A     1     1    B
        0    A     2     0    a
        2    B     9     9    c
        5    C     4     3    F
        4    D     7     2    e
        3  NaN     8     4    D

        Sort Descending

        >>> df.sort_values(by='col1', ascending=False)
          col1  col2  col3 col4
        4    D     7     2    e
        5    C     4     3    F
        2    B     9     9    c
        0    A     2     0    a
        1    A     1     1    B
        3  NaN     8     4    D

        Putting NAs first

        >>> df.sort_values(by='col1', ascending=False, na_position='first')
          col1  col2  col3 col4
        3  NaN     8     4    D
        4    D     7     2    e
        5    C     4     3    F
        2    B     9     9    c
        0    A     2     0    a
        1    A     1     1    B

        Sorting with a key function

        >>> df.sort_values(by='col4', key=lambda col: col.str.lower())
           col1  col2  col3 col4
        0    A     2     0    a
        1    A     1     1    B
        2    B     9     9    c
        3  NaN     8     4    D
        4    D     7     2    e
        5    C     4     3    F
        N)r$)rjr��	ascendingrmr�r�r�r�rororp�sort_values�szNDFrame.sort_valuesr[rZ)r[rZZoptional_labelsZ
optional_axisc
s��j||�\}}tj|jdd��}|jdd�}|jdd�}|jdd�}|jdd�}|jdd�}	|jd	d�|r�td
t|j��d�d����j�t�fd
d�|j	�D��r�|r��j
�S�S�j|||�r؈j|||	�S�j
||||||	|�j�dd�S)a�
        Conform {klass} to new index with optional filling logic.

        Places NA/NaN in locations having no value in the previous index. A new object
        is produced unless the new index is equivalent to the current one and
        ``copy=False``.

        Parameters
        ----------
        {optional_labels}
        {axes} : array-like, optional
            New labels / index to conform to, should be specified using
            keywords. Preferably an Index object to avoid duplicating data.
        {optional_axis}
        method : {{None, 'backfill'/'bfill', 'pad'/'ffill', 'nearest'}}
            Method to use for filling holes in reindexed DataFrame.
            Please note: this is only applicable to DataFrames/Series with a
            monotonically increasing/decreasing index.

            * None (default): don't fill gaps
            * pad / ffill: Propagate last valid observation forward to next
              valid.
            * backfill / bfill: Use next valid observation to fill gap.
            * nearest: Use nearest valid observations to fill gap.

        copy : bool, default True
            Return a new object, even if the passed indexes are the same.
        level : int or name
            Broadcast across a level, matching Index values on the
            passed MultiIndex level.
        fill_value : scalar, default np.NaN
            Value to use for missing values. Defaults to NaN, but can be any
            "compatible" value.
        limit : int, default None
            Maximum number of consecutive elements to forward or backward fill.
        tolerance : optional
            Maximum distance between original and new labels for inexact
            matches. The values of the index at the matching locations most
            satisfy the equation ``abs(index[indexer] - target) <= tolerance``.

            Tolerance may be a scalar value, which applies the same tolerance
            to all values, or list-like, which applies variable tolerance per
            element. List-like includes list, tuple, array, Series, and must be
            the same size as the index and its dtype must exactly match the
            index's type.

        Returns
        -------
        {klass} with changed index.

        See Also
        --------
        DataFrame.set_index : Set row labels.
        DataFrame.reset_index : Remove row labels or move them to new columns.
        DataFrame.reindex_like : Change to same indices as other DataFrame.

        Examples
        --------
        ``DataFrame.reindex`` supports two calling conventions

        * ``(index=index_labels, columns=column_labels, ...)``
        * ``(labels, axis={{'index', 'columns'}}, ...)``

        We *highly* recommend using keyword arguments to clarify your
        intent.

        Create a dataframe with some fictional data.

        >>> index = ['Firefox', 'Chrome', 'Safari', 'IE10', 'Konqueror']
        >>> df = pd.DataFrame({{'http_status': [200, 200, 404, 404, 301],
        ...                   'response_time': [0.04, 0.02, 0.07, 0.08, 1.0]}},
        ...                   index=index)
        >>> df
                   http_status  response_time
        Firefox            200           0.04
        Chrome             200           0.02
        Safari             404           0.07
        IE10               404           0.08
        Konqueror          301           1.00

        Create a new index and reindex the dataframe. By default
        values in the new index that do not have corresponding
        records in the dataframe are assigned ``NaN``.

        >>> new_index = ['Safari', 'Iceweasel', 'Comodo Dragon', 'IE10',
        ...              'Chrome']
        >>> df.reindex(new_index)
                       http_status  response_time
        Safari               404.0           0.07
        Iceweasel              NaN            NaN
        Comodo Dragon          NaN            NaN
        IE10                 404.0           0.08
        Chrome               200.0           0.02

        We can fill in the missing values by passing a value to
        the keyword ``fill_value``. Because the index is not monotonically
        increasing or decreasing, we cannot use arguments to the keyword
        ``method`` to fill the ``NaN`` values.

        >>> df.reindex(new_index, fill_value=0)
                       http_status  response_time
        Safari                 404           0.07
        Iceweasel                0           0.00
        Comodo Dragon            0           0.00
        IE10                   404           0.08
        Chrome                 200           0.02

        >>> df.reindex(new_index, fill_value='missing')
                      http_status response_time
        Safari                404          0.07
        Iceweasel         missing       missing
        Comodo Dragon     missing       missing
        IE10                  404          0.08
        Chrome                200          0.02

        We can also reindex the columns.

        >>> df.reindex(columns=['http_status', 'user_agent'])
                   http_status  user_agent
        Firefox            200         NaN
        Chrome             200         NaN
        Safari             404         NaN
        IE10               404         NaN
        Konqueror          301         NaN

        Or we can use "axis-style" keyword arguments

        >>> df.reindex(['http_status', 'user_agent'], axis="columns")
                   http_status  user_agent
        Firefox            200         NaN
        Chrome             200         NaN
        Safari             404         NaN
        IE10               404         NaN
        Konqueror          301         NaN

        To further illustrate the filling functionality in
        ``reindex``, we will create a dataframe with a
        monotonically increasing index (for example, a sequence
        of dates).

        >>> date_index = pd.date_range('1/1/2010', periods=6, freq='D')
        >>> df2 = pd.DataFrame({{"prices": [100, 101, np.nan, 100, 89, 88]}},
        ...                    index=date_index)
        >>> df2
                    prices
        2010-01-01   100.0
        2010-01-02   101.0
        2010-01-03     NaN
        2010-01-04   100.0
        2010-01-05    89.0
        2010-01-06    88.0

        Suppose we decide to expand the dataframe to cover a wider
        date range.

        >>> date_index2 = pd.date_range('12/29/2009', periods=10, freq='D')
        >>> df2.reindex(date_index2)
                    prices
        2009-12-29     NaN
        2009-12-30     NaN
        2009-12-31     NaN
        2010-01-01   100.0
        2010-01-02   101.0
        2010-01-03     NaN
        2010-01-04   100.0
        2010-01-05    89.0
        2010-01-06    88.0
        2010-01-07     NaN

        The index entries that did not have a value in the original data frame
        (for example, '2009-12-29') are by default filled with ``NaN``.
        If desired, we can fill in the missing values using one of several
        options.

        For example, to back-propagate the last valid value to fill the ``NaN``
        values, pass ``bfill`` as an argument to the ``method`` keyword.

        >>> df2.reindex(date_index2, method='bfill')
                    prices
        2009-12-29   100.0
        2009-12-30   100.0
        2009-12-31   100.0
        2010-01-01   100.0
        2010-01-02   101.0
        2010-01-03     NaN
        2010-01-04   100.0
        2010-01-05    89.0
        2010-01-06    88.0
        2010-01-07     NaN

        Please note that the ``NaN`` value present in the original dataframe
        (at index value 2010-01-03) will not be filled by any of the
        value propagation schemes. This is because filling while reindexing
        does not look at dataframe values, but only compares the original and
        desired indexes. If you do want to fill in the ``NaN`` values present
        in the original dataframe, use the ``fillna()`` method.

        See the :ref:`user guide <basics.reindexing>` for more.
        rlNr�reTr]r��
fill_valuer�z.reindex() got an unexpected keyword argument "rr�c3s*|]"\}}|dk	r�j|�j|�VqdS)N)r�Z	identical)r�r�r�)rjrorpr�bsz"NDFrame.reindex.<locals>.<genexpr>r�)rl)r�rDZclean_reindex_fill_methodr�rbr�rr�rr�re�_needs_reindex_multi�_reindex_multi�
_reindex_axesrh)
rjr�r�rZrlr�rer]r�r�ro)rjrpr�xs0S
zNDFrame.reindexcCsp|}xf|jD]\}	||	}
|
dkr"q|j|	�}|j|
||||d�\}}
|j|	�}|j|||
gi||dd�}qW|S)z%Perform the reindex for all the axes.N)r�r]r�rlF)r�re�
allow_dups)r�r�r�r��_reindex_with_indexers)rjrZr�r]r�rlr�rer�r�r�r�r�r�r�rororpr�ss


zNDFrame._reindex_axescCs,tj|j��|jko*|dko*|dko*|jS)z$Check if we do need a multi reindex.N)r��count_not_nonerfr�r�)rjrZrlr�rororpr��szNDFrame._needs_reindex_multicCst|��dS)N)r$)rjrZrer�rororpr��szNDFrame._reindex_multi)rjrer�r�c
	Cs�|j}xft|j��D]V}||\}}|j|�}	|dkr8qt|�}|dk	rPt|�}|j|||	|||d�}d}qW|r�||jkr�|j�}|j|�j	|�S)z+allow_dups indicates an internal call here N)r�r�r�reF)
rs�sortedrr�rLr-�reindex_indexerrer�rh)
rj�
reindexersr�rer�rr�r_r�Zbaxisrororpr��s(	
zNDFrame._reindex_with_indexers)rj�like�regexr�c	s�tj|�|�}|dkrtd��|dkr,|j}|j|��|dk	rf|j|�}|jf|�fdd�|D�i�S�r��fdd�}�j|�}|j|d�|S|rćfd	d�}t	j
|���j|�}|j|d�|Std
��dS)u
        Subset the dataframe rows or columns according to the specified index labels.

        Note that this routine does not filter a dataframe on its
        contents. The filter is applied to the labels of the index.

        Parameters
        ----------
        items : list-like
            Keep labels from axis which are in items.
        like : str
            Keep labels from axis for which "like in label == True".
        regex : str (regular expression)
            Keep labels from axis for which re.search(regex, label) == True.
        axis : {0 or ‘index’, 1 or ‘columns’, None}, default None
            The axis to filter on, expressed either as an index (int)
            or axis name (str). By default this is the info axis,
            'index' for Series, 'columns' for DataFrame.

        Returns
        -------
        same type as input object

        See Also
        --------
        DataFrame.loc : Access a group of rows and columns
            by label(s) or a boolean array.

        Notes
        -----
        The ``items``, ``like``, and ``regex`` parameters are
        enforced to be mutually exclusive.

        ``axis`` defaults to the info axis that is used when indexing
        with ``[]``.

        Examples
        --------
        >>> df = pd.DataFrame(np.array(([1, 2, 3], [4, 5, 6])),
        ...                   index=['mouse', 'rabbit'],
        ...                   columns=['one', 'two', 'three'])
        >>> df
                one  two  three
        mouse     1    2      3
        rabbit    4    5      6

        >>> # select columns by name
        >>> df.filter(items=['one', 'three'])
                 one  three
        mouse     1      3
        rabbit    4      6

        >>> # select columns by regular expression
        >>> df.filter(regex='e$', axis=1)
                 one  three
        mouse     1      3
        rabbit    4      6

        >>> # select rows containing 'bbi'
        >>> df.filter(like='bbi', axis=0)
                 one  two  three
        rabbit    4    5      6
        r\zDKeyword arguments `items`, `like`, or `regex` are mutually exclusiveNcsg|]}|�kr|�qSroro)r�r�)r�rorpr�sz"NDFrame.filter.<locals>.<listcomp>cs�t|�kS)N)r/)�x)rrorpr�szNDFrame.filter.<locals>.f)r�cs�jt|��dk	S)N)�searchr/)r)�matcherrorpr�sz,Must pass either `items`, `like`, or `regex`)r�r�rbr�r�r�r�rGr��re�compile)	rjr�rrr�Znkwr�r�rfro)r�rrrp�filter�s(F




zNDFrame.filterr�)rj�nr�cCs|jd|�S)ae
        Return the first `n` rows.

        This function returns the first `n` rows for the object based
        on position. It is useful for quickly testing if your object
        has the right type of data in it.

        For negative values of `n`, this function returns all rows except
        the last `n` rows, equivalent to ``df[:-n]``.

        Parameters
        ----------
        n : int, default 5
            Number of rows to select.

        Returns
        -------
        same type as caller
            The first `n` rows of the caller object.

        See Also
        --------
        DataFrame.tail: Returns the last `n` rows.

        Examples
        --------
        >>> df = pd.DataFrame({'animal': ['alligator', 'bee', 'falcon', 'lion',
        ...                    'monkey', 'parrot', 'shark', 'whale', 'zebra']})
        >>> df
              animal
        0  alligator
        1        bee
        2     falcon
        3       lion
        4     monkey
        5     parrot
        6      shark
        7      whale
        8      zebra

        Viewing the first 5 lines

        >>> df.head()
              animal
        0  alligator
        1        bee
        2     falcon
        3       lion
        4     monkey

        Viewing the first `n` lines (three in this case)

        >>> df.head(3)
              animal
        0  alligator
        1        bee
        2     falcon

        For negative values of `n`

        >>> df.head(-3)
              animal
        0  alligator
        1        bee
        2     falcon
        3       lion
        4     monkey
        5     parrot
        N)r�)rjr	rororprO$sFzNDFrame.headcCs&|dkr|jdd�S|j|d�S)a5
        Return the last `n` rows.

        This function returns last `n` rows from the object based on
        position. It is useful for quickly verifying data, for example,
        after sorting or appending rows.

        For negative values of `n`, this function returns all rows except
        the first `n` rows, equivalent to ``df[n:]``.

        Parameters
        ----------
        n : int, default 5
            Number of rows to select.

        Returns
        -------
        type of caller
            The last `n` rows of the caller object.

        See Also
        --------
        DataFrame.head : The first `n` rows of the caller object.

        Examples
        --------
        >>> df = pd.DataFrame({'animal': ['alligator', 'bee', 'falcon', 'lion',
        ...                    'monkey', 'parrot', 'shark', 'whale', 'zebra']})
        >>> df
              animal
        0  alligator
        1        bee
        2     falcon
        3       lion
        4     monkey
        5     parrot
        6      shark
        7      whale
        8      zebra

        Viewing the last 5 lines

        >>> df.tail()
           animal
        4  monkey
        5  parrot
        6   shark
        7   whale
        8   zebra

        Viewing the last `n` lines (three in this case)

        >>> df.tail(3)
          animal
        6  shark
        7  whale
        8  zebra

        For negative values of `n`

        >>> df.tail(-3)
           animal
        3    lion
        4  monkey
        5  parrot
        6   shark
        7   whale
        8   zebra
        rN)r�)rjr	rororp�taillsFzNDFrame.tailcCs<|dkr|j}|j|�}|j|}tj|�}|dk	�r\t|t�rP|j|j|�}t|t	�r�t|t
�r�|dkr�y||}Wq�tk
r�}	ztd�|	�WYdd}	~	Xq�Xq�td��ntd��t
j|dd�}t|�|kr�td��|tjkj�s�|tjkj��rtd	��|dkj��rtd
��|jd�}|j�dk�rV|j�dk�rN||j�}ntd��|j}|dk�rv|dk�rvd}n�|dk	�r�|dk�r�|�r�td
��nn|dk	�r�|dk�r�|ddk�r�td��nB|dk�r�|dk	�r�tt||��}n|dk	�r
|dk	�r
td��|dk�rtd��|j||||d�}
|j|
|d�S)u�
        Return a random sample of items from an axis of object.

        You can use `random_state` for reproducibility.

        Parameters
        ----------
        n : int, optional
            Number of items from axis to return. Cannot be used with `frac`.
            Default = 1 if `frac` = None.
        frac : float, optional
            Fraction of axis items to return. Cannot be used with `n`.
        replace : bool, default False
            Allow or disallow sampling of the same row more than once.
        weights : str or ndarray-like, optional
            Default 'None' results in equal probability weighting.
            If passed a Series, will align with target object on index. Index
            values in weights not found in sampled object will be ignored and
            index values in sampled object not in weights will be assigned
            weights of zero.
            If called on a DataFrame, will accept the name of a column
            when axis = 0.
            Unless weights are a Series, weights must be same length as axis
            being sampled.
            If weights do not sum to 1, they will be normalized to sum to 1.
            Missing values in the weights column will be treated as zero.
            Infinite values not allowed.
        random_state : int, array-like, BitGenerator, np.random.RandomState, optional
            If int, array-like, or BitGenerator (NumPy>=1.17), seed for
            random number generator
            If np.random.RandomState, use as numpy RandomState object.

            .. versionchanged:: 1.1.0

                array-like and BitGenerator (for NumPy>=1.17) object now passed to
                np.random.RandomState() as seed

        axis : {0 or ‘index’, 1 or ‘columns’, None}, default None
            Axis to sample. Accepts axis number or name. Default is stat axis
            for given data type (0 for Series and DataFrames).

        Returns
        -------
        Series or DataFrame
            A new object of same type as caller containing `n` items randomly
            sampled from the caller object.

        See Also
        --------
        DataFrameGroupBy.sample: Generates random samples from each group of a
            DataFrame object.
        SeriesGroupBy.sample: Generates random samples from each group of a
            Series object.
        numpy.random.choice: Generates a random sample from a given 1-D numpy
            array.

        Notes
        -----
        If `frac` > 1, `replacement` should be set to `True`.

        Examples
        --------
        >>> df = pd.DataFrame({'num_legs': [2, 4, 8, 0],
        ...                    'num_wings': [2, 0, 0, 0],
        ...                    'num_specimen_seen': [10, 2, 1, 8]},
        ...                   index=['falcon', 'dog', 'spider', 'fish'])
        >>> df
                num_legs  num_wings  num_specimen_seen
        falcon         2          2                 10
        dog            4          0                  2
        spider         8          0                  1
        fish           0          0                  8

        Extract 3 random elements from the ``Series`` ``df['num_legs']``:
        Note that we use `random_state` to ensure the reproducibility of
        the examples.

        >>> df['num_legs'].sample(n=3, random_state=1)
        fish      0
        spider    8
        falcon    2
        Name: num_legs, dtype: int64

        A random 50% sample of the ``DataFrame`` with replacement:

        >>> df.sample(frac=0.5, replace=True, random_state=1)
              num_legs  num_wings  num_specimen_seen
        dog          4          0                  2
        fish         0          0                  8

        An upsample sample of the ``DataFrame`` with replacement:
        Note that `replace` parameter has to be `True` for `frac` parameter > 1.

        >>> df.sample(frac=2, replace=True, random_state=1)
                num_legs  num_wings  num_specimen_seen
        dog            4          0                  2
        fish           0          0                  8
        falcon         2          2                 10
        falcon         2          2                 10
        fish           0          0                  8
        dog            4          0                  2
        fish           0          0                  8
        dog            4          0                  2

        Using a DataFrame column as weights. Rows with larger value in the
        `num_specimen_seen` column are more likely to be sampled.

        >>> df.sample(n=2, weights='num_specimen_seen', random_state=1)
                num_legs  num_wings  num_specimen_seen
        falcon         2          2                 10
        fish           0          0                  8
        Nrz+String passed to weights not a valid columnzLStrings can only be passed to weights when sampling from rows on a DataFramez@Strings cannot be passed as weights when sampling from a Series.�float64)r`z5Weights and axis to be sampled must be of same lengthz*weight vector may not include `inf` valuesz.weight vector many not include negative valuesr\z$Invalid weights: weights sum to zerozJReplace has to be set to `True` when upsampling the population `frac` > 1.z$Only integers accepted as `n` valuesz0Please enter a value for `frac` OR `n`, not bothzCA negative number of rows requested. Please provide positive value.)r��replace�p)r�)�_stat_axis_numberr�r�r��random_stater�r@r�rZr�r?r�r�rgrYr�r�rXr�fillna�sumrr�r�choicer�)rjr	�fracr�weightsrr�Zaxis_length�rsr��locsrororp�sample�sfy






 
"

zNDFrame.samplecOstj||f|�|�S)a�
        Apply func(self, \*args, \*\*kwargs).

        Parameters
        ----------
        func : function
            Function to apply to the {klass}.
            ``args``, and ``kwargs`` are passed into ``func``.
            Alternatively a ``(callable, data_keyword)`` tuple where
            ``data_keyword`` is a string indicating the keyword of
            ``callable`` that expects the {klass}.
        args : iterable, optional
            Positional arguments passed into ``func``.
        kwargs : mapping, optional
            A dictionary of keyword arguments passed into ``func``.

        Returns
        -------
        object : the return type of ``func``.

        See Also
        --------
        DataFrame.apply : Apply a function along input axis of DataFrame.
        DataFrame.applymap : Apply a function elementwise on a whole DataFrame.
        Series.map : Apply a mapping correspondence on a
            :class:`~pandas.Series`.

        Notes
        -----
        Use ``.pipe`` when chaining together functions that expect
        Series, DataFrames or GroupBy objects. Instead of writing

        >>> func(g(h(df), arg1=a), arg2=b, arg3=c)  # doctest: +SKIP

        You can write

        >>> (df.pipe(h)
        ...    .pipe(g, arg1=a)
        ...    .pipe(func, arg2=b, arg3=c)
        ... )  # doctest: +SKIP

        If you have a function that takes the data as (say) the second
        argument, pass a tuple indicating which keyword expects the
        data. For example, suppose ``f`` takes its data as ``arg2``:

        >>> (df.pipe(h)
        ...    .pipe(g, arg1=a)
        ...    .pipe((func, 'arg2'), arg1=a, arg3=c)
        ...  )  # doctest: +SKIP
    )r��pipe)rj�funcr�r�rororpr�s4zNDFrame.pipea"
        Aggregate using one or more operations over the specified axis.
        {versionadded}
        Parameters
        ----------
        func : function, str, list or dict
            Function to use for aggregating the data. If a function, must either
            work when passed a {klass} or when passed to {klass}.apply.

            Accepted combinations are:

            - function
            - string function name
            - list of functions and/or function names, e.g. ``[np.sum, 'mean']``
            - dict of axis labels -> functions, function names or list of such.
        {axis}
        *args
            Positional arguments to pass to `func`.
        **kwargs
            Keyword arguments to pass to `func`.

        Returns
        -------
        scalar, Series or DataFrame

            The return can be:

            * scalar : when Series.agg is called with single function
            * Series : when DataFrame.agg is called with a single function
            * DataFrame : when DataFrame.agg is called with several functions

            Return scalar, Series or DataFrame.
        {see_also}
        Notes
        -----
        `agg` is an alias for `aggregate`. Use the alias.

        A passed user-defined-function will be passed a Series for evaluation.
        {examples}�	aggregate)rjrlr�cKsbt|t�r^x|jD]}|j||j|<qWx2|jD](}t|t�sDt�tj||t||d��q2W|S)a�
        Propagate metadata from other to self.

        Parameters
        ----------
        other : the object from which to get the attributes that we are going
            to propagate
        method : str, optional
            A passed method name providing context on where ``__finalize__``
            was called.

            .. warning:

               The value passed as `method` are not currently considered
               stable across pandas releases.
        N)	r�rrr}rzr�r�rr�r�)rjrrlr�r�rororprh�s
zNDFrame.__finalize__)r�cCsN||jks||jks||jkr*tj||�S|jj|�r>||Stj||�SdS)z�
        After regular attribute access, try looking up the name
        This allows simpler access to columns for interactive use.
        N)�_internal_names_setrz�
_accessorsr�__getattribute__r�Z$_can_hold_identifiers_and_holds_name)rjr�rororp�__getattr__s


zNDFrame.__getattr__)r�r�cCs�ytj||�tj|||�Stk
r.YnX||jkrJtj|||�n�||jkrdtj|||�n�yJt||�}t|t�r�tj|||�n"||j	kr�|||<ntj|||�WnFtt
fk
r�t|t�r�t|�r�t
jddd�tj|||�YnXdS)z�
        After regular attribute access, try setting the name
        This allows simpler access to columns for interactive use.
        z�Pandas doesn't allow columns to be created via a new attribute name - see https://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-accessr�)r�N)rrr��AttributeErrorrrzr�r�rIr�rbr?r7r�r�)rjr�r��existingrororpr�s,	





zNDFrame.__setattr__cs0dd�|jjdd�dd�D�}t�j�j|�S)z�
        add the string-like attributes from the info_axis.
        If info_axis is a MultiIndex, it's first level values are used.
        cSs"h|]}t|t�r|j�r|�qSro)r�r��isidentifier)r��crororp�	<setcomp>Esz)NDFrame._dir_additions.<locals>.<setcomp>r)r�N�d)r��unique�super�_dir_additions�union)rjZ	additions)�	__class__rorpr'@szNDFrame._dir_additionscCs.t|jj�}|�}t|jj�|kr*|j�|S)z^
        Consolidate _mgr -- if the blocks have changed, then clear the
        cache
        )r�rsr�r�)rjr�Z
blocks_beforernrororp�_protect_consolidateOs
zNDFrame._protect_consolidatecs�fdd�}�j|�dS)z)Consolidate data in place and return Nonecs�jj��_dS)N)rs�consolidatero)rjrorpr�]sz'NDFrame._consolidate_inplace.<locals>.fN)r*)rjr�ro)rjrpr�ZszNDFrame._consolidate_inplace)rmcsBt|d�}|r�j�n&�fdd�}�j|�}�j|�j��SdS)ae
        Compute NDFrame with "consolidated" internals (data of each dtype
        grouped together in a single ndarray).

        Parameters
        ----------
        inplace : bool, default False
            If False return new object, otherwise modify existing object.

        Returns
        -------
        consolidated : same type as caller
        rmcs
�jj�S)N)rsr+ro)rjrorp�<lambda>tsz&NDFrame._consolidate.<locals>.<lambda>N)r*r�r*r�rh)rjrmr�Z	cons_dataro)rjrp�_consolidatebs


zNDFrame._consolidatecs�fdd�}�j|�S)Ncs�jjS)N)rsZ
is_mixed_typero)rjrorpr,zsz(NDFrame._is_mixed_type.<locals>.<lambda>)r*)rjr�ro)rjrpr�xszNDFrame._is_mixed_typecCs0|jr,|jjs,t|�r$tj|�r$dStd��dS)zA check whether we allow in-place setting with this type of value TzHCannot do inplace boolean setting on mixed-types with a non np.nan value)r�rsZis_numeric_mixed_typer6r��isnanrb)rjr�rororp�_check_inplace_setting}szNDFrame._check_inplace_settingcCs|j|jj��j|�S)N)r�rsZget_numeric_datarh)rjrororp�_get_numeric_data�szNDFrame._get_numeric_datacCs|j|jj��j|�S)N)r�rsZ
get_bool_datarh)rjrororp�_get_bool_data�szNDFrame._get_bool_datacCs|j�|jj|jd�S)a�	
        Return a Numpy representation of the DataFrame.

        .. warning::

           We recommend using :meth:`DataFrame.to_numpy` instead.

        Only the values in the DataFrame will be returned, the axes labels
        will be removed.

        Returns
        -------
        numpy.ndarray
            The values of the DataFrame.

        See Also
        --------
        DataFrame.to_numpy : Recommended alternative to this method.
        DataFrame.index : Retrieve the index labels.
        DataFrame.columns : Retrieving the column names.

        Notes
        -----
        The dtype will be a lower-common-denominator dtype (implicit
        upcasting); that is to say if the dtypes (even of numeric types)
        are mixed, the one that accommodates all will be chosen. Use this
        with care if you are not dealing with the blocks.

        e.g. If the dtypes are float16 and float32, dtype will be upcast to
        float32.  If dtypes are int32 and uint8, dtype will be upcast to
        int32. By :func:`numpy.find_common_type` convention, mixing int64
        and uint64 will result in a float64 dtype.

        Examples
        --------
        A DataFrame where all columns are the same type (e.g., int64) results
        in an array of the same type.

        >>> df = pd.DataFrame({'age':    [ 3,  29],
        ...                    'height': [94, 170],
        ...                    'weight': [31, 115]})
        >>> df
           age  height  weight
        0    3      94      31
        1   29     170     115
        >>> df.dtypes
        age       int64
        height    int64
        weight    int64
        dtype: object
        >>> df.values
        array([[  3,  94,  31],
               [ 29, 170, 115]])

        A DataFrame with mixed type columns(e.g., str/object, int64, float32)
        results in an ndarray of the broadest type that accommodates these
        mixed types (e.g., object).

        >>> df2 = pd.DataFrame([('parrot',   24.0, 'second'),
        ...                     ('lion',     80.5, 1),
        ...                     ('monkey', np.nan, None)],
        ...                   columns=('name', 'max_speed', 'rank'))
        >>> df2.dtypes
        name          object
        max_speed    float64
        rank          object
        dtype: object
        >>> df2.values
        array([['parrot', 24.0, 'second'],
               ['lion', 80.5, 1],
               ['monkey', nan, None]], dtype=object)
        )Z	transpose)r�rsZas_arrayr�)rjrororprf�sJzNDFrame.valuescCs|jS)zinternal implementation)rf)rjrororpr�szNDFrame._valuescCs|jj�}|j||jtjd�S)aJ
        Return the dtypes in the DataFrame.

        This returns a Series with the data type of each column.
        The result's index is the original DataFrame's columns. Columns
        with mixed types are stored with the ``object`` dtype. See
        :ref:`the User Guide <basics.dtypes>` for more.

        Returns
        -------
        pandas.Series
            The data type of each column.

        Examples
        --------
        >>> df = pd.DataFrame({'float': [1.0],
        ...                    'int': [1],
        ...                    'datetime': [pd.Timestamp('20180310')],
        ...                    'string': ['foo']})
        >>> df.dtypes
        float              float64
        int                  int64
        datetime    datetime64[ns]
        string              object
        dtype: object
        )r_r`)rsZ
get_dtypesr�r�r�Zobject_)rjr|rororp�dtypes�s
zNDFrame.dtypes)recs �fdd��jj|d�j�D�S)z~
        Return a dict of dtype -> Constructor Types that
        each is a homogeneous dtype.

        Internal ONLY
        cs"i|]\}}�j|�j��|�qSro)r�rh)r�r�r�)rjrorpr�sz.NDFrame._to_dict_of_blocks.<locals>.<dictcomp>)re)rsZto_dictr�)rjrero)rjrp�_to_dict_of_blockss
zNDFrame._to_dict_of_blocks)rjrer�r�c
sDt��r��jdkrHt��dks(�j�kr0td����j}�j|�|�Sx �j�D]}|�krRtd��qRWg}x��j�D]B\}}|�kr�|j|j�|�|d��qx|j�r�|j	�n|�qxWnZt
��r�jdkr���fdd�tt�j��D�}n&�j
j��|d�}�j|�j�dd�S|�s(�j	�Stj|dd	d
�}	�j|	_|	S)aF

        Cast a pandas object to a specified dtype ``dtype``.

        Parameters
        ----------
        dtype : data type, or dict of column name -> data type
            Use a numpy.dtype or Python type to cast entire pandas object to
            the same type. Alternatively, use {col: dtype, ...}, where col is a
            column label and dtype is a numpy.dtype or Python type to cast one
            or more of the DataFrame's columns to column-specific types.
        copy : bool, default True
            Return a copy when ``copy=True`` (be very careful setting
            ``copy=False`` as changes to values then may propagate to other
            pandas objects).
        errors : {'raise', 'ignore'}, default 'raise'
            Control raising of exceptions on invalid data for provided dtype.

            - ``raise`` : allow exceptions to be raised
            - ``ignore`` : suppress exceptions. On error return original object.

        Returns
        -------
        casted : same type as caller

        See Also
        --------
        to_datetime : Convert argument to datetime.
        to_timedelta : Convert argument to timedelta.
        to_numeric : Convert argument to a numeric type.
        numpy.ndarray.astype : Cast a numpy array to a specified type.

        Examples
        --------
        Create a DataFrame:

        >>> d = {'col1': [1, 2], 'col2': [3, 4]}
        >>> df = pd.DataFrame(data=d)
        >>> df.dtypes
        col1    int64
        col2    int64
        dtype: object

        Cast all columns to int32:

        >>> df.astype('int32').dtypes
        col1    int32
        col2    int32
        dtype: object

        Cast col1 to int32 using a dictionary:

        >>> df.astype({'col1': 'int32'}).dtypes
        col1    int32
        col2    int64
        dtype: object

        Create a series:

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

        Convert to categorical type:

        >>> ser.astype('category')
        0    1
        1    2
        dtype: category
        Categories (2, int64): [1, 2]

        Convert to ordered categorical type with custom ordering:

        >>> cat_dtype = pd.api.types.CategoricalDtype(
        ...     categories=[2, 1], ordered=True)
        >>> ser.astype(cat_dtype)
        0    1
        1    2
        dtype: category
        Categories (2, int64): [2 < 1]

        Note that using ``copy=False`` and changing data on a new
        pandas object may propagate changes:

        >>> s1 = pd.Series([1, 2])
        >>> s2 = s1.astype('int64', copy=False)
        >>> s2[0] = 10
        >>> s1  # note that s1[0] has changed too
        0    10
        1     2
        dtype: int64

        Create a series of dates:

        >>> ser_date = pd.Series(pd.date_range('20200101', periods=3))
        >>> ser_date
        0   2020-01-01
        1   2020-01-02
        2   2020-01-03
        dtype: datetime64[ns]

        Datetimes are localized to UTC first before
        converting to the specified timezone:

        >>> ser_date.astype('datetime64[ns, US/Eastern]')
        0   2019-12-31 19:00:00-05:00
        1   2020-01-01 19:00:00-05:00
        2   2020-01-02 19:00:00-05:00
        dtype: datetime64[ns, US/Eastern]
        r\zFOnly the Series name can be used for the key in Series dtype mappings.zHOnly a column name can be used for the key in a dtype mappings argument.)r`rer�cs(g|] }�jdd�|fj��d��qS)N)re)r�r�)r�r�)rer`rjrorpr��sz"NDFrame.astype.<locals>.<listcomp>r�)rlF)r�re)r4rar�r�r�r�rr�r�rer5r�r�rsr�rhrg�concat)
rjr`rer�Znew_type�col_name�resultsr�rrnro)rer`rjrpr�s6v


zNDFrame.astype)rjr�r�cCs*|jj|d�}|j�|j|�j|dd�S)a2
        Make a copy of this object's indices and data.

        When ``deep=True`` (default), a new object will be created with a
        copy of the calling object's data and indices. Modifications to
        the data or indices of the copy will not be reflected in the
        original object (see notes below).

        When ``deep=False``, a new object will be created without copying
        the calling object's data or index (only references to the data
        and index are copied). Any changes to the data of the original
        will be reflected in the shallow copy (and vice versa).

        Parameters
        ----------
        deep : bool, default True
            Make a deep copy, including a copy of the data and the indices.
            With ``deep=False`` neither the indices nor the data are copied.

        Returns
        -------
        copy : Series or DataFrame
            Object type matches caller.

        Notes
        -----
        When ``deep=True``, data is copied but actual Python objects
        will not be copied recursively, only the reference to the object.
        This is in contrast to `copy.deepcopy` in the Standard Library,
        which recursively copies object data (see examples below).

        While ``Index`` objects are copied when ``deep=True``, the underlying
        numpy array is not copied for performance reasons. Since ``Index`` is
        immutable, the underlying data can be safely shared and a copy
        is not needed.

        Examples
        --------
        >>> s = pd.Series([1, 2], index=["a", "b"])
        >>> s
        a    1
        b    2
        dtype: int64

        >>> s_copy = s.copy()
        >>> s_copy
        a    1
        b    2
        dtype: int64

        **Shallow copy versus default (deep) copy:**

        >>> s = pd.Series([1, 2], index=["a", "b"])
        >>> deep = s.copy()
        >>> shallow = s.copy(deep=False)

        Shallow copy shares data and index with original.

        >>> s is shallow
        False
        >>> s.values is shallow.values and s.index is shallow.index
        True

        Deep copy has own copy of data and index.

        >>> s is deep
        False
        >>> s.values is deep.values or s.index is deep.index
        False

        Updates to the data shared by shallow copy and original is reflected
        in both; deep copy remains unchanged.

        >>> s[0] = 3
        >>> shallow[1] = 4
        >>> s
        a    3
        b    4
        dtype: int64
        >>> shallow
        a    3
        b    4
        dtype: int64
        >>> deep
        a    1
        b    2
        dtype: int64

        Note that when copying an object containing Python objects, a deep copy
        will copy the data, but will not do so recursively. Updating a nested
        data object will be reflected in the deep copy.

        >>> s = pd.Series([[1, 2], [3, 4]])
        >>> deep = s.copy()
        >>> s[0][0] = 10
        >>> s
        0    [10, 2]
        1     [3, 4]
        dtype: object
        >>> deep
        0    [10, 2]
        1     [3, 4]
        dtype: object
        )r�re)rl)rsrer�r�rh)rjr�r|rororpre�sizNDFrame.copycCs|j|d�S)N)r�)re)rjr�rororp�__copy__%szNDFrame.__copy__cCs|jdd�S)zq
        Parameters
        ----------
        memo, default None
            Standard signature. Unused
        T)r�)re)rj�memorororp�__deepcopy__(szNDFrame.__deepcopy__)rj�datetime�numericr�coercer�cCsJt|d�t|d�t|d�t|d�|j|jj||||dd��j|�S)a�
        Attempt to infer better dtype for object columns

        Parameters
        ----------
        datetime : bool, default False
            If True, convert to date where possible.
        numeric : bool, default False
            If True, attempt to convert to numbers (including strings), with
            unconvertible values becoming NaN.
        timedelta : bool, default False
            If True, convert to timedelta where possible.
        coerce : bool, default False
            If True, force conversion with unconvertible values converted to
            nulls (NaN or NaT).

        Returns
        -------
        converted : same as input object
        r:r;rr<T)r:r;rr<re)r*r�rs�convertrh)rjr:r;rr<rororp�_convert1s




zNDFrame._convertcCs&|j|jjdddddd��j|dd�S)a�
        Attempt to infer better dtypes for object columns.

        Attempts soft conversion of object-dtyped
        columns, leaving non-object and unconvertible
        columns unchanged. The inference rules are the
        same as during normal Series/DataFrame construction.

        Returns
        -------
        converted : same type as input object

        See Also
        --------
        to_datetime : Convert argument to datetime.
        to_timedelta : Convert argument to timedelta.
        to_numeric : Convert argument to numeric type.
        convert_dtypes : Convert argument to best possible dtype.

        Examples
        --------
        >>> df = pd.DataFrame({"A": ["a", 1, 2, 3]})
        >>> df = df.iloc[1:]
        >>> df
           A
        1  1
        2  2
        3  3

        >>> df.dtypes
        A    object
        dtype: object

        >>> df.infer_objects().dtypes
        A    int64
        dtype: object
        TF)r:r;rr<re�
infer_objects)rl)r�rsr=rh)rjrororpr?Zs)zNDFrame.infer_objects)rjr?�convert_string�convert_integer�convert_booleanr�csN|jdkr|j�����S����fdd�|j�D�}tj|ddd�}|SdS)aL
        Convert columns to best possible dtypes using dtypes supporting ``pd.NA``.

        .. versionadded:: 1.0.0

        Parameters
        ----------
        infer_objects : bool, default True
            Whether object dtypes should be converted to the best possible types.
        convert_string : bool, default True
            Whether object dtypes should be converted to ``StringDtype()``.
        convert_integer : bool, default True
            Whether, if possible, conversion can be done to integer extension types.
        convert_boolean : bool, defaults True
            Whether object dtypes should be converted to ``BooleanDtypes()``.

        Returns
        -------
        Series or DataFrame
            Copy of input object with new dtype.

        See Also
        --------
        infer_objects : Infer dtypes of objects.
        to_datetime : Convert argument to datetime.
        to_timedelta : Convert argument to timedelta.
        to_numeric : Convert argument to a numeric type.

        Notes
        -----
        By default, ``convert_dtypes`` will attempt to convert a Series (or each
        Series in a DataFrame) to dtypes that support ``pd.NA``. By using the options
        ``convert_string``, ``convert_integer``, and ``convert_boolean``, it is
        possible to turn off individual conversions to ``StringDtype``, the integer
        extension types or ``BooleanDtype``, respectively.

        For object-dtyped columns, if ``infer_objects`` is ``True``, use the inference
        rules as during normal Series/DataFrame construction.  Then, if possible,
        convert to ``StringDtype``, ``BooleanDtype`` or an appropriate integer extension
        type, otherwise leave as ``object``.

        If the dtype is integer, convert to an appropriate integer extension type.

        If the dtype is numeric, and consists of all integers, convert to an
        appropriate integer extension type.

        In the future, as new dtypes are added that support ``pd.NA``, the results
        of this method will change to support those new dtypes.

        Examples
        --------
        >>> df = pd.DataFrame(
        ...     {
        ...         "a": pd.Series([1, 2, 3], dtype=np.dtype("int32")),
        ...         "b": pd.Series(["x", "y", "z"], dtype=np.dtype("O")),
        ...         "c": pd.Series([True, False, np.nan], dtype=np.dtype("O")),
        ...         "d": pd.Series(["h", "i", np.nan], dtype=np.dtype("O")),
        ...         "e": pd.Series([10, np.nan, 20], dtype=np.dtype("float")),
        ...         "f": pd.Series([np.nan, 100.5, 200], dtype=np.dtype("float")),
        ...     }
        ... )

        Start with a DataFrame with default dtypes.

        >>> df
           a  b      c    d     e      f
        0  1  x   True    h  10.0    NaN
        1  2  y  False    i   NaN  100.5
        2  3  z    NaN  NaN  20.0  200.0

        >>> df.dtypes
        a      int32
        b     object
        c     object
        d     object
        e    float64
        f    float64
        dtype: object

        Convert the DataFrame to use best possible dtypes.

        >>> dfn = df.convert_dtypes()
        >>> dfn
           a  b      c     d     e      f
        0  1  x   True     h    10    NaN
        1  2  y  False     i  <NA>  100.5
        2  3  z   <NA>  <NA>    20  200.0

        >>> dfn.dtypes
        a      Int32
        b     string
        c    boolean
        d     string
        e      Int64
        f    float64
        dtype: object

        Start with a Series of strings and missing data represented by ``np.nan``.

        >>> s = pd.Series(["a", "b", np.nan])
        >>> s
        0      a
        1      b
        2    NaN
        dtype: object

        Obtain a Series with dtype ``StringDtype``.

        >>> s.convert_dtypes()
        0       a
        1       b
        2    <NA>
        dtype: string
        r\cs g|]\}}|j������qSro)�_convert_dtypes)r�r5r�)rBrAr@r?rorpr�sz*NDFrame.convert_dtypes.<locals>.<listcomp>F)r�reN)rarCr�rgr4)rjr?r@rArBr6rnro)rBrAr@r?rp�convert_dtypes�sy
zNDFrame.convert_dtypes)rjrmr�cCst|d�}t||�\}}|j�|dkr,d}|j|�}|dkr�|jrx|dkrx|rVt��|jj||d�j}|jj	�|_|S|jj
||||d|d�}�nT|jdk�rt|t
tf�r�t|td�}|j|jd	d
�}|j}n t|�s�ntdt|�j�d���|jj||||d
�}n�t|t
tf��r�|dk�r*td��|�r4|n|j�}x>|j�D]2\}	}
|	|k�r\�qF||	}|j|
|d|d��qFW|�s�|SdSt|��s�|jj||||d
�}n>t|t��r�|jdk�r�|j|j�|�j}ntdt|�����|j|�}|�r|j |�S|j!|dd�SdS)a�

        Fill NA/NaN values using the specified method.

        Parameters
        ----------
        value : scalar, dict, Series, or DataFrame
            Value to use to fill holes (e.g. 0), alternately a
            dict/Series/DataFrame of values specifying which value to use for
            each index (for a Series) or column (for a DataFrame).  Values not
            in the dict/Series/DataFrame will not be filled. This value cannot
            be a list.
        method : {{'backfill', 'bfill', 'pad', 'ffill', None}}, default None
            Method to use for filling holes in reindexed Series
            pad / ffill: propagate last valid observation forward to next valid
            backfill / bfill: use next valid observation to fill gap.
        axis : {axes_single_arg}
            Axis along which to fill missing values.
        inplace : bool, default False
            If True, fill in-place. Note: this will modify any
            other views on this object (e.g., a no-copy slice for a column in a
            DataFrame).
        limit : int, default None
            If method is specified, this is the maximum number of consecutive
            NaN values to forward/backward fill. In other words, if there is
            a gap with more than this number of consecutive NaNs, it will only
            be partially filled. If method is not specified, this is the
            maximum number of entries along the entire axis where NaNs will be
            filled. Must be greater than 0 if not None.
        downcast : dict, default is None
            A dict of item->dtype of what to downcast if possible,
            or the string 'infer' which will try to downcast to an appropriate
            equal type (e.g. float64 to int64 if possible).

        Returns
        -------
        {klass} or None
            Object with missing values filled or None if ``inplace=True``.

        See Also
        --------
        interpolate : Fill NaN values using interpolation.
        reindex : Conform object to new index.
        asfreq : Convert TimeSeries to specified frequency.

        Examples
        --------
        >>> df = pd.DataFrame([[np.nan, 2, np.nan, 0],
        ...                    [3, 4, np.nan, 1],
        ...                    [np.nan, np.nan, np.nan, 5],
        ...                    [np.nan, 3, np.nan, 4]],
        ...                   columns=list('ABCD'))
        >>> df
             A    B   C  D
        0  NaN  2.0 NaN  0
        1  3.0  4.0 NaN  1
        2  NaN  NaN NaN  5
        3  NaN  3.0 NaN  4

        Replace all NaN elements with 0s.

        >>> df.fillna(0)
            A   B   C   D
        0   0.0 2.0 0.0 0
        1   3.0 4.0 0.0 1
        2   0.0 0.0 0.0 5
        3   0.0 3.0 0.0 4

        We can also propagate non-null values forward or backward.

        >>> df.fillna(method='ffill')
            A   B   C   D
        0   NaN 2.0 NaN 0
        1   3.0 4.0 NaN 1
        2   3.0 4.0 NaN 5
        3   3.0 3.0 NaN 4

        Replace all NaN elements in column 'A', 'B', 'C', and 'D', with 0, 1,
        2, and 3 respectively.

        >>> values = {{'A': 0, 'B': 1, 'C': 2, 'D': 3}}
        >>> df.fillna(value=values)
            A   B   C   D
        0   0.0 2.0 2.0 0
        1   3.0 4.0 2.0 1
        2   0.0 1.0 2.0 5
        3   0.0 3.0 2.0 4

        Only replace the first NaN element.

        >>> df.fillna(value=values, limit=1)
            A   B   C   D
        0   0.0 2.0 2.0 0
        1   3.0 4.0 NaN 1
        2   NaN 1.0 NaN 5
        3   NaN 3.0 NaN 4
        rmNrr\)rlr]T)rlr�r]rmr<�downcast)Zdtype_if_emptyF)rezF"value" parameter must be a scalar, dict or Series, but you passed a "r�)r�r]rmrEz9Currently only can fill with dict/Series column by column)r]rmrEr�zinvalid fill value with a r)rl)"r*r+r�r�r�r��TrrsrE�interpolaterar�r�r@rHrr�r_rr7rbrcrdrer�r?�whererCr�r�r�rirh)rjr�rlr�rmr]rErnrr�r�r�rororprsjj







zNDFrame.fillnacCs|jd||||d�S)z�
        Synonym for :meth:`DataFrame.fillna` with ``method='ffill'``.

        Returns
        -------
        {klass} or None
            Object with missing values filled or None if ``inplace=True``.
        �ffill)rlr�rmr]rE)r)rjr�rmr]rErororprI�sz
NDFrame.ffillcCs|jd||||d�S)z�
        Synonym for :meth:`DataFrame.fillna` with ``method='bfill'``.

        Returns
        -------
        {klass} or None
            Object with missing values filled or None if ``inplace=True``.
        �bfill)rlr�rmr]rE)r)rjr�rmr]rErororprJ�sz
NDFrame.bfill�padcs�t��pt��pt��s0tdtt��j�����t|d�}t|�rT�dk	rTt	d���j
��dk�r�t��r�t|�r��g�t�t
tf�r�t�t�r��jt�|||fd�St��|||�St��s�t|�s�td��|�d}t�j��}|r�t|�nggf\}}	dd	�|	D�}
t|
��r�t|
��s,td
��i}i}xH|D]@\}
}tt|j����pZggf\}}	t|�||
<t|	�||
<�q:W||��n
||	���j��|||d�S�j�s��St���r>t���r���fdd
��j�D�}�j|||�St���s2�jdk�rtd���fdd
��j�D�}�j|||�Std���nFt���r�t���r�t��t��k�r�tdt���dt���d����j
��jj��||d�}n�jj��||d�}nΈdk�r
t|��p�t|��p�t|��s�tdtt|�j������j|�||dd�St���rL�jdk�r(td���fdd
��j�D�}�j|||�St���sl�jj��||d�}ntdtt��j������j|�}|�r��j |�S|j!�dd�SdS)a�*
        Replace values given in `to_replace` with `value`.

        Values of the {klass} are replaced with other values dynamically.
        This differs from updating with ``.loc`` or ``.iloc``, which require
        you to specify a location to update with some value.

        Parameters
        ----------
        to_replace : str, regex, list, dict, Series, int, float, or None
            How to find the values that will be replaced.

            * numeric, str or regex:

                - numeric: numeric values equal to `to_replace` will be
                  replaced with `value`
                - str: string exactly matching `to_replace` will be replaced
                  with `value`
                - regex: regexs matching `to_replace` will be replaced with
                  `value`

            * list of str, regex, or numeric:

                - First, if `to_replace` and `value` are both lists, they
                  **must** be the same length.
                - Second, if ``regex=True`` then all of the strings in **both**
                  lists will be interpreted as regexs otherwise they will match
                  directly. This doesn't matter much for `value` since there
                  are only a few possible substitution regexes you can use.
                - str, regex and numeric rules apply as above.

            * dict:

                - Dicts can be used to specify different replacement values
                  for different existing values. For example,
                  ``{{'a': 'b', 'y': 'z'}}`` replaces the value 'a' with 'b' and
                  'y' with 'z'. To use a dict in this way the `value`
                  parameter should be `None`.
                - For a DataFrame a dict can specify that different values
                  should be replaced in different columns. For example,
                  ``{{'a': 1, 'b': 'z'}}`` looks for the value 1 in column 'a'
                  and the value 'z' in column 'b' and replaces these values
                  with whatever is specified in `value`. The `value` parameter
                  should not be ``None`` in this case. You can treat this as a
                  special case of passing two lists except that you are
                  specifying the column to search in.
                - For a DataFrame nested dictionaries, e.g.,
                  ``{{'a': {{'b': np.nan}}}}``, are read as follows: look in column
                  'a' for the value 'b' and replace it with NaN. The `value`
                  parameter should be ``None`` to use a nested dict in this
                  way. You can nest regular expressions as well. Note that
                  column names (the top-level dictionary keys in a nested
                  dictionary) **cannot** be regular expressions.

            * None:

                - This means that the `regex` argument must be a string,
                  compiled regular expression, or list, dict, ndarray or
                  Series of such elements. If `value` is also ``None`` then
                  this **must** be a nested dictionary or Series.

            See the examples section for examples of each of these.
        value : scalar, dict, list, str, regex, default None
            Value to replace any values matching `to_replace` with.
            For a DataFrame a dict of values can be used to specify which
            value to use for each column (columns not in the dict will not be
            filled). Regular expressions, strings and lists or dicts of such
            objects are also allowed.
        inplace : bool, default False
            If True, in place. Note: this will modify any
            other views on this object (e.g. a column from a DataFrame).
            Returns the caller if this is True.
        limit : int, default None
            Maximum size gap to forward or backward fill.
        regex : bool or same types as `to_replace`, default False
            Whether to interpret `to_replace` and/or `value` as regular
            expressions. If this is ``True`` then `to_replace` *must* be a
            string. Alternatively, this could be a regular expression or a
            list, dict, or array of regular expressions in which case
            `to_replace` must be ``None``.
        method : {{'pad', 'ffill', 'bfill', `None`}}
            The method to use when for replacement, when `to_replace` is a
            scalar, list or tuple and `value` is ``None``.

            .. versionchanged:: 0.23.0
                Added to DataFrame.

        Returns
        -------
        {klass}
            Object after replacement.

        Raises
        ------
        AssertionError
            * If `regex` is not a ``bool`` and `to_replace` is not
              ``None``.

        TypeError
            * If `to_replace` is not a scalar, array-like, ``dict``, or ``None``
            * If `to_replace` is a ``dict`` and `value` is not a ``list``,
              ``dict``, ``ndarray``, or ``Series``
            * If `to_replace` is ``None`` and `regex` is not compilable
              into a regular expression or is a list, dict, ndarray, or
              Series.
            * When replacing multiple ``bool`` or ``datetime64`` objects and
              the arguments to `to_replace` does not match the type of the
              value being replaced

        ValueError
            * If a ``list`` or an ``ndarray`` is passed to `to_replace` and
              `value` but they are not the same length.

        See Also
        --------
        {klass}.fillna : Fill NA values.
        {klass}.where : Replace values based on boolean condition.
        Series.str.replace : Simple string replacement.

        Notes
        -----
        * Regex substitution is performed under the hood with ``re.sub``. The
          rules for substitution for ``re.sub`` are the same.
        * Regular expressions will only substitute on strings, meaning you
          cannot provide, for example, a regular expression matching floating
          point numbers and expect the columns in your frame that have a
          numeric dtype to be matched. However, if those floating point
          numbers *are* strings, then you can do this.
        * This method has *a lot* of options. You are encouraged to experiment
          and play with this method to gain intuition about how it works.
        * When dict is used as the `to_replace` value, it is like
          key(s) in the dict are the to_replace part and
          value(s) in the dict are the value parameter.

        Examples
        --------

        **Scalar `to_replace` and `value`**

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

        >>> df = pd.DataFrame({{'A': [0, 1, 2, 3, 4],
        ...                    'B': [5, 6, 7, 8, 9],
        ...                    'C': ['a', 'b', 'c', 'd', 'e']}})
        >>> df.replace(0, 5)
           A  B  C
        0  5  5  a
        1  1  6  b
        2  2  7  c
        3  3  8  d
        4  4  9  e

        **List-like `to_replace`**

        >>> df.replace([0, 1, 2, 3], 4)
           A  B  C
        0  4  5  a
        1  4  6  b
        2  4  7  c
        3  4  8  d
        4  4  9  e

        >>> df.replace([0, 1, 2, 3], [4, 3, 2, 1])
           A  B  C
        0  4  5  a
        1  3  6  b
        2  2  7  c
        3  1  8  d
        4  4  9  e

        >>> s.replace([1, 2], method='bfill')
        0    0
        1    3
        2    3
        3    3
        4    4
        dtype: int64

        **dict-like `to_replace`**

        >>> df.replace({{0: 10, 1: 100}})
             A  B  C
        0   10  5  a
        1  100  6  b
        2    2  7  c
        3    3  8  d
        4    4  9  e

        >>> df.replace({{'A': 0, 'B': 5}}, 100)
             A    B  C
        0  100  100  a
        1    1    6  b
        2    2    7  c
        3    3    8  d
        4    4    9  e

        >>> df.replace({{'A': {{0: 100, 4: 400}}}})
             A  B  C
        0  100  5  a
        1    1  6  b
        2    2  7  c
        3    3  8  d
        4  400  9  e

        **Regular expression `to_replace`**

        >>> df = pd.DataFrame({{'A': ['bat', 'foo', 'bait'],
        ...                    'B': ['abc', 'bar', 'xyz']}})
        >>> df.replace(to_replace=r'^ba.$', value='new', regex=True)
              A    B
        0   new  abc
        1   foo  new
        2  bait  xyz

        >>> df.replace({{'A': r'^ba.$'}}, {{'A': 'new'}}, regex=True)
              A    B
        0   new  abc
        1   foo  bar
        2  bait  xyz

        >>> df.replace(regex=r'^ba.$', value='new')
              A    B
        0   new  abc
        1   foo  new
        2  bait  xyz

        >>> df.replace(regex={{r'^ba.$': 'new', 'foo': 'xyz'}})
              A    B
        0   new  abc
        1   xyz  new
        2  bait  xyz

        >>> df.replace(regex=[r'^ba.$', 'foo'], value='new')
              A    B
        0   new  abc
        1   new  new
        2  bait  xyz

        Note that when replacing multiple ``bool`` or ``datetime64`` objects,
        the data types in the `to_replace` parameter must match the data
        type of the value being replaced:

        >>> df = pd.DataFrame({{'A': [True, False, True],
        ...                    'B': [False, True, False]}})
        >>> df.replace({{'a string': 'new value', True: False}})  # raises
        Traceback (most recent call last):
            ...
        TypeError: Cannot compare types 'ndarray(dtype=bool)' and 'str'

        This raises a ``TypeError`` because one of the ``dict`` keys is not of
        the correct type for replacement.

        Compare the behavior of ``s.replace({{'a': None}})`` and
        ``s.replace('a', None)`` to understand the peculiarities
        of the `to_replace` parameter:

        >>> s = pd.Series([10, 'a', 'a', 'b', 'a'])

        When one uses a dict as the `to_replace` value, it is like the
        value(s) in the dict are equal to the `value` parameter.
        ``s.replace({{'a': None}})`` is equivalent to
        ``s.replace(to_replace={{'a': None}}, value=None, method=None)``:

        >>> s.replace({{'a': None}})
        0      10
        1    None
        2    None
        3       b
        4    None
        dtype: object

        When ``value=None`` and `to_replace` is a scalar, list or
        tuple, `replace` uses the method parameter (default 'pad') to do the
        replacement. So this is why the 'a' values are being replaced by 10
        in rows 1 and 2 and 'b' in row 4 in this case.
        The command ``s.replace('a', None)`` is actually equivalent to
        ``s.replace(to_replace='a', value=None, method='pad')``:

        >>> s.replace('a', None)
        0    10
        1    10
        2    10
        3     b
        4     b
        dtype: object
    zYExpecting 'to_replace' to be either a scalar, array-like, dict or None, got invalid type rmNz4'to_replace' must be 'None' if 'regex' is not a bool)r�zfIf "to_replace" and "value" are both None and "to_replace" is not a list, then regex must be a mappingTcSsg|]}t|��qSro)r4)r�r�rororpr�Tsz#NDFrame.replace.<locals>.<listcomp>zSIf a nested mapping is passed, all values of the top level mapping must be mappings)rmr]rcs2i|]*}|�j�kr|�kr�|�|f|�qSro)r)r�r�)rjrkr�rorpr�wsz#NDFrame.replace.<locals>.<dictcomp>r\zASeries.replace cannot use dict-like to_replace and non-None valuecsi|]\}}|�f|�qSroro)r�r�Zto_rep)r�rorpr��sz.value argument must be scalar, dict, or Seriesz2Replacement lists must match in length. Expecting z got r%)Zsrc_listZ	dest_listrmr)rkr�rmrz|'regex' must be a string or a compiled regular expression or a list or dict of strings or regular expressions, you passed a z<Series.replace cannot use dict-value and non-None to_replacecsi|]\}}�|f|�qSroro)r�r��val)rkrorpr��szInvalid "to_replace" type: r)rl)"r<r;r7rbr-rcrdr*r0r�r�r4r�r�r�r?rrqr��ziprrrr�rZ_replace_columnwiserar�r�rsZreplace_listr�rirh)rjrkr�rmr]rrlr�rrfZare_mappingsZto_rep_dictZ
value_dictr�r�r�rrnro)rjrkr�rpr�s�2




















zNDFrame.replace�linear)	rjrlr�r]rm�limit_direction�
limit_arearEr�cKs�t|d�}|j|�}ddddg}	|dko.||	k}
|
r:|jn|}|jrL|j�S||	krZ|j}t|jt�rv|dkrvt	d��|d	kr�|dkr�d
nd}n@|dkr�|dkr�t	d|�d
���|dkr�|d
kr�t	d|�d
���|j
dko�tj|j
tjt�k��r�td��|dk�rtjt|j��}nV|j}ddddh}
t|j��pHt|j��pHt|j�}||
k�rl|�rlt	d|�d���t|�j��r�td��|jjf||||||||d�|��}|j|�}|
�r�|j}|�r�|j|�S|j|dd�Sd	S)a�
        Please note that only ``method='linear'`` is supported for
        DataFrame/Series with a MultiIndex.

        Parameters
        ----------
        method : str, default 'linear'
            Interpolation technique to use. One of:

            * 'linear': Ignore the index and treat the values as equally
              spaced. This is the only method supported on MultiIndexes.
            * 'time': Works on daily and higher resolution data to interpolate
              given length of interval.
            * 'index', 'values': use the actual numerical values of the index.
            * 'pad': Fill in NaNs using existing values.
            * 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', 'spline',
              'barycentric', 'polynomial': Passed to
              `scipy.interpolate.interp1d`. These methods use the numerical
              values of the index.  Both 'polynomial' and 'spline' require that
              you also specify an `order` (int), e.g.
              ``df.interpolate(method='polynomial', order=5)``.
            * 'krogh', 'piecewise_polynomial', 'spline', 'pchip', 'akima',
              'cubicspline': Wrappers around the SciPy interpolation methods of
              similar names. See `Notes`.
            * 'from_derivatives': Refers to
              `scipy.interpolate.BPoly.from_derivatives` which
              replaces 'piecewise_polynomial' interpolation method in
              scipy 0.18.
        axis : {{0 or 'index', 1 or 'columns', None}}, default None
            Axis to interpolate along.
        limit : int, optional
            Maximum number of consecutive NaNs to fill. Must be greater than
            0.
        inplace : bool, default False
            Update the data in place if possible.
        limit_direction : {{'forward', 'backward', 'both'}}, Optional
            Consecutive NaNs will be filled in this direction.

            If limit is specified:
                * If 'method' is 'pad' or 'ffill', 'limit_direction' must be 'forward'.
                * If 'method' is 'backfill' or 'bfill', 'limit_direction' must be
                  'backwards'.

            If 'limit' is not specified:
                * If 'method' is 'backfill' or 'bfill', the default is 'backward'
                * else the default is 'forward'

            .. versionchanged:: 1.1.0
                raises ValueError if `limit_direction` is 'forward' or 'both' and
                    method is 'backfill' or 'bfill'.
                raises ValueError if `limit_direction` is 'backward' or 'both' and
                    method is 'pad' or 'ffill'.

        limit_area : {{`None`, 'inside', 'outside'}}, default None
            If limit is specified, consecutive NaNs will be filled with this
            restriction.

            * ``None``: No fill restriction.
            * 'inside': Only fill NaNs surrounded by valid values
              (interpolate).
            * 'outside': Only fill NaNs outside valid values (extrapolate).

            .. versionadded:: 0.23.0

        downcast : optional, 'infer' or None, defaults to None
            Downcast dtypes if possible.
        **kwargs
            Keyword arguments to pass on to the interpolating function.

        Returns
        -------
        Series or DataFrame
            Returns the same object type as the caller, interpolated at
            some or all ``NaN`` values.

        See Also
        --------
        fillna : Fill missing values using different methods.
        scipy.interpolate.Akima1DInterpolator : Piecewise cubic polynomials
            (Akima interpolator).
        scipy.interpolate.BPoly.from_derivatives : Piecewise polynomial in the
            Bernstein basis.
        scipy.interpolate.interp1d : Interpolate a 1-D function.
        scipy.interpolate.KroghInterpolator : Interpolate polynomial (Krogh
            interpolator).
        scipy.interpolate.PchipInterpolator : PCHIP 1-d monotonic cubic
            interpolation.
        scipy.interpolate.CubicSpline : Cubic spline data interpolator.

        Notes
        -----
        The 'krogh', 'piecewise_polynomial', 'spline', 'pchip' and 'akima'
        methods are wrappers around the respective SciPy implementations of
        similar names. These use the actual numerical values of the index.
        For more information on their behavior, see the
        `SciPy documentation
        <https://docs.scipy.org/doc/scipy/reference/interpolate.html#univariate-interpolation>`__
        and `SciPy tutorial
        <https://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html>`__.

        Examples
        --------
        Filling in ``NaN`` in a :class:`~pandas.Series` via linear
        interpolation.

        >>> s = pd.Series([0, 1, np.nan, 3])
        >>> s
        0    0.0
        1    1.0
        2    NaN
        3    3.0
        dtype: float64
        >>> s.interpolate()
        0    0.0
        1    1.0
        2    2.0
        3    3.0
        dtype: float64

        Filling in ``NaN`` in a Series by padding, but filling at most two
        consecutive ``NaN`` at a time.

        >>> s = pd.Series([np.nan, "single_one", np.nan,
        ...                "fill_two_more", np.nan, np.nan, np.nan,
        ...                4.71, np.nan])
        >>> s
        0              NaN
        1       single_one
        2              NaN
        3    fill_two_more
        4              NaN
        5              NaN
        6              NaN
        7             4.71
        8              NaN
        dtype: object
        >>> s.interpolate(method='pad', limit=2)
        0              NaN
        1       single_one
        2       single_one
        3    fill_two_more
        4    fill_two_more
        5    fill_two_more
        6              NaN
        7             4.71
        8             4.71
        dtype: object

        Filling in ``NaN`` in a Series via polynomial interpolation or splines:
        Both 'polynomial' and 'spline' methods require that you also specify
        an ``order`` (int).

        >>> s = pd.Series([0, 2, np.nan, 8])
        >>> s.interpolate(method='polynomial', order=2)
        0    0.000000
        1    2.000000
        2    4.666667
        3    8.000000
        dtype: float64

        Fill the DataFrame forward (that is, going down) along each column
        using linear interpolation.

        Note how the last entry in column 'a' is interpolated differently,
        because there is no entry after it to use for interpolation.
        Note how the first entry in column 'b' remains ``NaN``, because there
        is no entry before it to use for interpolation.

        >>> df = pd.DataFrame([(0.0, np.nan, -1.0, 1.0),
        ...                    (np.nan, 2.0, np.nan, np.nan),
        ...                    (2.0, 3.0, np.nan, 9.0),
        ...                    (np.nan, 4.0, -4.0, 16.0)],
        ...                   columns=list('abcd'))
        >>> df
             a    b    c     d
        0  0.0  NaN -1.0   1.0
        1  NaN  2.0  NaN   NaN
        2  2.0  3.0  NaN   9.0
        3  NaN  4.0 -4.0  16.0
        >>> df.interpolate(method='linear', limit_direction='forward', axis=0)
             a    b    c     d
        0  0.0  NaN -1.0   1.0
        1  1.0  2.0 -2.0   5.0
        2  2.0  3.0 -3.0   9.0
        3  2.0  4.0 -4.0  16.0

        Using polynomial interpolation.

        >>> df['d'].interpolate(method='polynomial', order=2)
        0     1.0
        1     4.0
        2     9.0
        3    16.0
        Name: d, dtype: float64
        rmrIrJrK�backfillr\rNz@Only `method=linear` interpolation is supported on MultiIndexes.NZbackwardZforwardz0`limit_direction` must be 'forward' for method `�`z1`limit_direction` must be 'backward' for method `r�zvCannot interpolate with all object-dtype columns in the DataFrame. Try setting at least one column to a numeric dtype.r_rfZnearest�timez9Index column must be numeric or datetime type when using z_ method other than linear. Try setting a numeric or datetime index column before interpolating.zkInterpolation with NaNs in the index has not been implemented. Try filling those NaNs before interpolating.)rlr�r_r]rOrPrmrErG)rl)rQrJ)rKrI)rQrJ)r*r�rFr5re�_info_axis_numberr�r_rJr�rar�rr2r`rrb�aranger�r9r2r=rBrr�rsrGr�rirh)rjrlr�r]rmrOrPrEr�Zfillna_methodsZshould_transposer�r_�methodsZis_numeric_or_datetimerrnrororprG�sjO

"



zNDFrame.interpolatecCs�t|t�rt|�}|jjs"td��t|t�}|rB|dk	r^td��n|dkrP|j}t|�s^|g}t|�}|�s|jd}t|jt	�r�t
||jjd�}||kr�|s�|j|j|t
jd�St
jS|�r|jj|dd�}|dkr�|d	8}|j}x$|dk�rt||��r|d	8}q�W||St|t��s6|�r,t|�nt|g�}|�rD|j�n||j�jd	�}|j��r�|�rz|jt
j||jd
�S|�r�|jt
j||jd�S|jt
j|j|dd
�S|jj||j�}	|	dk}
|j|	�}||_t
j|j|
<|�r�|S|jd
S)a�
        Return the last row(s) without any NaNs before `where`.

        The last row (for each element in `where`, if list) without any
        NaN is taken.
        In case of a :class:`~pandas.DataFrame`, the last row without NaN
        considering only the subset of columns (if not `None`)

        If there is no good value, NaN is returned for a Series or
        a Series of NaN values for a DataFrame

        Parameters
        ----------
        where : date or array-like of dates
            Date(s) before which the last row(s) are returned.
        subset : str or array-like of str, default `None`
            For DataFrame, if not `None`, only use these columns to
            check for NaNs.

        Returns
        -------
        scalar, Series, or DataFrame

            The return can be:

            * scalar : when `self` is a Series and `where` is a scalar
            * Series: when `self` is a Series and `where` is an array-like,
              or when `self` is a DataFrame and `where` is a scalar
            * DataFrame : when `self` is a DataFrame and `where` is an
              array-like

            Return scalar, Series, or DataFrame.

        See Also
        --------
        merge_asof : Perform an asof merge. Similar to left join.

        Notes
        -----
        Dates are assumed to be sorted. Raises if this is not the case.

        Examples
        --------
        A Series and a scalar `where`.

        >>> s = pd.Series([1, 2, np.nan, 4], index=[10, 20, 30, 40])
        >>> s
        10    1.0
        20    2.0
        30    NaN
        40    4.0
        dtype: float64

        >>> s.asof(20)
        2.0

        For a sequence `where`, a Series is returned. The first value is
        NaN, because the first element of `where` is before the first
        index value.

        >>> s.asof([5, 20])
        5     NaN
        20    2.0
        dtype: float64

        Missing values are not considered. The following is ``2.0``, not
        NaN, even though NaN is at the index location for ``30``.

        >>> s.asof(30)
        2.0

        Take all columns into consideration

        >>> df = pd.DataFrame({'a': [10, 20, 30, 40, 50],
        ...                    'b': [None, None, None, None, 500]},
        ...                   index=pd.DatetimeIndex(['2018-02-27 09:01:00',
        ...                                           '2018-02-27 09:02:00',
        ...                                           '2018-02-27 09:03:00',
        ...                                           '2018-02-27 09:04:00',
        ...                                           '2018-02-27 09:05:00']))
        >>> df.asof(pd.DatetimeIndex(['2018-02-27 09:03:30',
        ...                           '2018-02-27 09:04:30']))
                              a   b
        2018-02-27 09:03:30 NaN NaN
        2018-02-27 09:04:30 NaN NaN

        Take a single column into consideration

        >>> df.asof(pd.DatetimeIndex(['2018-02-27 09:03:30',
        ...                           '2018-02-27 09:04:30']),
        ...         subset=['a'])
                                 a   b
        2018-02-27 09:03:30   30.0 NaN
        2018-02-27 09:04:30   40.0 NaN
        zasof requires a sorted indexNzsubset is not valid for Seriesr)�freq)r_r�r`�right)�sider\)r_r�)r_r�r�r�)r�r�rr_Zis_monotonicr�r@r�r7rOrNrWr�r�r�nan�searchsortedrrBrIrrr�r�Z	asof_locsr�r�r�)rjrH�subset�	is_seriesZis_list�startr�rfZnullsrrDr|rororp�asof�s\`



 

zNDFrame.asofcCst|�j|dd�S)ai
        Detect missing values.

        Return a boolean same-sized object indicating if the values are NA.
        NA values, such as None or :attr:`numpy.NaN`, gets mapped to True
        values.
        Everything else gets mapped to False values. Characters such as empty
        strings ``''`` or :attr:`numpy.inf` are not considered NA values
        (unless you set ``pandas.options.mode.use_inf_as_na = True``).

        Returns
        -------
        {klass}
            Mask of bool values for each element in {klass} that
            indicates whether an element is not an NA value.

        See Also
        --------
        {klass}.isnull : Alias of isna.
        {klass}.notna : Boolean inverse of isna.
        {klass}.dropna : Omit axes labels with missing values.
        isna : Top-level isna.

        Examples
        --------
        Show which entries in a DataFrame are NA.

        >>> df = pd.DataFrame({{'age': [5, 6, np.NaN],
        ...                    'born': [pd.NaT, pd.Timestamp('1939-05-27'),
        ...                             pd.Timestamp('1940-04-25')],
        ...                    'name': ['Alfred', 'Batman', ''],
        ...                    'toy': [None, 'Batmobile', 'Joker']}})
        >>> df
           age       born    name        toy
        0  5.0        NaT  Alfred       None
        1  6.0 1939-05-27  Batman  Batmobile
        2  NaN 1940-04-25              Joker

        >>> df.isna()
             age   born   name    toy
        0  False   True  False   True
        1  False  False  False  False
        2   True  False  False  False

        Show which entries in a Series are NA.

        >>> ser = pd.Series([5, 6, np.NaN])
        >>> ser
        0    5.0
        1    6.0
        2    NaN
        dtype: float64

        >>> ser.isna()
        0    False
        1    False
        2     True
        dtype: bool
        rB)rl)rBrh)rjrororprB�s=zNDFrame.isnacCst|�j|dd�S)N�isnull)rl)rBrh)rjrororpr`�szNDFrame.isnullcCst|�j|dd�S)a�
        Detect existing (non-missing) values.

        Return a boolean same-sized object indicating if the values are not NA.
        Non-missing values get mapped to True. Characters such as empty
        strings ``''`` or :attr:`numpy.inf` are not considered NA values
        (unless you set ``pandas.options.mode.use_inf_as_na = True``).
        NA values, such as None or :attr:`numpy.NaN`, get mapped to False
        values.

        Returns
        -------
        {klass}
            Mask of bool values for each element in {klass} that
            indicates whether an element is not an NA value.

        See Also
        --------
        {klass}.notnull : Alias of notna.
        {klass}.isna : Boolean inverse of notna.
        {klass}.dropna : Omit axes labels with missing values.
        notna : Top-level notna.

        Examples
        --------
        Show which entries in a DataFrame are not NA.

        >>> df = pd.DataFrame({{'age': [5, 6, np.NaN],
        ...                    'born': [pd.NaT, pd.Timestamp('1939-05-27'),
        ...                             pd.Timestamp('1940-04-25')],
        ...                    'name': ['Alfred', 'Batman', ''],
        ...                    'toy': [None, 'Batmobile', 'Joker']}})
        >>> df
           age       born    name        toy
        0  5.0        NaT  Alfred       None
        1  6.0 1939-05-27  Batman  Batmobile
        2  NaN 1940-04-25              Joker

        >>> df.notna()
             age   born  name    toy
        0   True  False  True  False
        1   True   True  True   True
        2  False   True  True   True

        Show which entries in a Series are not NA.

        >>> ser = pd.Series([5, 6, np.NaN])
        >>> ser
        0    5.0
        1    6.0
        2    NaN
        dtype: float64

        >>> ser.notna()
        0     True
        1     True
        2    False
        dtype: bool
        rC)rl)rCrh)rjrororprC�s=z
NDFrame.notnacCst|�j|dd�S)N�notnull)rl)rCrh)rjrororpraszNDFrame.notnullc
Cs�|dk	rtjt|��s,|dk	r4tjt|��r4td��|}t|j�}tjdd��R|dk	rv|j�|k}|j||ddd�}|dk	r�|j�|k}|j||ddd�}WdQRXtj|�r�tj||<|r�|j	|�S|SdS)Nz*Cannot use an NA value as a clip thresholdr�)rF)r�rm)
r�rrBr�rZerrstateZto_numpyrHrZri)rj�lower�upperrmrnr^r\rororp�_clip_with_scalar s"



zNDFrame._clip_with_scalarcCs�|dk	r|j|�}t|�rLt|�rL|jdkr<|jd||d�S|j|d|d�S|||d�t|�B}t|t�r�t|�r�t|t�r�|j	||j
d�}nt|||dd�d}|j||||d�S)N�le)rm)r�)r_)Zflexr\)r�rm)
r�r<r8rdrdrBr�r@r7r�r_rRrH)rj�	thresholdrlr�rmr\rororp�_clip_with_one_bound9s


zNDFrame._clip_with_one_boundcOs$t|d�}tj|||�}|dk	r*|j|�}t|�rFtjt|��rFd}t|�rbtjt|��rbd}|dk	r�|dk	r�t|�r�t|�r�t	||�t
||�}}|dks�t|�r�t|�r�|dks�t|�r�t|�r�|j|||d�S|}|dk	r�|j
||j||d�}|dk	�r |�r|}|j
||j||d�}|S)a	
        Trim values at input threshold(s).

        Assigns values outside boundary to boundary values. Thresholds
        can be singular values or array like, and in the latter case
        the clipping is performed element-wise in the specified axis.

        Parameters
        ----------
        lower : float or array_like, default None
            Minimum threshold value. All values below this
            threshold will be set to it.
        upper : float or array_like, default None
            Maximum threshold value. All values above this
            threshold will be set to it.
        axis : int or str axis name, optional
            Align object with lower and upper along the given axis.
        inplace : bool, default False
            Whether to perform the operation in place on the data.
        *args, **kwargs
            Additional keywords have no effect but might be accepted
            for compatibility with numpy.

        Returns
        -------
        Series or DataFrame
            Same type as calling object with the values outside the
            clip boundaries replaced.

        See Also
        --------
        Series.clip : Trim values at input threshold in series.
        DataFrame.clip : Trim values at input threshold in dataframe.
        numpy.clip : Clip (limit) the values in an array.

        Examples
        --------
        >>> data = {'col_0': [9, -3, 0, -1, 5], 'col_1': [-2, -7, 6, 8, -5]}
        >>> df = pd.DataFrame(data)
        >>> df
           col_0  col_1
        0      9     -2
        1     -3     -7
        2      0      6
        3     -1      8
        4      5     -5

        Clips per column using lower and upper thresholds:

        >>> df.clip(-4, 6)
           col_0  col_1
        0      6     -2
        1     -3     -4
        2      0      6
        3     -1      6
        4      5     -4

        Clips using specific lower and upper thresholds per column element:

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

        >>> df.clip(t, t + 4, axis=0)
           col_0  col_1
        0      6      2
        1     -3     -4
        2      0      3
        3      6      8
        4      5      3
        rmN)rm)rlr�rm)r*r�Zvalidate_clip_with_axisr�r7r�rrBr<�min�maxr8rdrg�gere)rjrbrcr�rmr�r�rnrororp�clipPs0U


zNDFrame.clipa�
        Group %(klass)s using a mapper or by a Series of columns.

        A groupby operation involves some combination of splitting the
        object, applying a function, and combining the results. This can be
        used to group large amounts of data and compute operations on these
        groups.

        Parameters
        ----------
        by : mapping, function, label, or list of labels
            Used to determine the groups for the groupby.
            If ``by`` is a function, it's called on each value of the object's
            index. If a dict or Series is passed, the Series or dict VALUES
            will be used to determine the groups (the Series' values are first
            aligned; see ``.align()`` method). If an ndarray is passed, the
            values are used as-is determine the groups. A label or list of
            labels may be passed to group by the columns in ``self``. Notice
            that a tuple is interpreted as a (single) key.
        axis : {0 or 'index', 1 or 'columns'}, default 0
            Split along rows (0) or columns (1).
        level : int, level name, or sequence of such, default None
            If the axis is a MultiIndex (hierarchical), group by a particular
            level or levels.
        as_index : bool, default True
            For aggregated output, return object with group labels as the
            index. Only relevant for DataFrame input. as_index=False is
            effectively "SQL-style" grouped output.
        sort : bool, default True
            Sort group keys. Get better performance by turning this off.
            Note this does not influence the order of observations within each
            group. Groupby preserves the order of rows within each group.
        group_keys : bool, default True
            When calling apply, add group keys to index to identify pieces.
        squeeze : bool, default False
            Reduce the dimensionality of the return type if possible,
            otherwise return a consistent type.

            .. deprecated:: 1.1.0

        observed : bool, default False
            This only applies if any of the groupers are Categoricals.
            If True: only show observed values for categorical groupers.
            If False: show all values for categorical groupers.

            .. versionadded:: 0.23.0
        dropna : bool, default True
            If True, and if group keys contain NA values, NA values together
            with row/column will be dropped.
            If False, NA values will also be treated as the key in groups

            .. versionadded:: 1.1.0

        Returns
        -------
        %(klass)sGroupBy
            Returns a groupby object that contains information about the groups.

        See Also
        --------
        resample : Convenience method for frequency conversion and resampling
            of time series.

        Notes
        -----
        See the `user guide
        <https://pandas.pydata.org/pandas-docs/stable/groupby.html>`_ for more.
        �groupby)rj�how�	normalizer�cCs ddlm}|||||||d�S)a�
        Convert TimeSeries to specified frequency.

        Optionally provide filling method to pad/backfill missing values.

        Returns the original data conformed to a new index with the specified
        frequency. ``resample`` is more appropriate if an operation, such as
        summarization, is necessary to represent the data at the new frequency.

        Parameters
        ----------
        freq : DateOffset or str
            Frequency DateOffset or string.
        method : {'backfill'/'bfill', 'pad'/'ffill'}, default None
            Method to use for filling holes in reindexed Series (note this
            does not fill NaNs that already were present):

            * 'pad' / 'ffill': propagate last valid observation forward to next
              valid
            * 'backfill' / 'bfill': use NEXT valid observation to fill.
        how : {'start', 'end'}, default end
            For PeriodIndex only (see PeriodIndex.asfreq).
        normalize : bool, default False
            Whether to reset output index to midnight.
        fill_value : scalar, optional
            Value to use for missing values, applied during upsampling (note
            this does not fill NaNs that already were present).

        Returns
        -------
        Same type as caller
            Object converted to the specified frequency.

        See Also
        --------
        reindex : Conform DataFrame to new index with optional filling logic.

        Notes
        -----
        To learn more about the frequency strings, please see `this link
        <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.

        Examples
        --------
        Start by creating a series with 4 one minute timestamps.

        >>> index = pd.date_range('1/1/2000', periods=4, freq='T')
        >>> series = pd.Series([0.0, None, 2.0, 3.0], index=index)
        >>> df = pd.DataFrame({'s':series})
        >>> df
                               s
        2000-01-01 00:00:00    0.0
        2000-01-01 00:01:00    NaN
        2000-01-01 00:02:00    2.0
        2000-01-01 00:03:00    3.0

        Upsample the series into 30 second bins.

        >>> df.asfreq(freq='30S')
                               s
        2000-01-01 00:00:00    0.0
        2000-01-01 00:00:30    NaN
        2000-01-01 00:01:00    NaN
        2000-01-01 00:01:30    NaN
        2000-01-01 00:02:00    2.0
        2000-01-01 00:02:30    NaN
        2000-01-01 00:03:00    3.0

        Upsample again, providing a ``fill value``.

        >>> df.asfreq(freq='30S', fill_value=9.0)
                               s
        2000-01-01 00:00:00    0.0
        2000-01-01 00:00:30    9.0
        2000-01-01 00:01:00    NaN
        2000-01-01 00:01:30    9.0
        2000-01-01 00:02:00    2.0
        2000-01-01 00:02:30    9.0
        2000-01-01 00:03:00    3.0

        Upsample again, providing a ``method``.

        >>> df.asfreq(freq='30S', method='bfill')
                               s
        2000-01-01 00:00:00    0.0
        2000-01-01 00:00:30    NaN
        2000-01-01 00:01:00    NaN
        2000-01-01 00:01:30    2.0
        2000-01-01 00:02:00    2.0
        2000-01-01 00:02:30    3.0
        2000-01-01 00:03:00    3.0
        r)�asfreq)rlrmrnr�)�pandas.core.resamplero)rjrWrlrmrnr�rorororprosdzNDFrame.asfreq)rjr_r�cCsP|dkr|j}|j|�}|j|�}t|t�s4td��|j||d�}|j||d�S)a�
        Select values at particular time of day (e.g., 9:30AM).

        Parameters
        ----------
        time : datetime.time or str
        axis : {0 or 'index', 1 or 'columns'}, default 0

            .. versionadded:: 0.24.0

        Returns
        -------
        Series or DataFrame

        Raises
        ------
        TypeError
            If the index is not  a :class:`DatetimeIndex`

        See Also
        --------
        between_time : Select values between particular times of the day.
        first : Select initial periods of time series based on a date offset.
        last : Select final periods of time series based on a date offset.
        DatetimeIndex.indexer_at_time : Get just the index locations for
            values at particular time of the day.

        Examples
        --------
        >>> i = pd.date_range('2018-04-09', periods=4, freq='12H')
        >>> ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i)
        >>> ts
                             A
        2018-04-09 00:00:00  1
        2018-04-09 12:00:00  2
        2018-04-10 00:00:00  3
        2018-04-10 12:00:00  4

        >>> ts.at_time('12:00')
                             A
        2018-04-09 12:00:00  2
        2018-04-10 12:00:00  4
        NzIndex must be DatetimeIndex)r_)r�)rr�r�r�rMrbZindexer_at_timer�)rjrSr_r�r_r�rororp�at_time�s.


zNDFrame.at_time)rj�
include_start�include_endr�cCsT|dkr|j}|j|�}|j|�}t|t�s4td��|j||||d�}|j||d�S)a�
        Select values between particular times of the day (e.g., 9:00-9:30 AM).

        By setting ``start_time`` to be later than ``end_time``,
        you can get the times that are *not* between the two times.

        Parameters
        ----------
        start_time : datetime.time or str
            Initial time as a time filter limit.
        end_time : datetime.time or str
            End time as a time filter limit.
        include_start : bool, default True
            Whether the start time needs to be included in the result.
        include_end : bool, default True
            Whether the end time needs to be included in the result.
        axis : {0 or 'index', 1 or 'columns'}, default 0
            Determine range time on index or columns value.

            .. versionadded:: 0.24.0

        Returns
        -------
        Series or DataFrame
            Data from the original object filtered to the specified dates range.

        Raises
        ------
        TypeError
            If the index is not  a :class:`DatetimeIndex`

        See Also
        --------
        at_time : Select values at a particular time of the day.
        first : Select initial periods of time series based on a date offset.
        last : Select final periods of time series based on a date offset.
        DatetimeIndex.indexer_between_time : Get just the index locations for
            values between particular times of the day.

        Examples
        --------
        >>> i = pd.date_range('2018-04-09', periods=4, freq='1D20min')
        >>> ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i)
        >>> ts
                             A
        2018-04-09 00:00:00  1
        2018-04-10 00:20:00  2
        2018-04-11 00:40:00  3
        2018-04-12 01:00:00  4

        >>> ts.between_time('0:15', '0:45')
                             A
        2018-04-10 00:20:00  2
        2018-04-11 00:40:00  3

        You get the times that are *not* between two times by setting
        ``start_time`` later than ``end_time``:

        >>> ts.between_time('0:45', '0:15')
                             A
        2018-04-09 00:00:00  1
        2018-04-12 01:00:00  4
        NzIndex must be DatetimeIndex)rrrs)r�)rr�r�r�rMrbZindexer_between_timer�)rj�
start_time�end_timerrrsr�r_r�rororp�between_time�sG


zNDFrame.between_timer^�	start_dayrX)�closedr��
conventionr��base�origin�offsetr�c
Cs8ddlm}
|j|�}|
||||||||||	|
||d�
S)a�6
        Resample time-series data.

        Convenience method for frequency conversion and resampling of time
        series. Object must have a datetime-like index (`DatetimeIndex`,
        `PeriodIndex`, or `TimedeltaIndex`), or pass datetime-like values
        to the `on` or `level` keyword.

        Parameters
        ----------
        rule : DateOffset, Timedelta or str
            The offset string or object representing target conversion.
        axis : {0 or 'index', 1 or 'columns'}, default 0
            Which axis to use for up- or down-sampling. For `Series` this
            will default to 0, i.e. along the rows. Must be
            `DatetimeIndex`, `TimedeltaIndex` or `PeriodIndex`.
        closed : {'right', 'left'}, default None
            Which side of bin interval is closed. The default is 'left'
            for all frequency offsets except for 'M', 'A', 'Q', 'BM',
            'BA', 'BQ', and 'W' which all have a default of 'right'.
        label : {'right', 'left'}, default None
            Which bin edge label to label bucket with. The default is 'left'
            for all frequency offsets except for 'M', 'A', 'Q', 'BM',
            'BA', 'BQ', and 'W' which all have a default of 'right'.
        convention : {'start', 'end', 's', 'e'}, default 'start'
            For `PeriodIndex` only, controls whether to use the start or
            end of `rule`.
        kind : {'timestamp', 'period'}, optional, default None
            Pass 'timestamp' to convert the resulting index to a
            `DateTimeIndex` or 'period' to convert it to a `PeriodIndex`.
            By default the input representation is retained.
        loffset : timedelta, default None
            Adjust the resampled time labels.

            .. deprecated:: 1.1.0
                You should add the loffset to the `df.index` after the resample.
                See below.

        base : int, default 0
            For frequencies that evenly subdivide 1 day, the "origin" of the
            aggregated intervals. For example, for '5min' frequency, base could
            range from 0 through 4. Defaults to 0.

            .. deprecated:: 1.1.0
                The new arguments that you should use are 'offset' or 'origin'.

        on : str, optional
            For a DataFrame, column to use instead of index for resampling.
            Column must be datetime-like.
        level : str or int, optional
            For a MultiIndex, level (name or number) to use for
            resampling. `level` must be datetime-like.
        origin : {'epoch', 'start', 'start_day'}, Timestamp or str, default 'start_day'
            The timestamp on which to adjust the grouping. The timezone of origin
            must match the timezone of the index.
            If a timestamp is not used, these values are also supported:

            - 'epoch': `origin` is 1970-01-01
            - 'start': `origin` is the first value of the timeseries
            - 'start_day': `origin` is the first day at midnight of the timeseries

            .. versionadded:: 1.1.0

        offset : Timedelta or str, default is None
            An offset timedelta added to the origin.

            .. versionadded:: 1.1.0

        Returns
        -------
        Resampler object

        See Also
        --------
        groupby : Group by mapping, function, label, or list of labels.
        Series.resample : Resample a Series.
        DataFrame.resample: Resample a DataFrame.

        Notes
        -----
        See the `user guide
        <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling>`_
        for more.

        To learn more about the offset strings, please see `this link
        <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#dateoffset-objects>`__.

        Examples
        --------
        Start by creating a series with 9 one minute timestamps.

        >>> index = pd.date_range('1/1/2000', periods=9, freq='T')
        >>> series = pd.Series(range(9), index=index)
        >>> series
        2000-01-01 00:00:00    0
        2000-01-01 00:01:00    1
        2000-01-01 00:02:00    2
        2000-01-01 00:03:00    3
        2000-01-01 00:04:00    4
        2000-01-01 00:05:00    5
        2000-01-01 00:06:00    6
        2000-01-01 00:07:00    7
        2000-01-01 00:08:00    8
        Freq: T, dtype: int64

        Downsample the series into 3 minute bins and sum the values
        of the timestamps falling into a bin.

        >>> series.resample('3T').sum()
        2000-01-01 00:00:00     3
        2000-01-01 00:03:00    12
        2000-01-01 00:06:00    21
        Freq: 3T, dtype: int64

        Downsample the series into 3 minute bins as above, but label each
        bin using the right edge instead of the left. Please note that the
        value in the bucket used as the label is not included in the bucket,
        which it labels. For example, in the original series the
        bucket ``2000-01-01 00:03:00`` contains the value 3, but the summed
        value in the resampled bucket with the label ``2000-01-01 00:03:00``
        does not include 3 (if it did, the summed value would be 6, not 3).
        To include this value close the right side of the bin interval as
        illustrated in the example below this one.

        >>> series.resample('3T', label='right').sum()
        2000-01-01 00:03:00     3
        2000-01-01 00:06:00    12
        2000-01-01 00:09:00    21
        Freq: 3T, dtype: int64

        Downsample the series into 3 minute bins as above, but close the right
        side of the bin interval.

        >>> series.resample('3T', label='right', closed='right').sum()
        2000-01-01 00:00:00     0
        2000-01-01 00:03:00     6
        2000-01-01 00:06:00    15
        2000-01-01 00:09:00    15
        Freq: 3T, dtype: int64

        Upsample the series into 30 second bins.

        >>> series.resample('30S').asfreq()[0:5]   # Select first 5 rows
        2000-01-01 00:00:00   0.0
        2000-01-01 00:00:30   NaN
        2000-01-01 00:01:00   1.0
        2000-01-01 00:01:30   NaN
        2000-01-01 00:02:00   2.0
        Freq: 30S, dtype: float64

        Upsample the series into 30 second bins and fill the ``NaN``
        values using the ``pad`` method.

        >>> series.resample('30S').pad()[0:5]
        2000-01-01 00:00:00    0
        2000-01-01 00:00:30    0
        2000-01-01 00:01:00    1
        2000-01-01 00:01:30    1
        2000-01-01 00:02:00    2
        Freq: 30S, dtype: int64

        Upsample the series into 30 second bins and fill the
        ``NaN`` values using the ``bfill`` method.

        >>> series.resample('30S').bfill()[0:5]
        2000-01-01 00:00:00    0
        2000-01-01 00:00:30    1
        2000-01-01 00:01:00    1
        2000-01-01 00:01:30    2
        2000-01-01 00:02:00    2
        Freq: 30S, dtype: int64

        Pass a custom function via ``apply``

        >>> def custom_resampler(array_like):
        ...     return np.sum(array_like) + 5
        ...
        >>> series.resample('3T').apply(custom_resampler)
        2000-01-01 00:00:00     8
        2000-01-01 00:03:00    17
        2000-01-01 00:06:00    26
        Freq: 3T, dtype: int64

        For a Series with a PeriodIndex, the keyword `convention` can be
        used to control whether to use the start or end of `rule`.

        Resample a year by quarter using 'start' `convention`. Values are
        assigned to the first quarter of the period.

        >>> s = pd.Series([1, 2], index=pd.period_range('2012-01-01',
        ...                                             freq='A',
        ...                                             periods=2))
        >>> s
        2012    1
        2013    2
        Freq: A-DEC, dtype: int64
        >>> s.resample('Q', convention='start').asfreq()
        2012Q1    1.0
        2012Q2    NaN
        2012Q3    NaN
        2012Q4    NaN
        2013Q1    2.0
        2013Q2    NaN
        2013Q3    NaN
        2013Q4    NaN
        Freq: Q-DEC, dtype: float64

        Resample quarters by month using 'end' `convention`. Values are
        assigned to the last month of the period.

        >>> q = pd.Series([1, 2, 3, 4], index=pd.period_range('2018-01-01',
        ...                                                   freq='Q',
        ...                                                   periods=4))
        >>> q
        2018Q1    1
        2018Q2    2
        2018Q3    3
        2018Q4    4
        Freq: Q-DEC, dtype: int64
        >>> q.resample('M', convention='end').asfreq()
        2018-03    1.0
        2018-04    NaN
        2018-05    NaN
        2018-06    2.0
        2018-07    NaN
        2018-08    NaN
        2018-09    3.0
        2018-10    NaN
        2018-11    NaN
        2018-12    4.0
        Freq: M, dtype: float64

        For DataFrame objects, the keyword `on` can be used to specify the
        column instead of the index for resampling.

        >>> d = dict({'price': [10, 11, 9, 13, 14, 18, 17, 19],
        ...           'volume': [50, 60, 40, 100, 50, 100, 40, 50]})
        >>> df = pd.DataFrame(d)
        >>> df['week_starting'] = pd.date_range('01/01/2018',
        ...                                     periods=8,
        ...                                     freq='W')
        >>> df
           price  volume week_starting
        0     10      50    2018-01-07
        1     11      60    2018-01-14
        2      9      40    2018-01-21
        3     13     100    2018-01-28
        4     14      50    2018-02-04
        5     18     100    2018-02-11
        6     17      40    2018-02-18
        7     19      50    2018-02-25
        >>> df.resample('M', on='week_starting').mean()
                       price  volume
        week_starting
        2018-01-31     10.75    62.5
        2018-02-28     17.00    60.0

        For a DataFrame with MultiIndex, the keyword `level` can be used to
        specify on which level the resampling needs to take place.

        >>> days = pd.date_range('1/1/2000', periods=4, freq='D')
        >>> d2 = dict({'price': [10, 11, 9, 13, 14, 18, 17, 19],
        ...            'volume': [50, 60, 40, 100, 50, 100, 40, 50]})
        >>> df2 = pd.DataFrame(d2,
        ...                    index=pd.MultiIndex.from_product([days,
        ...                                                     ['morning',
        ...                                                      'afternoon']]
        ...                                                     ))
        >>> df2
                              price  volume
        2000-01-01 morning       10      50
                   afternoon     11      60
        2000-01-02 morning        9      40
                   afternoon     13     100
        2000-01-03 morning       14      50
                   afternoon     18     100
        2000-01-04 morning       17      40
                   afternoon     19      50
        >>> df2.resample('D', level=0).sum()
                    price  volume
        2000-01-01     21     110
        2000-01-02     22     140
        2000-01-03     32     150
        2000-01-04     36      90

        If you want to adjust the start of the bins based on a fixed timestamp:

        >>> start, end = '2000-10-01 23:30:00', '2000-10-02 00:30:00'
        >>> rng = pd.date_range(start, end, freq='7min')
        >>> ts = pd.Series(np.arange(len(rng)) * 3, index=rng)
        >>> ts
        2000-10-01 23:30:00     0
        2000-10-01 23:37:00     3
        2000-10-01 23:44:00     6
        2000-10-01 23:51:00     9
        2000-10-01 23:58:00    12
        2000-10-02 00:05:00    15
        2000-10-02 00:12:00    18
        2000-10-02 00:19:00    21
        2000-10-02 00:26:00    24
        Freq: 7T, dtype: int64

        >>> ts.resample('17min').sum()
        2000-10-01 23:14:00     0
        2000-10-01 23:31:00     9
        2000-10-01 23:48:00    21
        2000-10-02 00:05:00    54
        2000-10-02 00:22:00    24
        Freq: 17T, dtype: int64

        >>> ts.resample('17min', origin='epoch').sum()
        2000-10-01 23:18:00     0
        2000-10-01 23:35:00    18
        2000-10-01 23:52:00    27
        2000-10-02 00:09:00    39
        2000-10-02 00:26:00    24
        Freq: 17T, dtype: int64

        >>> ts.resample('17min', origin='2000-01-01').sum()
        2000-10-01 23:24:00     3
        2000-10-01 23:41:00    15
        2000-10-01 23:58:00    45
        2000-10-02 00:15:00    45
        Freq: 17T, dtype: int64

        If you want to adjust the start of the bins with an `offset` Timedelta, the two
        following lines are equivalent:

        >>> ts.resample('17min', origin='start').sum()
        2000-10-01 23:30:00     9
        2000-10-01 23:47:00    21
        2000-10-02 00:04:00    54
        2000-10-02 00:21:00    24
        Freq: 17T, dtype: int64

        >>> ts.resample('17min', offset='23h30min').sum()
        2000-10-01 23:30:00     9
        2000-10-01 23:47:00    21
        2000-10-02 00:04:00    54
        2000-10-02 00:21:00    24
        Freq: 17T, dtype: int64

        To replace the use of the deprecated `base` argument, you can now use `offset`,
        in this example it is equivalent to have `base=2`:

        >>> ts.resample('17min', offset='2min').sum()
        2000-10-01 23:16:00     0
        2000-10-01 23:33:00     9
        2000-10-01 23:50:00    36
        2000-10-02 00:07:00    39
        2000-10-02 00:24:00    24
        Freq: 17T, dtype: int64

        To replace the use of the deprecated `loffset` argument:

        >>> from pandas.tseries.frequencies import to_offset
        >>> loffset = '19min'
        >>> ts_out = ts.resample('17min').sum()
        >>> ts_out.index = ts_out.index + to_offset(loffset)
        >>> ts_out
        2000-10-01 23:33:00     0
        2000-10-01 23:50:00     9
        2000-10-02 00:07:00    21
        2000-10-02 00:24:00    54
        2000-10-02 00:41:00    24
        Freq: 17T, dtype: int64
        r)�
get_resampler)rWr�rxr�r��loffsetryrzr�r�r{r|)rpr}r�)rjZruler�rxr�ryr�r~rz�onr�r{r|r}rororp�resamples&
zNDFrame.resamplecCs�t|jt�std��t|j�dkr&|St|�}|jd|}}t|t�rr||jkrr|jj|dd�}|jd|�S|j	d|�S)a�
        Select initial periods of time series data based on a date offset.

        When having a DataFrame with dates as index, this function can
        select the first few rows based on a date offset.

        Parameters
        ----------
        offset : str, DateOffset or dateutil.relativedelta
            The offset length of the data that will be selected. For instance,
            '1M' will display all the rows having their index within the first month.

        Returns
        -------
        Series or DataFrame
            A subset of the caller.

        Raises
        ------
        TypeError
            If the index is not  a :class:`DatetimeIndex`

        See Also
        --------
        last : Select final periods of time series based on a date offset.
        at_time : Select values at a particular time of the day.
        between_time : Select values between particular times of the day.

        Examples
        --------
        >>> i = pd.date_range('2018-04-09', periods=4, freq='2D')
        >>> ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i)
        >>> ts
                    A
        2018-04-09  1
        2018-04-11  2
        2018-04-13  3
        2018-04-15  4

        Get the rows for the first 3 days:

        >>> ts.first('3D')
                    A
        2018-04-09  1
        2018-04-11  2

        Notice the data for 3 first calendar days were returned, not the first
        3 days observed in the dataset, and therefore data for 2018-04-13 was
        not returned.
        z+'first' only supports a DatetimeIndex indexr�left)rYN)
r�r_rMrbr�rrr[r�r�)rjr|�end_date�endrororp�first�s3

z
NDFrame.firstcCsZt|jt�std��t|j�dkr&|St|�}|jd|}|jj|dd�}|j|d�S)a�
        Select final periods of time series data based on a date offset.

        When having a DataFrame with dates as index, this function can
        select the last few rows based on a date offset.

        Parameters
        ----------
        offset : str, DateOffset, dateutil.relativedelta
            The offset length of the data that will be selected. For instance,
            '3D' will display all the rows having their index within the last 3 days.

        Returns
        -------
        Series or DataFrame
            A subset of the caller.

        Raises
        ------
        TypeError
            If the index is not  a :class:`DatetimeIndex`

        See Also
        --------
        first : Select initial periods of time series based on a date offset.
        at_time : Select values at a particular time of the day.
        between_time : Select values between particular times of the day.

        Examples
        --------
        >>> i = pd.date_range('2018-04-09', periods=4, freq='2D')
        >>> ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i)
        >>> ts
                    A
        2018-04-09  1
        2018-04-11  2
        2018-04-13  3
        2018-04-15  4

        Get the rows for the last 3 days:

        >>> ts.last('3D')
                    A
        2018-04-13  3
        2018-04-15  4

        Notice the data for 3 last calendar days were returned, not the last
        3 observed days in the dataset, and therefore data for 2018-04-11 was
        not returned.
        z*'last' only supports a DatetimeIndex indexrr\rX)rYNr�)r�r_rMrbr�rr[r�)rjr|Z
start_dater^rororpr��s3zNDFrame.last�average�keep)rjrl�numeric_only�	na_optionr��pctr�c
sx�j����d	krd}t|��������fdd�}|dkr^y|��Stk
r\d}YnX|rl�j�}	n�}	||	�S)
a�

        Compute numerical data ranks (1 through n) along axis.

        By default, equal values are assigned a rank that is the average of the
        ranks of those values.

        Parameters
        ----------
        axis : {0 or 'index', 1 or 'columns'}, default 0
            Index to direct ranking.
        method : {'average', 'min', 'max', 'first', 'dense'}, default 'average'
            How to rank the group of records that have the same value (i.e. ties):

            * average: average rank of the group
            * min: lowest rank in the group
            * max: highest rank in the group
            * first: ranks assigned in order they appear in the array
            * dense: like 'min', but rank always increases by 1 between groups.

        numeric_only : bool, optional
            For DataFrame objects, rank only numeric columns if set to True.
        na_option : {'keep', 'top', 'bottom'}, default 'keep'
            How to rank NaN values:

            * keep: assign NaN rank to NaN values
            * top: assign smallest rank to NaN values if ascending
            * bottom: assign highest rank to NaN values if ascending.

        ascending : bool, default True
            Whether or not the elements should be ranked in ascending order.
        pct : bool, default False
            Whether or not to display the returned rankings in percentile
            form.

        Returns
        -------
        same type as caller
            Return a Series or DataFrame with data ranks as values.

        See Also
        --------
        core.groupby.GroupBy.rank : Rank of values within each group.

        Examples
        --------
        >>> df = pd.DataFrame(data={'Animal': ['cat', 'penguin', 'dog',
        ...                                    'spider', 'snake'],
        ...                         'Number_legs': [4, 2, 4, 8, np.nan]})
        >>> df
            Animal  Number_legs
        0      cat          4.0
        1  penguin          2.0
        2      dog          4.0
        3   spider          8.0
        4    snake          NaN

        The following example shows how the method behaves with the above
        parameters:

        * default_rank: this is the default behaviour obtained without using
          any parameter.
        * max_rank: setting ``method = 'max'`` the records that have the
          same values are ranked using the highest rank (e.g.: since 'cat'
          and 'dog' are both in the 2nd and 3rd position, rank 3 is assigned.)
        * NA_bottom: choosing ``na_option = 'bottom'``, if there are records
          with NaN values they are placed at the bottom of the ranking.
        * pct_rank: when setting ``pct = True``, the ranking is expressed as
          percentile rank.

        >>> df['default_rank'] = df['Number_legs'].rank()
        >>> df['max_rank'] = df['Number_legs'].rank(method='max')
        >>> df['NA_bottom'] = df['Number_legs'].rank(na_option='bottom')
        >>> df['pct_rank'] = df['Number_legs'].rank(pct=True)
        >>> df
            Animal  Number_legs  default_rank  max_rank  NA_bottom  pct_rank
        0      cat          4.0           2.5       3.0        2.5     0.625
        1  penguin          2.0           1.0       1.0        1.0     0.250
        2      dog          4.0           2.5       3.0        2.5     0.625
        3   spider          8.0           4.0       4.0        4.0     1.000
        4    snake          NaN           NaN       NaN        5.0       NaN
        r��top�bottomz3na_option must be one of 'keep', 'top', or 'bottom'cs8tj|j�����d�}�j|f|j��}|j�dd�S)N)r�rlr�r�r��rank)rl)�algosr�rfr�r�rh)r|Zranks)r�r�rlr�r�rjrorp�ranker� szNDFrame.rank.<locals>.rankerNT>r�r�r�)r�r�rbr0)
rjr�rlr�r�r�r�r&r�r|ro)r�r�rlr�r�rjrpr�& sZ


zNDFrame.ranka�
        Compare to another %(klass)s and show the differences.

        .. versionadded:: 1.1.0

        Parameters
        ----------
        other : %(klass)s
            Object to compare with.

        align_axis : {0 or 'index', 1 or 'columns'}, default 1
            Determine which axis to align the comparison on.

            * 0, or 'index' : Resulting differences are stacked vertically
                with rows drawn alternately from self and other.
            * 1, or 'columns' : Resulting differences are aligned horizontally
                with columns drawn alternately from self and other.

        keep_shape : bool, default False
            If true, all rows and columns are kept.
            Otherwise, only the ones with different values are kept.

        keep_equal : bool, default False
            If true, the result keeps values that are equal.
            Otherwise, equal values are shown as NaNs.
        �comparer\)�
align_axis�
keep_shape�
keep_equalcCs�ddlm}t|�t|�k	rNt|�jt|�j}}td|�d|�d|�d���||k|j�|j�@B}ddg}	|s�|j|�}|j|�}|s�t|t�r�|j	�}
|j	d	d
�}|j
||
f}|j
||
f}n||}||}|dkr�d	}n
|j|�}|||g||	d�}
||jk�r|
S|
j
|�}tj|j�}tjt|��|_ttd	|j��dg}t|
t��rj|
j||d
�}
n
|
j|�}
|||
j
|d
�_tj|
j|�jd
|
j|d
g�jj�}|
j||d
�}
|
S)Nr)r4zcan only compare 'z' (not 'z	') with 'r$rjrr\)r�r�)r�rr�)r\r�)Zpandas.core.reshape.concatr4rcrdrbrBrHr�r?rr�r�rar�r��arrayr�rUr�r�r�ZnlevelsZreorder_levelsr�ZreshaperF�flattenr�)rjrr�r�r�r4Zcls_selfZ	cls_otherr^rZcmaskZrmaskr�Zdiffr�Zax_names�orderr�rororpr�� sF





*zNDFrame.compare�outerc
s,tj|�}|
dkr��j�jkr�t�t�rj�j}|�fdd��jD�f�j��}|j�||||||||	d�	St�t�r��j}|�fdd��jD�f�j��}�j|||||||||	d�	S|dk	rȈj	|�}t�t
�r�j�||||||||	d�	St�t��r�j�||||||||	d�	Stdt
������dS)a�
        Align two objects on their axes with the specified join method.

        Join method is specified for each axis Index.

        Parameters
        ----------
        other : DataFrame or Series
        join : {{'outer', 'inner', 'left', 'right'}}, default 'outer'
        axis : allowed axis of the other object, default None
            Align on index (0), columns (1), or both (None).
        level : int or level name, default None
            Broadcast across a level, matching Index values on the
            passed MultiIndex level.
        copy : bool, default True
            Always returns new objects. If copy=False and no reindexing is
            required then original objects are returned.
        fill_value : scalar, default np.NaN
            Value to use for missing values. Defaults to NaN, but can be any
            "compatible" value.
        method : {{'backfill', 'bfill', 'pad', 'ffill', None}}, default None
            Method to use for filling holes in reindexed Series:

            - pad / ffill: propagate last valid observation forward to next valid.
            - backfill / bfill: use NEXT valid observation to fill gap.

        limit : int, default None
            If method is specified, this is the maximum number of consecutive
            NaN values to forward/backward fill. In other words, if there is
            a gap with more than this number of consecutive NaNs, it will only
            be partially filled. If method is not specified, this is the
            maximum number of entries along the entire axis where NaNs will be
            filled. Must be greater than 0 if not None.
        fill_axis : {axes_single_arg}, default 0
            Filling axis, method and limit.
        broadcast_axis : {axes_single_arg}, default None
            Broadcast values along this axis, if aligning two objects of
            different dimensions.

        Returns
        -------
        (left, right) : ({klass}, type of other)
            Aligned objects.
        r\csi|]
}�|�qSroro)r�r")rjrorpr�F!sz!NDFrame.align.<locals>.<dictcomp>)rFr�r�rer�rlr]�	fill_axiscsi|]
}�|�qSroro)r�r")rrorpr�X!sNzunsupported type: )rDZclean_fill_methodrar�r@r�r�r��_align_framer�r?�
_align_seriesrbrc)
rjrrFr�r�rer�rlr]r��broadcast_axis�consrjro)rrjrp�align!sn;




z
NDFrame.alignc
Cszd\}
}d	\}}
d
\}}t|t�}|dks2|dkr\|jj|j�s\|jj|j||dd�\}
}}
|dksl|dkr�|r�|jj|j�r�|jj|j||dd�\}}}|r�d|
|gi}n|
|g||gd�}|j|||dd�}|j|
|
g||gd�||dd�}|dk	�r0|j||	|d�}|dk	�st�|}|j||	|d�}t	|jj
��rf|jj|jjk�rf|
dk	�rf|
|_|
|_|j|�|j|�fS)NrT)rmr��return_indexersr\)rr\)rer�r�)rlr�r])NN)NN)NN)
r�r@r_rrFr�r�rr�r3r`�tzrh)rjrrFr�r�rer�rlr]r��
join_indexZjoin_columnsZilidxZiridxZclidxZcridxr]rr�rX�_leftrororpr��!sD



zNDFrame._align_framec
Cst|t�}
|
rp|rtd��|jj|j�r4d\}}}
n|jj|j||dd�\}}}
|j|||�}|j||
|�}�n
|j}|dkr�|j}d\}}
|jj|j�s�|jj|j||dd�\}}}
|dk	r�|j||dd�}nh|dk�r0|j	}d
\}}
|j	j|j��s|j	j|j||dd�\}}}
|dk	�r8|j||dd�}ntd��|�rR||jk�rR|j
�}|j|�}|
dk�rl|}n|j||d�}t
|��p�|dk	}|�r�|j||||	d	�}|j|||d
�}|
�s�|
�r|dk�rt|jj��r|jj|jjk�r|dk	�r||_||_|j|�|j|�fS)Nz1cannot align series to a series other than axis 0T)rmr�r�rr\)r�zMust specify axis=0 or 1)r�)rlr]r�)rlr])NNN)NN)NN)r�r@r�r_rrFZ_reindex_indexerrsr�r�rer�r�rCrr3r`r�rh)rjrrFr�r�rer�rlr]r�r]r�ZlidxZridxr�rX�fdataZfill_narororpr��!s\





zNDFrame._align_seriescs�t|d�}tj||�}t|t�r6|j|ddd�\}}n:t|d�sJtj|�}|j	|j	kr^t
d��|j|f|j��}t
|�}	|j|	�}d}
|js�t|t�s�t|�s�t
|
j|jd���q�x2|jD]}t|�s�t
|
j|d���q�Wn
|jt
�}|r�|n|}d	}t�t��rd�j|jk�r\|j�d
||tjd�\}�|dk�rdt�fd
d�t|j�D���rdt�ntd��t�tj��r�j	|j	k�r�|jdk�r�|j}
t��dk�r��d�nDt||
�t��k�r�|�r�tj |�}|j!�}�||
<|�nt
d��nt
d��n|j�f|j���|dk�rd}|jt"�dd�k�r4d	}n|j#|�dk}|�rft�t��rf�j$|j%|j&d��t|t��r�|j$|j%|j&d�}|j'|�}|�r�|j(��|j)j*|�||d�}|j|�}|j+|�S|j)j,�|||||d�}|j|�}|j-|�SdS)z�
        Equivalent to public method `where`, except that `other` is not
        applied as a function even if callable. Used in __setitem__.
        rmrXr\)rFr�r�z,Array conditional must be same shape as selfz5Boolean array expected for the condition, not {dtype})r`Tr�)rFr�r�r�Nc3s"|]\}}�j|�j|�VqdS)N)r�r)r�r�r�)rrorpr�X"sz!NDFrame._where.<locals>.<genexpr>z.cannot align with a higher dimensional NDFramerz/Length of replacements must equal series lengthz4other must be the same shape as self when an ndarrayra)r�)r^�newr�r�)r�condr�r��try_castr�).r*r��apply_if_callabler�rrr�r�r�Z
asanyarrayr�r�r�r�rrr5r?r1rTr`r2r�rarZrr�rZr%r�r�rr�r6rer�r�r�r�rTr�r/rsZputmaskrirHrh)rjr�rrmr�r�r�r�r�r�r&�dtZ	try_quickZicondZ	new_otherr��
block_axisrrnro)rrp�_where"s�














zNDFrame._where�True�FalserHr^)r[r�Zcond_revr�Z
name_otherc	Cs$tj||�}|j|||||||d�S)a�

        Replace values where the condition is {cond_rev}.

        Parameters
        ----------
        cond : bool {klass}, array-like, or callable
            Where `cond` is {cond}, keep the original value. Where
            {cond_rev}, replace with corresponding value from `other`.
            If `cond` is callable, it is computed on the {klass} and
            should return boolean {klass} or array. The callable must
            not change input {klass} (though pandas doesn't check it).
        other : scalar, {klass}, or callable
            Entries where `cond` is {cond_rev} are replaced with
            corresponding value from `other`.
            If other is callable, it is computed on the {klass} and
            should return scalar or {klass}. The callable must not
            change input {klass} (though pandas doesn't check it).
        inplace : bool, default False
            Whether to perform the operation in place on the data.
        axis : int, default None
            Alignment axis if needed.
        level : int, default None
            Alignment level if needed.
        errors : str, {{'raise', 'ignore'}}, default 'raise'
            Note that currently this parameter won't affect
            the results and will always coerce to a suitable dtype.

            - 'raise' : allow exceptions to be raised.
            - 'ignore' : suppress exceptions. On error return original object.

        try_cast : bool, default False
            Try to cast the result back to the input type (if possible).

        Returns
        -------
        Same type as caller

        See Also
        --------
        :func:`DataFrame.{name_other}` : Return an object of same shape as
            self.

        Notes
        -----
        The {name} method is an application of the if-then idiom. For each
        element in the calling DataFrame, if ``cond`` is ``{cond}`` the
        element is used; otherwise the corresponding element from the DataFrame
        ``other`` is used.

        The signature for :func:`DataFrame.where` differs from
        :func:`numpy.where`. Roughly ``df1.where(m, df2)`` is equivalent to
        ``np.where(m, df1, df2)``.

        For further details and examples see the ``{name}`` documentation in
        :ref:`indexing <indexing.where_mask>`.

        Examples
        --------
        >>> s = pd.Series(range(5))
        >>> s.where(s > 0)
        0    NaN
        1    1.0
        2    2.0
        3    3.0
        4    4.0
        dtype: float64

        >>> s.mask(s > 0)
        0    0.0
        1    NaN
        2    NaN
        3    NaN
        4    NaN
        dtype: float64

        >>> s.where(s > 1, 10)
        0    10
        1    10
        2    2
        3    3
        4    4
        dtype: int64

        >>> df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=['A', 'B'])
        >>> df
           A  B
        0  0  1
        1  2  3
        2  4  5
        3  6  7
        4  8  9
        >>> m = df % 3 == 0
        >>> df.where(m, -df)
           A  B
        0  0 -1
        1 -2  3
        2 -4 -5
        3  6 -7
        4 -8  9
        >>> df.where(m, -df) == np.where(m, df, -df)
              A     B
        0  True  True
        1  True  True
        2  True  True
        3  True  True
        4  True  True
        >>> df.where(m, -df) == df.mask(~m, -df)
              A     B
        0  True  True
        1  True  True
        2  True  True
        3  True  True
        4  True  True
        )r�r�)r�r�r�)rjr�rrmr�r�r�r�rororprH�"sz
NDFrame.wherec	CsDt|d�}tj||�}t|d�s*tj|�}|j|||||||d�S)Nrmr)rrmr�r�r�r�)r*r�r�r�r�r�rH)rjr�rrmr�r�r�r�rororpr^6#s


zNDFrame.maskcCs|dkr|j�S|dkrH|j|�}|jj|||d�}|j|�j|dd�S|j|�}|dkr�t|dd�}|dkrzt|dd�}|dkr�d	}t|��nt	|t
�r�t|�}t	|t�r�t|j
�}	||	kr�|	dk	s�t�td
|j�d|	j����|j|�}
n|j||�}
|j|
|�}|j|dd�S)a�
        Shift index by desired number of periods with an optional time `freq`.

        When `freq` is not passed, shift the index without realigning the data.
        If `freq` is passed (in this case, the index must be date or datetime,
        or it will raise a `NotImplementedError`), the index will be
        increased using the periods and the `freq`. `freq` can be inferred
        when specified as "infer" as long as either freq or inferred_freq
        attribute is set in the index.

        Parameters
        ----------
        periods : int
            Number of periods to shift. Can be positive or negative.
        freq : DateOffset, tseries.offsets, timedelta, or str, optional
            Offset to use from the tseries module or time rule (e.g. 'EOM').
            If `freq` is specified then the index values are shifted but the
            data is not realigned. That is, use `freq` if you would like to
            extend the index when shifting and preserve the original data.
            If `freq` is specified as "infer" then it will be inferred from
            the freq or inferred_freq attributes of the index. If neither of
            those attributes exist, a ValueError is thrown
        axis : {{0 or 'index', 1 or 'columns', None}}, default None
            Shift direction.
        fill_value : object, optional
            The scalar value to use for newly introduced missing values.
            the default depends on the dtype of `self`.
            For numeric data, ``np.nan`` is used.
            For datetime, timedelta, or period data, etc. :attr:`NaT` is used.
            For extension dtypes, ``self.dtype.na_value`` is used.

            .. versionchanged:: 1.1.0

        Returns
        -------
        {klass}
            Copy of input object, shifted.

        See Also
        --------
        Index.shift : Shift values of Index.
        DatetimeIndex.shift : Shift values of DatetimeIndex.
        PeriodIndex.shift : Shift values of PeriodIndex.
        tshift : Shift the time index, using the index's frequency if
            available.

        Examples
        --------
        >>> df = pd.DataFrame({{"Col1": [10, 20, 15, 30, 45],
        ...                    "Col2": [13, 23, 18, 33, 48],
        ...                    "Col3": [17, 27, 22, 37, 52]}},
        ...                   index=pd.date_range("2020-01-01", "2020-01-05"))
        >>> df
                    Col1  Col2  Col3
        2020-01-01    10    13    17
        2020-01-02    20    23    27
        2020-01-03    15    18    22
        2020-01-04    30    33    37
        2020-01-05    45    48    52

        >>> df.shift(periods=3)
                    Col1  Col2  Col3
        2020-01-01   NaN   NaN   NaN
        2020-01-02   NaN   NaN   NaN
        2020-01-03   NaN   NaN   NaN
        2020-01-04  10.0  13.0  17.0
        2020-01-05  20.0  23.0  27.0

        >>> df.shift(periods=1, axis="columns")
                    Col1  Col2  Col3
        2020-01-01   NaN  10.0  13.0
        2020-01-02   NaN  20.0  23.0
        2020-01-03   NaN  15.0  18.0
        2020-01-04   NaN  30.0  33.0
        2020-01-05   NaN  45.0  48.0

        >>> df.shift(periods=3, fill_value=0)
                    Col1  Col2  Col3
        2020-01-01     0     0     0
        2020-01-02     0     0     0
        2020-01-03     0     0     0
        2020-01-04    10    13    17
        2020-01-05    20    23    27

        >>> df.shift(periods=3, freq="D")
                    Col1  Col2  Col3
        2020-01-04    10    13    17
        2020-01-05    20    23    27
        2020-01-06    15    18    22
        2020-01-07    30    33    37
        2020-01-08    45    48    52

        >>> df.shift(periods=3, freq="infer")
                    Col1  Col2  Col3
        2020-01-04    10    13    17
        2020-01-05    20    23    27
        2020-01-06    15    18    22
        2020-01-07    30    33    37
        2020-01-08    45    48    52
        rN)�periodsr�r��shift)rlrorWZ
inferred_freqz6Freq was not set in the index hence cannot be inferredzGiven freq z! does not match PeriodIndex freq )rer�rsr�r�rhr�r�r�r�r�rrOrWr�Z	rule_coder�)rjr�rWr�r�r�rr_r&Z	orig_freqr�rnrororpr�Z#s6h





z
NDFrame.shift)rjr�r�cCs||dkr|S|dkr,td|�}t|d�}nt|d�}td|�}|j||d�}|j|�|}|j||dd�|j|dd�S)a
        Equivalent to `shift` without copying data.

        The shifted data will not include the dropped periods and the
        shifted axis will be smaller than the original.

        Parameters
        ----------
        periods : int
            Number of periods to move, can be positive or negative.

        Returns
        -------
        shifted : same type as caller

        Notes
        -----
        While the `slice_shift` is faster than `shift`, you may pay for it
        later during alignment.
        rN)r�T)r�rm�slice_shift)rl)r�r�r�r�rh)rjr�r�ZvslicerZislicerZnew_objZshifted_axisrororpr��#s
zNDFrame.slice_shift)rjr�r�r�cCs*tjdtdd�|dkrd}|j|||�S)uW
        Shift the time index, using the index's frequency if available.

        .. deprecated:: 1.1.0
            Use `shift` instead.

        Parameters
        ----------
        periods : int
            Number of periods to move, can be positive or negative.
        freq : DateOffset, timedelta, or str, default None
            Increment to use from the tseries module
            or time rule expressed as a string (e.g. 'EOM').
        axis : {0 or ‘index’, 1 or ‘columns’, None}, default 0
            Corresponds to the axis that contains the Index.

        Returns
        -------
        shifted : Series/DataFrame

        Notes
        -----
        If freq is not specified then tries to use the freq or inferred_freq
        attributes of the index. If neither of those attributes exist, a
        ValueError is thrown
        zWtshift is deprecated and will be removed in a future version. Please use shift instead.r�)r�Nro)r�r�r�r�)rjr�rWr�rororpr{$szNDFrame.tshift)rjrer�c	Cs|dkr|j}|j|�}|j|�}|jr:|jr:td��|jr\ddlm}||�}||�}|dk	r�|dk	r�||kr�td|�d|����t	|�dkr�|jr�||}}t
dd�g|j}t
||�||<|jt
|�}t|t�r�t||j|�|j||��|�r|j�}|S)a
        Truncate a Series or DataFrame before and after some index value.

        This is a useful shorthand for boolean indexing based on index
        values above or below certain thresholds.

        Parameters
        ----------
        before : date, str, int
            Truncate all rows before this index value.
        after : date, str, int
            Truncate all rows after this index value.
        axis : {0 or 'index', 1 or 'columns'}, optional
            Axis to truncate. Truncates the index (rows) by default.
        copy : bool, default is True,
            Return a copy of the truncated section.

        Returns
        -------
        type of caller
            The truncated Series or DataFrame.

        See Also
        --------
        DataFrame.loc : Select a subset of a DataFrame by label.
        DataFrame.iloc : Select a subset of a DataFrame by position.

        Notes
        -----
        If the index being truncated contains only datetime values,
        `before` and `after` may be specified as strings instead of
        Timestamps.

        Examples
        --------
        >>> df = pd.DataFrame({'A': ['a', 'b', 'c', 'd', 'e'],
        ...                    'B': ['f', 'g', 'h', 'i', 'j'],
        ...                    'C': ['k', 'l', 'm', 'n', 'o']},
        ...                   index=[1, 2, 3, 4, 5])
        >>> df
           A  B  C
        1  a  f  k
        2  b  g  l
        3  c  h  m
        4  d  i  n
        5  e  j  o

        >>> df.truncate(before=2, after=4)
           A  B  C
        2  b  g  l
        3  c  h  m
        4  d  i  n

        The columns of a DataFrame can be truncated.

        >>> df.truncate(before="A", after="B", axis="columns")
           A  B
        1  a  f
        2  b  g
        3  c  h
        4  d  i
        5  e  j

        For Series, only rows can be truncated.

        >>> df['A'].truncate(before=2, after=4)
        2    b
        3    c
        4    d
        Name: A, dtype: object

        The index values in ``truncate`` can be datetimes or string
        dates.

        >>> dates = pd.date_range('2016-01-01', '2016-02-01', freq='s')
        >>> df = pd.DataFrame(index=dates, data={'A': 1})
        >>> df.tail()
                             A
        2016-01-31 23:59:56  1
        2016-01-31 23:59:57  1
        2016-01-31 23:59:58  1
        2016-01-31 23:59:59  1
        2016-02-01 00:00:00  1

        >>> df.truncate(before=pd.Timestamp('2016-01-05'),
        ...             after=pd.Timestamp('2016-01-10')).tail()
                             A
        2016-01-09 23:59:56  1
        2016-01-09 23:59:57  1
        2016-01-09 23:59:58  1
        2016-01-09 23:59:59  1
        2016-01-10 00:00:00  1

        Because the index is a DatetimeIndex containing only dates, we can
        specify `before` and `after` as strings. They will be coerced to
        Timestamps before truncation.

        >>> df.truncate('2016-01-05', '2016-01-10').tail()
                             A
        2016-01-09 23:59:56  1
        2016-01-09 23:59:57  1
        2016-01-09 23:59:58  1
        2016-01-09 23:59:59  1
        2016-01-10 00:00:00  1

        Note that ``truncate`` assumes a 0 value for any unspecified time
        component (midnight). This differs from partial string slicing, which
        returns any partially matching dates.

        >>> df.loc['2016-01-05':'2016-01-10', :].tail()
                             A
        2016-01-10 23:59:55  1
        2016-01-10 23:59:56  1
        2016-01-10 23:59:57  1
        2016-01-10 23:59:58  1
        2016-01-10 23:59:59  1
        Nz truncate requires a sorted indexr)�to_datetimez
Truncate: z must be after r\)rr�r�Zis_monotonic_increasingZis_monotonic_decreasingr�Zis_all_datesZpandas.core.tools.datetimesr�r�r�r�r�r�r�rJr�r��truncatere)	rjZbefore�afterr�rer�r�r�rnrororpr�<$s.x



zNDFrame.truncatec	s��j����j��}��fdd�}t|t�rV|j|�}||j||�}|j||d�}n*|dd|jfkrvtd|�d���|||�}�j	|d�}|j
|�d	d
�}|j�dd�S)
aB
        Convert tz-aware axis to target time zone.

        Parameters
        ----------
        tz : str or tzinfo object
        axis : the axis to convert
        level : int, str, default None
            If axis is a MultiIndex, convert a specific level. Otherwise
            must be None.
        copy : bool, default True
            Also make a copy of the underlying data.

        Returns
        -------
        {klass}
            Object with time zone converted axis.

        Raises
        ------
        TypeError
            If the axis is tz-naive.
        csLt|d�s>t|�dkr0�j��}t|�d���qHtg|d�}n
|j|�}|S)N�
tz_convertrz, is not a valid DatetimeIndex or PeriodIndex)r�)r�r�r�rbrMr�)r�r��ax_name)r�rjrorp�_tz_convert�$s


z'NDFrame.tz_convert.<locals>._tz_convert)r�Nrz
The level z
 is not valid)r�F)r�rmr�)rl)r�r�r�rJr��levels�
set_levelsr�r�rer�rh)	rjr�r�r�rer�r��	new_levelrnro)r�rjrpr��$s




zNDFrame.tz_convert)rjre�nonexistentr�cs�d}||kr t|t�r td���j����j��}��fdd�}	t|t�rz|j|�}|	|j||||�}
|j|
|d�}n.|d	d
|j	fkr�td|�d���|	||||�}�j
|d
�}|j|�dd�}|j�dd�S)a7
        Localize tz-naive index of a Series or DataFrame to target time zone.

        This operation localizes the Index. To localize the values in a
        timezone-naive Series, use :meth:`Series.dt.tz_localize`.

        Parameters
        ----------
        tz : str or tzinfo
        axis : the axis to localize
        level : int, str, default None
            If axis ia a MultiIndex, localize a specific level. Otherwise
            must be None.
        copy : bool, default True
            Also make a copy of the underlying data.
        ambiguous : 'infer', bool-ndarray, 'NaT', default 'raise'
            When clocks moved backward due to DST, ambiguous times may arise.
            For example in Central European Time (UTC+01), when going from
            03:00 DST to 02:00 non-DST, 02:30:00 local time occurs both at
            00:30:00 UTC and at 01:30:00 UTC. In such a situation, the
            `ambiguous` parameter dictates how ambiguous times should be
            handled.

            - 'infer' will attempt to infer fall dst-transition hours based on
              order
            - bool-ndarray where True signifies a DST time, False designates
              a non-DST time (note that this flag is only applicable for
              ambiguous times)
            - 'NaT' will return NaT where there are ambiguous times
            - 'raise' will raise an AmbiguousTimeError if there are ambiguous
              times.
        nonexistent : str, default 'raise'
            A nonexistent time does not exist in a particular timezone
            where clocks moved forward due to DST. Valid values are:

            - 'shift_forward' will shift the nonexistent time forward to the
              closest existing time
            - 'shift_backward' will shift the nonexistent time backward to the
              closest existing time
            - 'NaT' will return NaT where there are nonexistent times
            - timedelta objects will shift nonexistent times by the timedelta
            - 'raise' will raise an NonExistentTimeError if there are
              nonexistent times.

            .. versionadded:: 0.24.0

        Returns
        -------
        Series or DataFrame
            Same type as the input.

        Raises
        ------
        TypeError
            If the TimeSeries is tz-aware and tz is not None.

        Examples
        --------
        Localize local times:

        >>> s = pd.Series([1],
        ...               index=pd.DatetimeIndex(['2018-09-15 01:30:00']))
        >>> s.tz_localize('CET')
        2018-09-15 01:30:00+02:00    1
        dtype: int64

        Be careful with DST changes. When there is sequential data, pandas
        can infer the DST time:

        >>> s = pd.Series(range(7),
        ...               index=pd.DatetimeIndex(['2018-10-28 01:30:00',
        ...                                       '2018-10-28 02:00:00',
        ...                                       '2018-10-28 02:30:00',
        ...                                       '2018-10-28 02:00:00',
        ...                                       '2018-10-28 02:30:00',
        ...                                       '2018-10-28 03:00:00',
        ...                                       '2018-10-28 03:30:00']))
        >>> s.tz_localize('CET', ambiguous='infer')
        2018-10-28 01:30:00+02:00    0
        2018-10-28 02:00:00+02:00    1
        2018-10-28 02:30:00+02:00    2
        2018-10-28 02:00:00+01:00    3
        2018-10-28 02:30:00+01:00    4
        2018-10-28 03:00:00+01:00    5
        2018-10-28 03:30:00+01:00    6
        dtype: int64

        In some cases, inferring the DST is impossible. In such cases, you can
        pass an ndarray to the ambiguous parameter to set the DST explicitly

        >>> s = pd.Series(range(3),
        ...               index=pd.DatetimeIndex(['2018-10-28 01:20:00',
        ...                                       '2018-10-28 02:36:00',
        ...                                       '2018-10-28 03:46:00']))
        >>> s.tz_localize('CET', ambiguous=np.array([True, True, False]))
        2018-10-28 01:20:00+02:00    0
        2018-10-28 02:36:00+02:00    1
        2018-10-28 03:46:00+01:00    2
        dtype: int64

        If the DST transition causes nonexistent times, you can shift these
        dates forward or backward with a timedelta object or `'shift_forward'`
        or `'shift_backward'`.

        >>> s = pd.Series(range(2),
        ...               index=pd.DatetimeIndex(['2015-03-29 02:30:00',
        ...                                       '2015-03-29 03:30:00']))
        >>> s.tz_localize('Europe/Warsaw', nonexistent='shift_forward')
        2015-03-29 03:00:00+02:00    0
        2015-03-29 03:30:00+02:00    1
        dtype: int64
        >>> s.tz_localize('Europe/Warsaw', nonexistent='shift_backward')
        2015-03-29 01:59:59.999999999+01:00    0
        2015-03-29 03:30:00+02:00              1
        dtype: int64
        >>> s.tz_localize('Europe/Warsaw', nonexistent=pd.Timedelta('1H'))
        2015-03-29 03:30:00+02:00    0
        2015-03-29 03:30:00+02:00    1
        dtype: int64
        r��NaT�
shift_forward�shift_backwardzoThe nonexistent argument must be one of 'raise', 'NaT', 'shift_forward', 'shift_backward' or a timedelta objectcsRt|d�s>t|�dkr0�j��}t|�d���qNtg|d�}n|j|||d�}|S)N�tz_localizerz, is not a valid DatetimeIndex or PeriodIndex)r�)�	ambiguousr�)r�r�r�rbrMr�)r�r�r�r�r�)r�rjrorp�_tz_localize�%s

z)NDFrame.tz_localize.<locals>._tz_localize)r�Nrz
The level z
 is not valid)r�F)r�rmr�)rl)r�r�r�r�)
r�rr�r�r�rJr�r�r�r�rer�rh)rjr�r�r�rer�r�Znonexistent_optionsr�r�r�rnro)r�rjrpr�%s&





zNDFrame.tz_localizecCs
tj|�S)a�
        Return a Series/DataFrame with absolute numeric value of each element.

        This function only applies to elements that are all numeric.

        Returns
        -------
        abs
            Series/DataFrame containing the absolute value of each element.

        See Also
        --------
        numpy.absolute : Calculate the absolute value element-wise.

        Notes
        -----
        For ``complex`` inputs, ``1.2 + 1j``, the absolute value is
        :math:`\sqrt{ a^2 + b^2 }`.

        Examples
        --------
        Absolute numeric values in a Series.

        >>> s = pd.Series([-1.10, 2, -3.33, 4])
        >>> s.abs()
        0    1.10
        1    2.00
        2    3.33
        3    4.00
        dtype: float64

        Absolute numeric values in a Series with complex numbers.

        >>> s = pd.Series([1.2 + 1j])
        >>> s.abs()
        0    1.56205
        dtype: float64

        Absolute numeric values in a Series with a Timedelta element.

        >>> s = pd.Series([pd.Timedelta('1 days')])
        >>> s.abs()
        0   1 days
        dtype: timedelta64[ns]

        Select rows with data closest to certain value using argsort (from
        `StackOverflow <https://stackoverflow.com/a/17758115>`__).

        >>> df = pd.DataFrame({
        ...     'a': [4, 5, 6, 7],
        ...     'b': [10, 20, 30, 40],
        ...     'c': [100, 50, -30, -50]
        ... })
        >>> df
             a    b    c
        0    4   10  100
        1    5   20   50
        2    6   30  -30
        3    7   40  -50
        >>> df.loc[(df.c - 43).abs().argsort()]
             a    b    c
        1    5   20   50
        0    4   10  100
        2    6   30  -30
        3    7   40  -50
        )r�r)rjrororpr�%sCzNDFrame.abscs��jdkr�jjdkrtd���dk	rTt���t��d�krH�jd�tj���ntj	dddg��tj
��}t|�t��kr�td��|�t�����fd	d
���fdd����fd
d������fdd���jdkrވ��S|dko�|dk�r*tj
g}��r|jd��j|d�}t|j�dk�r^�}n4|dk�rP|dk	�rJd}t|���}n�j||d�}�fdd�|j�D�}	g�tdd�|	D�td�}
x2|
D]*}x"|D]}|�k�r��j|��q�W�q�Wtj�fdd�|	D�ddd�}
|jj�|
_|
S)a�"
        Generate descriptive statistics.

        Descriptive statistics include those that summarize the central
        tendency, dispersion and shape of a
        dataset's distribution, excluding ``NaN`` values.

        Analyzes both numeric and object series, as well
        as ``DataFrame`` column sets of mixed data types. The output
        will vary depending on what is provided. Refer to the notes
        below for more detail.

        Parameters
        ----------
        percentiles : list-like of numbers, optional
            The percentiles to include in the output. All should
            fall between 0 and 1. The default is
            ``[.25, .5, .75]``, which returns the 25th, 50th, and
            75th percentiles.
        include : 'all', list-like of dtypes or None (default), optional
            A white list of data types to include in the result. Ignored
            for ``Series``. Here are the options:

            - 'all' : All columns of the input will be included in the output.
            - A list-like of dtypes : Limits the results to the
              provided data types.
              To limit the result to numeric types submit
              ``numpy.number``. To limit it instead to object columns submit
              the ``numpy.object`` data type. Strings
              can also be used in the style of
              ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To
              select pandas categorical columns, use ``'category'``
            - None (default) : The result will include all numeric columns.
        exclude : list-like of dtypes or None (default), optional,
            A black list of data types to omit from the result. Ignored
            for ``Series``. Here are the options:

            - A list-like of dtypes : Excludes the provided data types
              from the result. To exclude numeric types submit
              ``numpy.number``. To exclude object columns submit the data
              type ``numpy.object``. Strings can also be used in the style of
              ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To
              exclude pandas categorical columns, use ``'category'``
            - None (default) : The result will exclude nothing.
        datetime_is_numeric : bool, default False
            Whether to treat datetime dtypes as numeric. This affects statistics
            calculated for the column. For DataFrame input, this also
            controls whether datetime columns are included by default.

            .. versionadded:: 1.1.0

        Returns
        -------
        Series or DataFrame
            Summary statistics of the Series or Dataframe provided.

        See Also
        --------
        DataFrame.count: Count number of non-NA/null observations.
        DataFrame.max: Maximum of the values in the object.
        DataFrame.min: Minimum of the values in the object.
        DataFrame.mean: Mean of the values.
        DataFrame.std: Standard deviation of the observations.
        DataFrame.select_dtypes: Subset of a DataFrame including/excluding
            columns based on their dtype.

        Notes
        -----
        For numeric data, the result's index will include ``count``,
        ``mean``, ``std``, ``min``, ``max`` as well as lower, ``50`` and
        upper percentiles. By default the lower percentile is ``25`` and the
        upper percentile is ``75``. The ``50`` percentile is the
        same as the median.

        For object data (e.g. strings or timestamps), the result's index
        will include ``count``, ``unique``, ``top``, and ``freq``. The ``top``
        is the most common value. The ``freq`` is the most common value's
        frequency. Timestamps also include the ``first`` and ``last`` items.

        If multiple object values have the highest count, then the
        ``count`` and ``top`` results will be arbitrarily chosen from
        among those with the highest count.

        For mixed data types provided via a ``DataFrame``, the default is to
        return only an analysis of numeric columns. If the dataframe consists
        only of object and categorical data without any numeric columns, the
        default is to return an analysis of both the object and categorical
        columns. If ``include='all'`` is provided as an option, the result
        will include a union of attributes of each type.

        The `include` and `exclude` parameters can be used to limit
        which columns in a ``DataFrame`` are analyzed for the output.
        The parameters are ignored when analyzing a ``Series``.

        Examples
        --------
        Describing a numeric ``Series``.

        >>> s = pd.Series([1, 2, 3])
        >>> s.describe()
        count    3.0
        mean     2.0
        std      1.0
        min      1.0
        25%      1.5
        50%      2.0
        75%      2.5
        max      3.0
        dtype: float64

        Describing a categorical ``Series``.

        >>> s = pd.Series(['a', 'a', 'b', 'c'])
        >>> s.describe()
        count     4
        unique    3
        top       a
        freq      2
        dtype: object

        Describing a timestamp ``Series``.

        >>> s = pd.Series([
        ...   np.datetime64("2000-01-01"),
        ...   np.datetime64("2010-01-01"),
        ...   np.datetime64("2010-01-01")
        ... ])
        >>> s.describe(datetime_is_numeric=True)
        count                      3
        mean     2006-09-01 08:00:00
        min      2000-01-01 00:00:00
        25%      2004-12-31 12:00:00
        50%      2010-01-01 00:00:00
        75%      2010-01-01 00:00:00
        max      2010-01-01 00:00:00
        dtype: object

        Describing a ``DataFrame``. By default only numeric fields
        are returned.

        >>> df = pd.DataFrame({'categorical': pd.Categorical(['d','e','f']),
        ...                    'numeric': [1, 2, 3],
        ...                    'object': ['a', 'b', 'c']
        ...                   })
        >>> df.describe()
               numeric
        count      3.0
        mean       2.0
        std        1.0
        min        1.0
        25%        1.5
        50%        2.0
        75%        2.5
        max        3.0

        Describing all columns of a ``DataFrame`` regardless of data type.

        >>> df.describe(include='all')  # doctest: +SKIP
               categorical  numeric object
        count            3      3.0      3
        unique           3      NaN      3
        top              f      NaN      a
        freq             1      NaN      1
        mean           NaN      2.0    NaN
        std            NaN      1.0    NaN
        min            NaN      1.0    NaN
        25%            NaN      1.5    NaN
        50%            NaN      2.0    NaN
        75%            NaN      2.5    NaN
        max            NaN      3.0    NaN

        Describing a column from a ``DataFrame`` by accessing it as
        an attribute.

        >>> df.numeric.describe()
        count    3.0
        mean     2.0
        std      1.0
        min      1.0
        25%      1.5
        50%      2.0
        75%      2.5
        max      3.0
        Name: numeric, dtype: float64

        Including only numeric columns in a ``DataFrame`` description.

        >>> df.describe(include=[np.number])
               numeric
        count      3.0
        mean       2.0
        std        1.0
        min        1.0
        25%        1.5
        50%        2.0
        75%        2.5
        max        3.0

        Including only string columns in a ``DataFrame`` description.

        >>> df.describe(include=[object])  # doctest: +SKIP
               object
        count       3
        unique      3
        top         a
        freq        1

        Including only categorical columns from a ``DataFrame`` description.

        >>> df.describe(include=['category'])
               categorical
        count            3
        unique           3
        top              f
        freq             1

        Excluding numeric columns from a ``DataFrame`` description.

        >>> df.describe(exclude=[np.number])  # doctest: +SKIP
               categorical object
        count            3      3
        unique           3      3
        top              f      a
        freq             1      1

        Excluding object columns from a ``DataFrame`` description.

        >>> df.describe(exclude=[object])  # doctest: +SKIP
               categorical  numeric
        count            3      3.0
        unique           3      NaN
        top              f      NaN
        freq             1      NaN
        mean           NaN      2.0
        std            NaN      1.0
        min            NaN      1.0
        25%            NaN      1.5
        50%            NaN      2.0
        75%            NaN      2.5
        max            NaN      3.0
        r�rz+Cannot describe a DataFrame without columnsNg�?g�?g�?z%percentiles cannot contain duplicatescs\ddddg�dg}|j�|j�|j�|j�g|j��j�|j�g}tj|||j	d�S)N�count�mean�stdrhri)r_r�)
r�r�r�rh�quantile�tolistrirgrYr�)Zseries�
stat_indexr�)�formatted_percentiles�percentilesrorp�describe_numeric_1d's4z-NDFrame.describe.<locals>.describe_numeric_1dcsTddg}|j�}t||dk�}|j�|g}d}|ddk�r |jd|jd}}t|j��r�jdkrpd}nd}tj	dt
|d�|jj}	|j
�jjd	�}
t|�}|jdk	r�|	dk	r�|j|	�}n
|j|	�}|d
ddd
g7}|||t|
j�|	d�t|
j�|	d�g7}n|d
dg7}|||g7}n |d
dg7}|tjtjg7}d}tj|||j|d�S)Nr�r%rr\r�r�z�Treating datetime data as categorical rather than numeric in `.describe` is deprecated and will be removed in a future version of pandas. Specify `datetime_is_numeric=True` to silence this warning and adopt the future behavior now.)r��i8r�rWr�r�)r�r)r_r�r`)Zvalue_countsr�r�r_r�r2r`rar�r�r�r�r�r�rf�viewr�tzinfor�r�rhrir�rZrgrYr�)r|r�Z	objcountsZcount_uniquernr`r�rWr�r�Zasint)rjrorp�describe_categorical_1d'sB

z1NDFrame.describe.<locals>.describe_categorical_1dcsTdddg�dg}|j�|j�|j�g|j��j�|j�g}tj|||jd�S)Nr�r�rhri)r_r�)	r�r�rhr�r�rirgrYr�)r|r�r�)r�r�rorp�describe_timestamp_1dP's.z/NDFrame.describe.<locals>.describe_timestamp_1dcsVt|j�r�|�St|�r"�|�St|j�r8�r8�|�St|j�rJ�|�S�|�SdS)N)r1r`r9r2r=)r|)�datetime_is_numericr�r�r�rorp�describe_1dZ's

z%NDFrame.describe.<locals>.describe_1dr\r:)�includerz*exclude must be None when include is 'all')r��excludecsg|]\}}�|��qSroro)r�r�r�)r�rorpr�x'sz$NDFrame.describe.<locals>.<listcomp>css|]}|jVqdS)N)r_)r�rrororpr�{'sz#NDFrame.describe.<locals>.<genexpr>)r�csg|]}|j�dd��qS)F)re)r�)r�r)r�rorpr��'sF)r��sort)rar�r�r�r�r,r�r�r6r�r%r�rV�numberZ
select_dtypesr�r�rgr4re)rjr�r�r�r�Zunique_pctsZdefault_includer|r&ZldescZ
ldesc_indexesZidxnamesr�r�ro)	r�r�r�r�r�r�r�r�rjrp�describe&sXy

1







zNDFrame.describec
Ks�|j|jd|j��}|dkr"|}n |j|||d�}|dk	s>t�|}|j|jf|||d�|���d}	|dk	r�|	j|	jj	�}	|	j
|�}	|	S)a�

        Percentage change between the current and a prior element.

        Computes the percentage change from the immediately previous row by
        default. This is useful in comparing the percentage of change in a time
        series of elements.

        Parameters
        ----------
        periods : int, default 1
            Periods to shift for forming percent change.
        fill_method : str, default 'pad'
            How to handle NAs before computing percent changes.
        limit : int, default None
            The number of consecutive NAs to fill before stopping.
        freq : DateOffset, timedelta, or str, optional
            Increment to use from time series API (e.g. 'M' or BDay()).
        **kwargs
            Additional keyword arguments are passed into
            `DataFrame.shift` or `Series.shift`.

        Returns
        -------
        chg : Series or DataFrame
            The same type as the calling object.

        See Also
        --------
        Series.diff : Compute the difference of two elements in a Series.
        DataFrame.diff : Compute the difference of two elements in a DataFrame.
        Series.shift : Shift the index by some number of periods.
        DataFrame.shift : Shift the index by some number of periods.

        Examples
        --------
        **Series**

        >>> s = pd.Series([90, 91, 85])
        >>> s
        0    90
        1    91
        2    85
        dtype: int64

        >>> s.pct_change()
        0         NaN
        1    0.011111
        2   -0.065934
        dtype: float64

        >>> s.pct_change(periods=2)
        0         NaN
        1         NaN
        2   -0.055556
        dtype: float64

        See the percentage change in a Series where filling NAs with last
        valid observation forward to next valid.

        >>> s = pd.Series([90, 91, None, 85])
        >>> s
        0    90.0
        1    91.0
        2     NaN
        3    85.0
        dtype: float64

        >>> s.pct_change(fill_method='ffill')
        0         NaN
        1    0.011111
        2    0.000000
        3   -0.065934
        dtype: float64

        **DataFrame**

        Percentage change in French franc, Deutsche Mark, and Italian lira from
        1980-01-01 to 1980-03-01.

        >>> df = pd.DataFrame({
        ...     'FR': [4.0405, 4.0963, 4.3149],
        ...     'GR': [1.7246, 1.7482, 1.8519],
        ...     'IT': [804.74, 810.01, 860.13]},
        ...     index=['1980-01-01', '1980-02-01', '1980-03-01'])
        >>> df
                        FR      GR      IT
        1980-01-01  4.0405  1.7246  804.74
        1980-02-01  4.0963  1.7482  810.01
        1980-03-01  4.3149  1.8519  860.13

        >>> df.pct_change()
                          FR        GR        IT
        1980-01-01       NaN       NaN       NaN
        1980-02-01  0.013810  0.013684  0.006549
        1980-03-01  0.053365  0.059318  0.061876

        Percentage of change in GOOG and APPL stock volume. Shows computing
        the percentage change between columns.

        >>> df = pd.DataFrame({
        ...     '2016': [1769950, 30586265],
        ...     '2015': [1500923, 40912316],
        ...     '2014': [1371819, 41403351]},
        ...     index=['GOOG', 'APPL'])
        >>> df
                  2016      2015      2014
        GOOG   1769950   1500923   1371819
        APPL  30586265  40912316  41403351

        >>> df.pct_change(axis='columns')
              2016      2015      2014
        GOOG   NaN -0.151997 -0.086016
        APPL   NaN  0.337604  0.012002
        r�N)rlr�r])r�rWr�r\)r�r�r�rr��divr�r�r_Z
duplicatedr�)
rjr�Zfill_methodr]rWr�r�r|r�rrororp�
pct_change�'sz"
zNDFrame.pct_changecsr�dkrtd��|j|�dd�}t||�r>�r>t||�f��S|j���tt|�|������fdd�}|j|�S)Nz.Must specify 'axis' when aggregating by level.F)r�r�r�cs�|f��d����S)N)r��skipnaro)r)r�r�rlr�rorpr,(sz'NDFrame._agg_by_level.<locals>.<lambda>)r�rlr�r�r�rcr)rjr�r�r�r�r�ZgroupedZapplyfro)r�r�rlr�rp�
_agg_by_level(s
zNDFrame._agg_by_levelcCs.t|�\}}}t|d|||ttjttdd�
|_t|d|||ttj	t
tdd�
|_t
d|||ddd�d-d
d��}||_t|d|||d
tjd�|_t|d|||dtjd�|_t|d|||dtjd�|_t|d|||dtjjdtd�	|_t|d|||dtjdtd�	|_t|d|||dtjdtd�	|_t|d|||dtj jdt!d�	|_"t#|d|||dtj$t%t&d �	|_'t(|d!|||d"tj)d�|_*t(|d#|||d$tj+d�|_,t(|d%|||d&tj-d�|_.|j.|_/t#|d|||d'tj0t1d(�|_2|j2|_3t(|d)|||d*tj4d�|_5t(|d|||d+tj6t%t7d �	|_8t(|d|||d,tj9t%t:d �	|_;d	S).zO
        Add the operations to the cls; evaluate the doc strings again
        rF)�name1�name2�
axis_descr�descr�see_also�examples�empty_valuerTzHReturn the mean absolute deviation of the values for the requested axis.r()r�r�r�r�r�r�NcSs�|dkrd}|dkr|j}|dk	r4|jd|||d�S|j�}|dkrV||jdd�}n|j|jdd�dd�}tj|�j||d�S)	aU
            {desc}

            Parameters
            ----------
            axis : {axis_descr}
                Axis for the function to be applied on.
            skipna : bool, default None
                Exclude NA/null values when computing the result.
            level : int or level name, default None
                If the axis is a MultiIndex (hierarchical), count along a
                particular level, collapsing into a {name1}.

            Returns
            -------
            {name1} or {name2} (if level specified)            {see_also}            {examples}
            NT�mad)r�r�r�r)r�r\)r�r�)rr�r0r��subr�r)rjr�r�r�r|Zdemeanedrororpr�:(sz,NDFrame._add_numeric_operations.<locals>.mad�semz�Return unbiased standard error of the mean over requested axis.

Normalized by N-1 by default. This can be changed using the ddof argument)r�r�r�r�r�varzxReturn unbiased variance over requested axis.

Normalized by N-1 by default. This can be changed using the ddof argumentr�z�Return sample standard deviation over requested axis.

Normalized by N-1 by default. This can be changed using the ddof argument�cummin�minimumrh)r�r�r�r��
accum_func�accum_func_namer��cumsumr�cumprod�productr��cummax�maximumrizeReturn the sum of the values for the requested axis.

This is equivalent to the method ``numpy.sum``.)r�r�r�r�rr�r�r�z5Return the mean of the values for the requested axis.�skewz=Return unbiased skew over requested axis.

Normalized by N-1.�kurtz�Return unbiased kurtosis over requested axis.

Kurtosis obtained using Fisher's definition of
kurtosis (kurtosis of normal == 0.0). Normalized by N-1.z8Return the product of the values for the requested axis.)r�r�r�r�rr��medianz7Return the median of the values for the requested axis.z�Return the maximum of the values for the requested axis.

If you want the *index* of the maximum, use ``idxmax``. This isthe equivalent of the ``numpy.ndarray`` method ``argmax``.z�Return the minimum of the values for the requested axis.

If you want the *index* of the minimum, use ``idxmin``. This isthe equivalent of the ``numpy.ndarray`` method ``argmin``.)NNN)<�
_doc_parms�_make_logical_function�	_any_descrEZnanany�
_any_see_also�
_any_examplesr�	_all_descZnanall�
_all_see_also�
_all_examplesrr(r��_make_stat_function_ddofZnansemr�Znanvarr�Znanstdr��_make_cum_functionr�r��
accumulate�_cummin_examplesr�r��_cumsum_examplesr��_cumprod_examplesr��_cummax_examplesr��_make_min_count_stat_functionZnansum�_stat_func_see_also�
_sum_examplesr�_make_stat_functionZnanmeanr�Znanskewr�Znankurtr�ZkurtosisZnanprod�_prod_examplesr�r�Z	nanmedianr�Znanmax�
_max_examplesriZnanmin�
_min_examplesrh)r�r�r�r�r�rororp�_add_numeric_operations(sR

"






zNDFrame._add_numeric_operationsc
srddlm�m�m�m�t��d
��fdd�	�}||_t��d�fdd	�	�}||_t��d�fdd�	�}||_dS)zq
        Add the series or dataframe only operations to the cls; evaluate
        the doc strings again.
        r)�	Expanding�ExponentialMovingWindow�Rolling�WindowNFc
sB|j|�}|dk	r*�||||||||d�S�||||||||d�S)N)�window�min_periods�center�win_typerr�rx)r�)rjr	r
rrrr�rx)rrrorp�rolling)s(
z<NDFrame._add_series_or_dataframe_operations.<locals>.rollingr\cs8|j|�}|dk	r$tjdtdd�nd}�||||d�S)NzBThe `center` argument on `expanding` will be removed in the futurer�)r�F)r
rr�)r�r�r�r�)rjr
rr�)rrorp�	expandingB)s

z>NDFrame._add_series_or_dataframe_operations.<locals>.expandingTc

s&|j|�}�||||||||||	d�
S)N)	r��span�halflife�alphar
�adjust�	ignore_nar��times)r�)
rjr�rrrr
rrr�r)rrorp�ewmS)s
z8NDFrame._add_series_or_dataframe_operations.<locals>.ewm)NFNNrN)r\Nr)	NNNNrTFrN)	Zpandas.core.windowrrrrr(r
rr)r�r
rrro)rrrrrp�#_add_series_or_dataframe_operations)s.z+NDFrame._add_series_or_dataframe_operations)r[r�cOs6|j|f|�|�}t|�s*t|�t|�kr2td��|S)a\
        Call ``func`` on self producing a {klass} with transformed values.

        Produced {klass} will have same axis length as self.

        Parameters
        ----------
        func : function, str, list or dict
            Function to use for transforming the data. If a function, must either
            work when passed a {klass} or when passed to {klass}.apply.

            Accepted combinations are:

            - function
            - string function name
            - list of functions and/or function names, e.g. ``[np.exp. 'sqrt']``
            - dict of axis labels -> functions, function names or list of such.
        {axis}
        *args
            Positional arguments to pass to `func`.
        **kwargs
            Keyword arguments to pass to `func`.

        Returns
        -------
        {klass}
            A {klass} that must have the same length as self.

        Raises
        ------
        ValueError : If the returned {klass} has a different length than self.

        See Also
        --------
        {klass}.agg : Only perform aggregating type operations.
        {klass}.apply : Invoke function on a {klass}.

        Examples
        --------
        >>> df = pd.DataFrame({{'A': range(3), 'B': range(1, 4)}})
        >>> df
           A  B
        0  0  1
        1  1  2
        2  2  3
        >>> df.transform(lambda x: x + 1)
           A  B
        0  1  2
        1  2  3
        2  3  4

        Even though the resulting {klass} must have the same length as the
        input {klass}, it is possible to provide several input functions:

        >>> s = pd.Series(range(3))
        >>> s
        0    0
        1    1
        2    2
        dtype: int64
        >>> s.transform([np.sqrt, np.exp])
               sqrt        exp
        0  0.000000   1.000000
        1  1.000000   2.718282
        2  1.414214   7.389056
        z,transforms cannot produce aggregated results)Zaggr<r�r�)rjrr�r�rnrororp�	transformp)sDzNDFrame.transform)rmcCs"t|j|�}|dkrdS|j|S)a
        Retrieves the index of the first valid value.

        Parameters
        ----------
        how : {'first', 'last'}
            Use this parameter to change between the first or last valid index.

        Returns
        -------
        idx_first_valid : type of index
        N)rQrr_)rjrmZidxposrororp�_find_valid_index�)s
zNDFrame._find_valid_indexr�)�positionr[cCs
|jd�S)a
        Return index for {position} non-NA/null value.

        Returns
        -------
        scalar : type of index

        Notes
        -----
        If all elements are non-NA/null, returns None.
        Also returns None for empty {klass}.
        r�)r)rjrororp�first_valid_index�)szNDFrame.first_valid_indexcCs
|jd�S)Nr�)r)rjrororp�last_valid_index�)szNDFrame.last_valid_index)FN)NF)N)FN)rF)T)r)N)N)reT)rmF)rF)r)r)r)r)r)r)r)N)N)rWr(NNTTNrrNTNrXTN)NNNrmTrnNFroTN)r�NNFNTNNNNr{r|)Nr�TNNNN)TN)NNNTTr�NNNTFNNNNr�NNNNN)NrBr(NNTTNr�NroNr�NNNTNr�r{)FT)rN)r)rNT)r)T)r�r�F)N)NTNN)NrNNNFr�)Nr�)T)rTFr�r�FN)NFF)NNNN)r�)r�)NNFNNN)N)F)T)Tr�)T)T)N)FFFF)TTTT)NNNFNN)NFNN)NFNN)NNFNFrK)rNrNFNNN)N)F)NNNF)NNFN)FN)TTN)rNNr^NNNNNrwN)rr�Nr�TF)r\FF)	r�NNTNNNrN)r�NNTNNNr)r�NNTNNNr)r\NrN)r\r)r\Nr)NNNT)rNT)rNTr�r�)NNNF)r\rKNN)rrT(rd�
__module__�__qualname__�__doc__r=r
r�r<rrr�	frozensetZ
_deprecationsrrzrwrPrsrrr	rr~r9rrr��classmethodr��propertyr}�setterr�rrr�r�r�r�rr�Z_ixr�r�rr�r�rTr�r�r�r�r�r�r�r�rIr�r�r@r�r�r�r�r�rr�rZrar�r�r�r�r�r�r�rrr�r�rrr�r)rr�rrrrrrrr�__bool__rrr�bool_trr!r'r�r�r*r,r.r0rr�r(r2r3r4r5Z__array_priority__r7rr;r@rHrKrVrlrrrrRr�r��pickle�HIGHEST_PROTOCOLr�r�r�r'�fmtZreturn_docstringrJr
r�r�r�r�r�r�r�r�r�r�r)r�r�r�r�r�r�r�r�r�r�r�r�r�r+r�rir�r�r r��_shared_doc_kwargsr�r�r�r�r�rrOr
rrrrSrhrr�r'r*r�r-r�r/r0r1rfrr2r3r�rer7r9r>r?rDrrIrKrJrQrrGr_rBr`rCrardrgrkrorqrvrrr�r�r�r�r&r�r�r�r�rZr�rHr^r�r�r{r�r�r�rr�r�r�rrrrrr�
__classcell__roro)r)rprr�s\

&
	"@t,%.>Z	,+CP

6
%
<
P
8;S
�%#a#
L&j5;= zw	
"`HLI6')L
$m#17

M$!(>><i<
P.DA?w:P
y
&
*:
%Gva M"rrcCsHddjdd�t|j�D���d�}|jdkr4|jjnd}|j}|||fS)z Return a tuple of the doc parms.�{z, css"|]\}}|�d|�d�VqdS)z (rENro)r�r�r�rororpr��)sz_doc_parms.<locals>.<genexpr>�}r\Zscalar)rFr�r�r�r�rd)r�r�r�r�rororpr��)s"r�a�
%(desc)s

Parameters
----------
axis : %(axis_descr)s
    Axis for the function to be applied on.
skipna : bool, default True
    Exclude NA/null values when computing the result.
level : int or level name, default None
    If the axis is a MultiIndex (hierarchical), count along a
    particular level, collapsing into a %(name1)s.
numeric_only : bool, default None
    Include only float, int, boolean columns. If None, will attempt to use
    everything, then use only numeric data. Not implemented for Series.
%(min_count)s**kwargs
    Additional keyword arguments to be passed to the function.

Returns
-------
%(name1)s or %(name2)s (if level specified)%(see_also)s%(examples)s
a�
%(desc)s

Parameters
----------
axis : %(axis_descr)s
skipna : bool, default True
    Exclude NA/null values. If an entire row/column is NA, the result
    will be NA.
level : int or level name, default None
    If the axis is a MultiIndex (hierarchical), count along a
    particular level, collapsing into a %(name1)s.
ddof : int, default 1
    Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
    where N represents the number of elements.
numeric_only : bool, default None
    Include only float, int, boolean columns. If None, will attempt to use
    everything, then use only numeric data. Not implemented for Series.

Returns
-------
%(name1)s or %(name2)s (if level specified)
a�
%(desc)s

Parameters
----------
axis : {0 or 'index', 1 or 'columns', None}, default 0
    Indicate which axis or axes should be reduced.

    * 0 / 'index' : reduce the index, return a Series whose index is the
      original column labels.
    * 1 / 'columns' : reduce the columns, return a Series whose index is the
      original index.
    * None : reduce all axes, return a scalar.

bool_only : bool, default None
    Include only boolean columns. If None, will attempt to use everything,
    then use only boolean data. Not implemented for Series.
skipna : bool, default True
    Exclude NA/null values. If the entire row/column is NA and skipna is
    True, then the result will be %(empty_value)s, as for an empty row/column.
    If skipna is False, then NA are treated as True, because these are not
    equal to zero.
level : int or level name, default None
    If the axis is a MultiIndex (hierarchical), count along a
    particular level, collapsing into a %(name1)s.
**kwargs : any, default None
    Additional keywords have no effect but might be accepted for
    compatibility with NumPy.

Returns
-------
%(name1)s or %(name2)s
    If level is specified, then, %(name2)s is returned; otherwise, %(name1)s
    is returned.

%(see_also)s
%(examples)sz�Return whether all elements are True, potentially over an axis.

Returns True unless there at least one element within a series or
along a Dataframe axis that is False or equivalent (e.g. zero or
empty).a�Examples
--------
**Series**

>>> pd.Series([True, True]).all()
True
>>> pd.Series([True, False]).all()
False
>>> pd.Series([]).all()
True
>>> pd.Series([np.nan]).all()
True
>>> pd.Series([np.nan]).all(skipna=False)
True

**DataFrames**

Create a dataframe from a dictionary.

>>> df = pd.DataFrame({'col1': [True, True], 'col2': [True, False]})
>>> df
   col1   col2
0  True   True
1  True  False

Default behaviour checks if column-wise values all return True.

>>> df.all()
col1     True
col2    False
dtype: bool

Specify ``axis='columns'`` to check if row-wise values all return True.

>>> df.all(axis='columns')
0     True
1    False
dtype: bool

Or ``axis=None`` for whether every value is True.

>>> df.all(axis=None)
False
z�See Also
--------
Series.all : Return True if all elements are True.
DataFrame.any : Return True if one (or more) elements are True.
a;
Return cumulative %(desc)s over a DataFrame or Series axis.

Returns a DataFrame or Series of the same size containing the cumulative
%(desc)s.

Parameters
----------
axis : {0 or 'index', 1 or 'columns'}, default 0
    The index or the name of the axis. 0 is equivalent to None or 'index'.
skipna : bool, default True
    Exclude NA/null values. If an entire row/column is NA, the result
    will be NA.
*args, **kwargs
    Additional keywords have no effect but might be accepted for
    compatibility with NumPy.

Returns
-------
%(name1)s or %(name2)s
    Return cumulative %(desc)s of %(name1)s or %(name2)s.

See Also
--------
core.window.Expanding.%(accum_func_name)s : Similar functionality
    but ignores ``NaN`` values.
%(name2)s.%(accum_func_name)s : Return the %(desc)s over
    %(name2)s axis.
%(name2)s.cummax : Return cumulative maximum over %(name2)s axis.
%(name2)s.cummin : Return cumulative minimum over %(name2)s axis.
%(name2)s.cumsum : Return cumulative sum over %(name2)s axis.
%(name2)s.cumprod : Return cumulative product over %(name2)s axis.

%(examples)sa�Examples
--------
**Series**

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

By default, NA values are ignored.

>>> s.cummin()
0    2.0
1    NaN
2    2.0
3   -1.0
4   -1.0
dtype: float64

To include NA values in the operation, use ``skipna=False``

>>> s.cummin(skipna=False)
0    2.0
1    NaN
2    NaN
3    NaN
4    NaN
dtype: float64

**DataFrame**

>>> df = pd.DataFrame([[2.0, 1.0],
...                    [3.0, np.nan],
...                    [1.0, 0.0]],
...                    columns=list('AB'))
>>> df
     A    B
0  2.0  1.0
1  3.0  NaN
2  1.0  0.0

By default, iterates over rows and finds the minimum
in each column. This is equivalent to ``axis=None`` or ``axis='index'``.

>>> df.cummin()
     A    B
0  2.0  1.0
1  2.0  NaN
2  1.0  0.0

To iterate over columns and find the minimum in each row,
use ``axis=1``

>>> df.cummin(axis=1)
     A    B
0  2.0  1.0
1  3.0  NaN
2  1.0  0.0
a�Examples
--------
**Series**

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

By default, NA values are ignored.

>>> s.cumsum()
0    2.0
1    NaN
2    7.0
3    6.0
4    6.0
dtype: float64

To include NA values in the operation, use ``skipna=False``

>>> s.cumsum(skipna=False)
0    2.0
1    NaN
2    NaN
3    NaN
4    NaN
dtype: float64

**DataFrame**

>>> df = pd.DataFrame([[2.0, 1.0],
...                    [3.0, np.nan],
...                    [1.0, 0.0]],
...                    columns=list('AB'))
>>> df
     A    B
0  2.0  1.0
1  3.0  NaN
2  1.0  0.0

By default, iterates over rows and finds the sum
in each column. This is equivalent to ``axis=None`` or ``axis='index'``.

>>> df.cumsum()
     A    B
0  2.0  1.0
1  5.0  NaN
2  6.0  1.0

To iterate over columns and find the sum in each row,
use ``axis=1``

>>> df.cumsum(axis=1)
     A    B
0  2.0  3.0
1  3.0  NaN
2  1.0  1.0
a�Examples
--------
**Series**

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

By default, NA values are ignored.

>>> s.cumprod()
0     2.0
1     NaN
2    10.0
3   -10.0
4    -0.0
dtype: float64

To include NA values in the operation, use ``skipna=False``

>>> s.cumprod(skipna=False)
0    2.0
1    NaN
2    NaN
3    NaN
4    NaN
dtype: float64

**DataFrame**

>>> df = pd.DataFrame([[2.0, 1.0],
...                    [3.0, np.nan],
...                    [1.0, 0.0]],
...                    columns=list('AB'))
>>> df
     A    B
0  2.0  1.0
1  3.0  NaN
2  1.0  0.0

By default, iterates over rows and finds the product
in each column. This is equivalent to ``axis=None`` or ``axis='index'``.

>>> df.cumprod()
     A    B
0  2.0  1.0
1  6.0  NaN
2  6.0  0.0

To iterate over columns and find the product in each row,
use ``axis=1``

>>> df.cumprod(axis=1)
     A    B
0  2.0  2.0
1  3.0  NaN
2  1.0  0.0
a�Examples
--------
**Series**

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

By default, NA values are ignored.

>>> s.cummax()
0    2.0
1    NaN
2    5.0
3    5.0
4    5.0
dtype: float64

To include NA values in the operation, use ``skipna=False``

>>> s.cummax(skipna=False)
0    2.0
1    NaN
2    NaN
3    NaN
4    NaN
dtype: float64

**DataFrame**

>>> df = pd.DataFrame([[2.0, 1.0],
...                    [3.0, np.nan],
...                    [1.0, 0.0]],
...                    columns=list('AB'))
>>> df
     A    B
0  2.0  1.0
1  3.0  NaN
2  1.0  0.0

By default, iterates over rows and finds the maximum
in each column. This is equivalent to ``axis=None`` or ``axis='index'``.

>>> df.cummax()
     A    B
0  2.0  1.0
1  3.0  NaN
2  3.0  1.0

To iterate over columns and find the maximum in each row,
use ``axis=1``

>>> df.cummax(axis=1)
     A    B
0  2.0  2.0
1  3.0  NaN
2  1.0  1.0
a2See Also
--------
numpy.any : Numpy version of this method.
Series.any : Return whether any element is True.
Series.all : Return whether all elements are True.
DataFrame.any : Return whether any element is True over requested axis.
DataFrame.all : Return whether all elements are True over requested axis.
z�Return whether any element is True, potentially over an axis.

Returns False unless there at least one element within a series or
along a Dataframe axis that is True or equivalent (e.g. non-zero or
non-empty).aKExamples
--------
**Series**

For Series input, the output is a scalar indicating whether any element
is True.

>>> pd.Series([False, False]).any()
False
>>> pd.Series([True, False]).any()
True
>>> pd.Series([]).any()
False
>>> pd.Series([np.nan]).any()
False
>>> pd.Series([np.nan]).any(skipna=False)
True

**DataFrame**

Whether each column contains at least one True element (the default).

>>> df = pd.DataFrame({"A": [1, 2], "B": [0, 2], "C": [0, 0]})
>>> df
   A  B  C
0  1  0  0
1  2  2  0

>>> df.any()
A     True
B     True
C    False
dtype: bool

Aggregating over the columns.

>>> df = pd.DataFrame({"A": [True, False], "B": [1, 2]})
>>> df
       A  B
0   True  1
1  False  2

>>> df.any(axis='columns')
0    True
1    True
dtype: bool

>>> df = pd.DataFrame({"A": [True, False], "B": [1, 0]})
>>> df
       A  B
0   True  1
1  False  0

>>> df.any(axis='columns')
0    True
1    False
dtype: bool

Aggregating over the entire DataFrame with ``axis=None``.

>>> df.any(axis=None)
True

`any` for an empty DataFrame is an empty Series.

>>> pd.DataFrame([]).any()
Series([], dtype: bool)
a�

Examples
--------
>>> idx = pd.MultiIndex.from_arrays([
...     ['warm', 'warm', 'cold', 'cold'],
...     ['dog', 'falcon', 'fish', 'spider']],
...     names=['blooded', 'animal'])
>>> s = pd.Series([4, 2, 0, 8], name='legs', index=idx)
>>> s
blooded  animal
warm     dog       4
         falcon    2
cold     fish      0
         spider    8
Name: legs, dtype: int64

>>> s.{stat_func}()
{default_output}

{verb} using level names, as well as indices.

>>> s.{stat_func}(level='blooded')
blooded
warm    {level_output_0}
cold    {level_output_1}
Name: legs, dtype: int64

>>> s.{stat_func}(level=0)
blooded
warm    {level_output_0}
cold    {level_output_1}
Name: legs, dtype: int64Zstat_func_examplerZSum���)�	stat_funcZverbZdefault_outputZlevel_output_0Zlevel_output_1a�

By default, the sum of an empty or all-NA Series is ``0``.

>>> pd.Series([]).sum()  # min_count=0 is the default
0.0

This can be controlled with the ``min_count`` parameter. For example, if
you'd like the sum of an empty series to be NaN, pass ``min_count=1``.

>>> pd.Series([]).sum(min_count=1)
nan

Thanks to the ``skipna`` parameter, ``min_count`` handles all-NA and
empty series identically.

>>> pd.Series([np.nan]).sum()
0.0

>>> pd.Series([np.nan]).sum(min_count=1)
nanriZMaxr�rhZMinr�a

See Also
--------
Series.sum : Return the sum.
Series.min : Return the minimum.
Series.max : Return the maximum.
Series.idxmin : Return the index of the minimum.
Series.idxmax : Return the index of the maximum.
DataFrame.sum : Return the sum over the requested axis.
DataFrame.min : Return the minimum over the requested axis.
DataFrame.max : Return the maximum over the requested axis.
DataFrame.idxmin : Return the index of the minimum over the requested axis.
DataFrame.idxmax : Return the index of the maximum over the requested axis.a�

Examples
--------
By default, the product of an empty or all-NA Series is ``1``

>>> pd.Series([]).prod()
1.0

This can be controlled with the ``min_count`` parameter

>>> pd.Series([]).prod(min_count=1)
nan

Thanks to the ``skipna`` parameter, ``min_count`` handles all-NA and
empty series identically.

>>> pd.Series([np.nan]).prod()
1.0

>>> pd.Series([np.nan]).prod(min_count=1)
nanakmin_count : int, default 0
    The required number of valid values to perform the operation. If fewer than
    ``min_count`` non-NA values are present the result will be NA.

    .. versionadded:: 0.22.0

       Added with the default being 0. This means the sum of an all-NA
       or empty Series is 0, and the product of an all-NA or empty
       Series is 1.
r()	r�r�r�r�r�rr�r�r�c	
	s:t||||t||d�tt�d��fdd�	��}	t|	�|�S)N)r�r�r�r��	min_countr�r�rcs��dkrtjt�|�n*�dkr0tjt�|�ntjt�|�d�|dkrNd}|dkr\|j}|dk	rx|j�||||d�S|j��||||d�S)Nrr�)�fnameT)r�r�r�r0)r�r�r�r�r0)r�Zvalidate_sumr�Z
validate_prod�validate_stat_funcrr��_reduce)rjr�r�r�r�r0r�)rr�rorpr/�,s&z0_make_min_count_stat_function.<locals>.stat_func)NNNNr)r'�_min_count_stubr&�_num_docr!)
r�r�r�r�r�r�rr�r�r/ro)rr�rpr�x,sr�c	
	s:t||||d||d�tt�d��fdd�	��}	t|	�|�S)Nr()r�r�r�r�r0r�r�csr�dkrtjt�|�ntjt�|�d�|dkr6d}|dkrD|j}|dk	r^|j�|||d�S|j��|||d�S)Nr�)r1T)r�r�r�)r�r�r�r�)r�Zvalidate_medianr�r2rr�r3)rjr�r�r�r�r�)rr�rorpr/�,s
z&_make_stat_function.<locals>.stat_func)NNNN)r'r&r5r!)
r�r�r�r�r�r�rr�r�r/ro)rr�rpr�,sr)r�r�r�r�r�rr�cs4t||||d�tt�d��fdd�	��}t|�|�S)N)r�r�r�r�r\cs^tjt�|�d�|dkrd}|dkr,|j}|dk	rH|j�||||d�S|j��||||d�S)N)r1T)r�r�r��ddof)r�r�r�r6)r�Zvalidate_stat_ddof_funcr�rr�r3)rjr�r�r�r6r�r�)rr�rorpr/�,sz+_make_stat_function_ddof.<locals>.stat_func)NNNr\N)r'r&�
_num_ddof_docr!)r�r�r�r�r�r�rr/ro)rr�rpr��,sr�)	r�r�r�r�r�r�r�r�r�c		s:t||||||d�tt�d���fdd�	���t��|�S)N)r�r�r�r�r�r�Tcs~tj�||���|dkr |j}n
|j|�}|dkrP�|jf|�d�d�|��jS��fdd�}|jj|�}|j|�j|�d�S)Nr\r)r�r�cs<t|d�r|jn|}tj|��d�}t|d�r4|jn|}|S)NrF)r�)r�rFrEZ
na_accum_func)Z
blk_valuesrfrn)r�r�rorp�block_accum_func-sz>_make_cum_function.<locals>.cum_func.<locals>.block_accum_func)rl)	r�Zvalidate_cum_func_with_skipnarr�rFrsrr�rh)rjr�r�r�r�r8rn)r��cum_funcr�)r�rpr9�,s

z$_make_cum_function.<locals>.cum_func)NT)r'r&�	_cnum_docr!)	r�r�r�r�r�r�r�r�r�ro)r�r9r�rpr��,sr�)
r�r�r�r�r�rr�r�r�r�c
	s:t|||||||	d�tt�d��fdd�	��}
t|
�|�S)N)r�r�r�r�r�r�r�rTcsRtjt�|�d�|dk	r<|dk	r*td��|j�|||d�S|j��|||dd�S)N)r1z6Option bool_only is not implemented with option level.)r�r�r�r)r�r�r�r�Zfilter_type)r�Zvalidate_logical_funcr�r�r�r3)rjr�Z	bool_onlyr�r�r�)rr�rorp�logical_func*-sz,_make_logical_function.<locals>.logical_func)rNTN)r'r&�	_bool_docr!)r�r�r�r�r�r�rr�r�r�r;ro)rr�rpr�-sr�)r(r()r(r()�rSr:rr�r�rPr	r%r�textwraprZtypingrrrrrr	r
rrr
rrrrr�r�Znumpyr�Zpandas._configrZpandas._libsrZpandas._libs.tslibsrrrZpandas._typingrrrrrrrrrr Z
pandas.compatr!Zpandas.compat._optionalr"Zpandas.compat.numpyr#r�Z
pandas.errorsr$r%Zpandas.util._decoratorsr&r'r(r)Zpandas.util._validatorsr*r+r,Zpandas.core.dtypes.commonr-r.r/r0r1r2r3r4r5r6r7r8r9r:r;r<r=r>Zpandas.core.dtypes.genericr?r@Zpandas.core.dtypes.inferencerAZpandas.core.dtypes.missingrBrCZpandasrgZpandas.corerDrEZpandas.core.algorithms�coreZ
algorithmsr�Zpandas.core.baserFrGZpandas.core.common�commonr�Zpandas.core.constructionrHZpandas.core.indexes.apirIrJrKrLZpandas.core.indexes.datetimesrMZpandas.core.indexes.periodrNrOZpandas.core.indexingZindexingZpandas.core.internalsrPZpandas.core.missingrQZpandas.core.opsrRZpandas.core.shared_docsrSZpandas.io.formatsrTr'Zpandas.io.formats.formatrUrVZpandas.io.formats.printingrWrprXZpandas.core.seriesrYr�r(rqrr$Z
IndexingMixinrrr�r5r7r<r�r�r�r:r�r�r�r�r�r�r�r�rrr�rr4r�r�rr�r�r�rorororp�<module>s�@0P"&.#AAAA
F$6 %