
    Piw                      U d dl mZ d dlZd dlmZ d dlZd dlmZ d dl	m
Z
 d dlZd dlZd dlZd dlZd dlmZmZmZmZmZmZmZmZmZmZ d dlZd dlZd dlmZ d dlm Z  d d	l!m"Z" d d
l#m$Z$m%Z%m&Z& d dl'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZT d dlUmVZV d dlWmXZX d dlYmZZZ d dl[m\Z] d dl^m_Z_m`Z`maZambZb d dlcmdZd d dlemfZfmgZg d dlhmiZi d dljmkZkmlZlmmZmmnZn d dlompZp d dlqmrZr d dlsmtZtmuZumvZvmwZwmxZxmyZymzZzm{Z{m|Z|m}Z}m~Z~mZmZ d dlmZmZmZ d dlmZmZ d dlmZmZ d dlmZmZ d dlmZmZmZmZmZmZmZ d dlmZ d dlmZ d dlmZ d d lmZ d d!lmZ d d"lmZmZmZmZmZmZ d d#lmZ d d$lmZ d d%lmZmZmZ d d&lmZ d d'lmZ d d(lmZ d d)lmZmZmZmZ d d*lmZmZ d d+lmZ er2d d,lmZmZmZmZmZ d d-l#mZ d d.l'mZ d d/lmZmZmZmZ d d0lmZ d d1lmZ i eZd2d3d4d5d6d7Z G d8 d9eej                  Zd:Zd;Zd<Zd=Zd>Zd?Zd@ZdAZdBZdCZdDZdEZdFZdGZdHZdIZdJZdKZdLZdMZdNZdOZdPZdQedR<   edR                             dSdTdUdVdWX          ZedYz  ZedR                             dZd[dWd\dWX          Zd]ed^<   edR                             d_d`d dad X          Zd]edb<   dcZddZdeZdfZdldkZdS )m    )annotationsN)deepcopypartial)loads)
TYPE_CHECKINGAnyClassVarConcatenateLiteralNoReturnSelfcastfinaloverload)config)lib)is_range_indexer)Period	Timestamp	to_offset)-	AlignJoinAnyArrayLike	ArrayLikeAxesAxisAxisIntCompressionOptionsDtypeArgDtypeBackendDtypeObjFilePathFillnaOptionsFloatFormatTypeFormattersType	FrequencyIgnoreRaiseIndexKeyFunc
IndexLabelInterpolateOptionsIntervalClosedTypeJSONSerializableLevelListLikeManager
NaPositionNDFrameTOpenFileErrorsRandomStateReindexMethodRenamerScalarSequenceNotStrSortKindStorageOptionsSuffixesTTimeAmbiguousTimedeltaConvertibleTypesTimeNonexistentTimestampConvertibleTypesTimeUnitValueKeyFuncWriteBufferWriteExcelBuffernpt)CHAINED_WARNING_DISABLED)REF_COUNT_METHOD)import_optional_dependency)function)AbstractMethodErrorChainedAssignmentErrorInvalidIndexErrorPandas4Warning)_chained_assignment_method_msg)deprecate_kwargdoc)find_stack_level)check_dtype_backendvalidate_ascendingvalidate_bool_kwargvalidate_inclusive)astype_is_view)can_hold_element)ensure_objectensure_platform_int
ensure_stris_boolis_bool_dtypeis_dict_likeis_extension_array_dtypeis_list_like	is_numberis_numeric_dtypeis_re_compilable	is_scalarpandas_dtype)DatetimeTZDtypeExtensionDtypePeriodDtype)ABCDataFrame	ABCSeries)is_hashableis_nested_list_like)isnanotna)
algorithms	arraylikecommonindexingmissingnanopssample)should_use_regex)ExtensionArray)PandasObject)extract_array)Flags)DatetimeIndexIndex
MultiIndexPeriodIndexdefault_indexensure_index)BlockManager)describe_ndframe)clean_fill_methodclean_reindex_fill_methodfind_valid_index)concat)_shared_docs)get_indexer_indexer)	ExpandingExponentialMovingWindowRollingWindow)DataFrameFormatterDataFrameRenderer)pprint_thing)CallableHashableIteratorMappingSequence)
BaseOffset)P)	DataFrameExcelWriterHDFStoreSeries)BaseIndexer)	Resamplerzkeywords for axeszSeries/DataFramezG{0 or 'index'} for Series, {0 or 'index', 1 or 'columns'} for DataFramezO
    inplace : bool, default False
        If True, performs operation inplace.zM
        by : str or list of str
            Name or list of names to sort by)axesklassaxes_single_arginplaceoptional_byc                      e Zd ZU dZg dZded<    ee          Zded<    e            Zded<    e	g           Z
ded	<   g Zded
<   ded<   ded<   ded<   djdZee	 	 dkdld                        Zeedmd!                        Zednd"            Zej        dod%            Zeedpd'                        Zeej        dd(dqd,            Zeedrd-                        Zedsd/            Zd0ed1<   d2d2d2d3Zd4ed5<   d6ed7<   d8ed9<   d6ed:<   e	 dtdud?            ZeedvdB                        ZeedwdC                        ZedxdE            ZeedvdF                        ZedydH            Z edzdJ            Z!ed{dL            Z"eed|dM                        Z#ed}dO            Z$ed~dP            Z%eeddQ                        Z&eeddR                        Z'd2ej        dSddTZ(e)ddW            Z*e)ddY            Z*e)dd[            Z*edd\            Z*edd_            Z+edddb            Z,ddfZ-edtddi            Z.e)	 ddjdjdjdjdjdjdkddr            Z/e)	 ddjdjdjdjdjdsddt            Z/e)	 ddjdjdjdjdjdsddu            Z/e	 dtddddddvdkddw            Z/e)	 ddjdjdjej        djdxddz            Z0e)	 ddjdjdjej        d{dd|            Z0e)	 ddjdjdjej        djdxdd}            Z0ej        fej        ej        d2ej        ddxdd~Z0e)	 ddjddd            Z1e)	 ddd            Z1e)	 ddd            Z1e	 ddddd            Z1edd            Z2edd            Z3edd            Z4edd            Z5edd            Z6edd            Z7edd            Z8edd            Z9eddd            Z:eddd            Z;eddd            Z<eddd            Z=eddd            Z>eddd            Z?eddd            Z@ded<   ddZAd|dZBd ZCddZDedd            ZEedd            ZFdZGd6ed<   	 dddZHedd            ZIedd            ZJedd            ZKddZLed             ZMed             ZNedddddddd2d2ddddddddddф            ZOe	 dtddddddddddddd֜dd            ZPeddddddddddddddd            ZQedddddddddd            ZRedeSjT        dddd            ZUeddddd            ZVed             ZWe)	 ddjdjdjdjdjdjdjdjdjdjdjdjdjdjdjdjdjdjdjdjddd&            ZXe)djdjdjdjdjdjdjdjdjdjdjdjdjdjdjdjdjdjdjdjddd(            ZXe	 dtdddd)dddddddddd*ddddddddd,            ZXe	 dtddddddd-dd5            ZYe)	 ddjdjdjdjdjdjdjdjdjdjdjdjdjdjdjdjdjdjdjdjd6dd?            ZZe)djdjdjdjdjdjdjdjdjdjdjdjdjdjdjdjdjdjdjdjd6ddA            ZZe	 dtdBdddddddddddCdddddd*ddd6ddD            ZZedddE            Z[e	 	 	 dddG            Z\dH Z]eddJ            Z^dddLZ_eddM            Z`eddN            ZaedtdO            ZbecdP             Zd eeefddQ          edej        ddfddT                        Zge)	 ddjdjdjdjdjdUddX            Zhe)	 ddjdjdjdjdjdjdYddZ            Zhe)	 ddjdjdjdjdjdjdYdd[            Zh	 dtd2ddddd\dYdd]Zhe	 	 	 ddd_            Ziedd`            Zjedtddb            Zkedtddd            Zle)djdjdjdjdjdjdjdeddn            Zme)djdjdjdjdjdjdoddp            Zme)djdjdjdjdjdjdjdeddq            Zmd2dddrdsdddedduZme)djdjdjdjdjdjdjdjdvddy            Zne)djdjdjdjdjdjdjdjdjdz	dd{            Zne)djdjdjdjdjdjdjdjdjdz	dd|            Znd2ddddrdsddddz	dÐd~Zn	 dtddddej        deojp        ddd	dĐdZqedŐd            ZrdƐdZsd Zte	 	 dkdǐd            Zu	 	 	 	 dȐdɐdZvedʐdːd            Zwedʐdːd            Zxe	 	 	 	 	 	 	 d̐d͐d            Zye)dΐd            Zze)dϐd            ZzedАd            Zzedtdѐd            Z{edҐd            Z|edӐd            Z}edԈ fd            Z~edd            Zed             Zeedd                        Zedd            Zed             Zed             ZedՐd            Zed             Zeej        d\fd֐d            Zedאdؐd            Zedd            Zedtdd            Zeej        fdِd            Ze	 	 	 	 	 	 dڐdېd            Zeddddddܐd            ZeddddÜdݐdń            ZeddddddސdƄ            ZeddddddސdǄ            Zedej        fdddȜdߐdɄ            Ze	 dd2ddddd˜ddτ            ZedtdЄ            ZddфZdd҄ZddӄZddԄZedddՄ            Zedք             Ze	 	 ddddלdd؄            Ze	 	 	 	 ddd            Zeddd            Ze	 	 ddd            Ze	 	 	 	 	 	 	 	 ddd            Ze	 	 	 	 	 	 ddd            Z	 	 	 	 dddZedddej        dfdd
            Ze	 	 	 	 ddd            Ze	 	 	 	 ddd            Zeej        fdddddd            Zeej        fdddddd            Zeej        fdddddd            Zddd2ej        dfddZedd            Zedddej        fdd            Zed2dej        fdd            Zed2dej        d\d\fdd             Ze	 	 	 ddd!            Ze	 	 	 ddd#            Ze	 	 	 ddd'            Zd2ddd(d d)Zd2ddd(dd*Ze	 	 ddd+            Zddd,Zddd-Zddd.Zddd/Ze	 	 	 	 ddd2            Zd2dddd3dd4Zd2dddd3dd5Zd2dddd3dd6Ze	 	 	 d	d
d7            Zd2ddd8dd9Zd2ddd8dd:Zd2ddd8dd;Zd2ddd8dd<Zd2ddd8dd=Zd2ddd8dd>ZeZe	 	 	 	 ddd@            Zd2ddd2dAddBZd2ddd2dAddCZeZe	 	 	 	 	 	 	 dddM            Ze	 	 dddP            Ze eeɦ          	 	 	 	 	 	 	 	 	 ddd[                        Zedd\            Zedd]            Zedd^            Zedd_            Zedd`            Zedda            Zeddb            Zeddc            Zeddd            Zedde            Zeddf            Zeddg            Zeddh            Zeddi            Z؈ xZS (  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_cache_name	_metadata_flagsz	list[str]_internal_namesset[str]_internal_names_set
_accessorszfrozenset[str]_hidden_attrsr   r/   r   dict[Hashable, Any]_attrsstr_typdatareturnNonec                    t                               | d|           t                               | di            t                               | dt          | d                     d S )Nr   r   r   T)allows_duplicate_labels)object__setattr__rx   selfr   s     g/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/pandas/core/generic.py__init__zNDFrame.__init__  s]    4...42...45t+T+T+TUUUUU    NFmgrr   .dict[Literal['index', 'columns'], Axes | None]dtypeDtypeObj | Nonecopyboolc                   |                                 D ]B\  }}|;t          |          }|                     |          }|                    ||          }C|r|                    d          }|_t          |t                    r4t          |j                  dk    r|j        d         j	        j
        |k    rn|                    |          }|S )z passed a manager and a axes dictNaxisTdeep   r   r   )itemsr~   _get_block_manager_axisreindex_axisr   
isinstancer   lenblocksvaluesr   astype)clsr   r   r   r   aaxebm_axiss           r   	_init_mgrzNDFrame._init_mgr  s     jjll 	: 	:FAs"3''55a88&&s&99  	&(((%%C 3--.
OOq((JqM(.%77jjuj--
r   list[Index]r   c                f    |                      |           }t                              ||           |S )a  
        Construct a new object of this type from a Manager object and axes.

        Parameters
        ----------
        mgr : Manager
            Must have the same ndim as cls.
        axes : list[Index]

        Notes
        -----
        The axes must match mgr.axes, but are required for future-proofing
        in the event that axes are refactored out of the Manager objects.
        )__new__r   r   )r   r   r   objs       r   	_from_mgrzNDFrame._from_mgr&  s0    " kk#c"""
r   c                    | j         S )a  
        Dictionary of global attributes of this dataset.

        .. warning::

           attrs is experimental and may change without warning.

        See Also
        --------
        DataFrame.flags : Global flags applying to this object.

        Notes
        -----
        Many operations that create new datasets will copy ``attrs``. Copies
        are always deep so that changing ``attrs`` will only affect the
        present dataset. :func:`pandas.concat` and :func:`pandas.merge` will
        only copy ``attrs`` if all input datasets have the same ``attrs``.

        Examples
        --------
        For Series:

        >>> ser = pd.Series([1, 2, 3])
        >>> ser.attrs = {"A": [10, 20, 30]}
        >>> ser.attrs
        {'A': [10, 20, 30]}

        For DataFrame:

        >>> df = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
        >>> df.attrs = {"A": [10, 20, 30]}
        >>> df.attrs
        {'A': [10, 20, 30]}
        )r   r   s    r   attrszNDFrame.attrs>  s    H {r   valueMapping[Hashable, Any]c                .    t          |          | _        d S N)dictr   )r   r   s     r   r   zNDFrame.attrsd  s    5kkr   rx   c                    | j         S )a  
        Get the properties associated with this pandas object.

        The available flags are

        * :attr:`Flags.allows_duplicate_labels`

        See Also
        --------
        Flags : Flags that apply to pandas objects.
        DataFrame.attrs : Global metadata applying to this dataset.

        Notes
        -----
        "Flags" differ from "metadata". Flags reflect properties of the
        pandas object (the Series or DataFrame). Metadata refer to properties
        of the dataset, and should be stored in :attr:`DataFrame.attrs`.

        Examples
        --------
        >>> df = pd.DataFrame({"A": [1, 2]})
        >>> df.flags
        <Flags(allows_duplicate_labels=True)>

        Flags can be get or set using ``.``

        >>> df.flags.allows_duplicate_labels
        True
        >>> df.flags.allows_duplicate_labels = False

        Or by slicing with a key

        >>> df.flags["allows_duplicate_labels"]
        False
        >>> df.flags["allows_duplicate_labels"] = True
        )r   r   s    r   flagszNDFrame.flagsh  s    N {r   )r   r   bool | lib.NoDefaultr   bool | Nonec               t    |                      |           |                     d          }|
||j        d<   |S )a  
        Return a new object with updated flags.

        This method creates a shallow copy of the original object, preserving its
        underlying data while modifying its global flags. In particular, it allows
        you to update properties such as whether duplicate labels are permitted. This
        behavior is especially useful in method chains, where one wishes to
        adjust DataFrame or Series characteristics without altering the original object.

        Parameters
        ----------
        copy : bool, default False
            This keyword is now ignored; changing its value will have no
            impact on the method.

            .. deprecated:: 3.0.0

                This keyword is ignored and will be removed in pandas 4.0. Since
                pandas 3.0, this method always returns a new object using a lazy
                copy mechanism that defers copies until necessary
                (Copy-on-Write). See the `user guide on Copy-on-Write
                <https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html>`__
                for more details.

        allows_duplicate_labels : bool, optional
            Whether the returned object allows duplicate labels.

        Returns
        -------
        Series or DataFrame
            The same type as the caller.

        See Also
        --------
        DataFrame.attrs : Global metadata applying to this dataset.
        DataFrame.flags : Global flags applying to this object.

        Notes
        -----
        This method returns a new object that's a view on the same data
        as the input. Mutating the input or the output values will be reflected
        in the other.

        This method is intended to be used in method chains.

        "Flags" differ from "metadata". Flags reflect properties of the
        pandas object (the Series or DataFrame). Metadata refer to properties
        of the dataset, and should be stored in :attr:`DataFrame.attrs`.

        Examples
        --------
        >>> df = pd.DataFrame({"A": [1, 2]})
        >>> df.flags.allows_duplicate_labels
        True
        >>> df2 = df.set_flags(allows_duplicate_labels=False)
        >>> df2.flags.allows_duplicate_labels
        False
        Fr   Nr   )_check_copy_deprecationr   r   )r   r   r   dfs       r   	set_flagszNDFrame.set_flags  sD    B 	$$T***YYEY""".2IBH./	r   c                n    |2t          |          }|j        dk    rt          d| j         d          |S )zvalidate the passed dtypeNVz+compound dtypes are not implemented in the z constructor)rc   kindNotImplementedError__name__)r   r   s     r   _validate_dtypezNDFrame._validate_dtype  sX      ''E zS  )9!l9 9 9  
 r   Callable[..., Self]c                     t          |           )zb
        Used when a manipulation result has the same dimensions as the
        original.
        rI   r   s    r   _constructorzNDFrame._constructor  s     "$'''r   z!list[Literal['index', 'columns']]_AXIS_ORDERSr   )r   indexrowszdict[Axis, AxisInt]_AXIS_TO_AXIS_NUMBERint_info_axis_numberLiteral['index', 'columns']_info_axis_name	_AXIS_LENSequence[Axis] | Nonekwargsr   r   c                \      fd|p j         D             }|                    |           |S )z%Return an axes dictionary for myself.c                <    i | ]}|                     |          S  	_get_axis.0r   r   s     r   
<dictcomp>z0NDFrame._construct_axes_dict.<locals>.<dictcomp>  s'    GGGaQq!!GGGr   )r   update)r   r   r   ds   `   r   _construct_axes_dictzNDFrame._construct_axes_dict  s@    
 HGGGD,ED4EGGG 	
r   r   r   c                x    	 | j         |         S # t          $ r }t          d| d| j                   |d }~ww xY w)NzNo axis named z for object type )r   KeyError
ValueErrorr   )r   r   errs      r   _get_axis_numberzNDFrame._get_axis_number  s^    	+D11 	 	 	FFFFF 	s    
949c                F    |                      |          }| j        |         S r   )r  r   )r   r   axis_numbers      r   _get_axis_namezNDFrame._get_axis_name  s%     **400,,r   rz   c                `    |                      |          }|dv sJ |dk    r| j        n| j        S )N>   r   r   r   )r  r   columns)r   r   r  s      r   r  zNDFrame._get_axis  s>    ++D11f$$$$(A--tzz4<?r   c                T    |                      |          }| j        }|dk    rd|z
  S |S )z'Map the axis to the block_manager axis.   r   )r  r   )r   r   ndims      r   r   zNDFrame._get_block_manager_axis  s5     ##D))}199t8Or   dict[str, Series | MultiIndex]c                Z   t          | |          }i }|d         }t          |j                  D ]J\  }}||x}}n	| d| }|}|                    |          }	|	                                }
||
_        |
||<   Kt          |t                    r|}n|                                }|||<   |S )Nr   level_)getattr	enumeratenamesget_level_values	to_seriesr   r   r{   )r   r   
axis_indexr	  prefixinamekeylevellevel_valuessdindexs               r   _get_axis_resolverszNDFrame._get_axis_resolvers(  s     T4((
a !122 	 	GAt""ee
  **q**%66u==L&&((A AGAcFF j*-- 	,FF))++F$r   #dict[Hashable, Series | MultiIndex]c                    ddl m i }| j        D ]*}|                    |                     |                     +fd|                                D             S )Nr   clean_column_namec                X    i | ]&\  }}t          |t                     |          |'S r  )r   r   )r  kvr-  s      r   r  z0NDFrame._get_index_resolvers.<locals>.<dictcomp>O  s<    XXXDAqZPQSVEWEWX!!!$$aXXXr   )pandas.core.computation.parsingr-  r   r  r)  r   )r   r	  	axis_namer-  s      @r   _get_index_resolverszNDFrame._get_index_resolversG  sq    EEEEEE,.* 	: 	:IHHT--i889999XXXXAGGIIXXXXr   dict[Hashable, Series]c                     ddl m ddlm t	           t
                    r  j                   iS  j        } fdt           j	         
                                |d          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,  r   c           
     |    i | ]8\  }}} |           |d j         ||                                        9S )F)r   r   r#  r   )r   __finalize__)r  r/  r0  r   r   r-  r   s       r   r  z9NDFrame._get_cleaned_column_resolvers.<locals>.<dictcomp>a  si     

 

 

 1e a  &&TZau# # #l4  

 

 

r   T)strict)r1  r-  pandas.core.seriesr   r   rh   r#  dtypeszipr  _iter_column_arrays)r   r;  r   r-  s   ` @@r   _get_cleaned_column_resolversz%NDFrame._get_cleaned_column_resolversQ  s     	FEEEEE------dI&& 	8%%di00$77

 

 

 

 

 

  #((**	     	

 

 

 
	
r   c                ,    t          | | j                  S r   )r  r   r   s    r   
_info_axiszNDFrame._info_axism  s     tT1222r   tuple[int, ...]c                D     t           fd j        D                       S )z3
        Return a tuple of axis dimensions
        c              3  \   K   | ]&}t                              |                    V  'd S r   r   r  r  s     r   	<genexpr>z NDFrame.shape.<locals>.<genexpr>w  s7      GGS**++GGGGGGr   )tupler   r   s   `r   shapezNDFrame.shaper  s+    
 GGGGT5FGGGGGGr   c                *      fd j         D             S )z?
        Return index label(s) of the internal NDFrame
        c                :    g | ]}                     |          S r  r  r  s     r   
<listcomp>z NDFrame.axes.<locals>.<listcomp>  s%    ===aq!!===r   )r   r   s   `r   r   zNDFrame.axesy  s"     >===4+<====r   c                    | j         j        S )a  
        Return an int representing the number of axes / array dimensions.

        Return 1 if Series. Otherwise return 2 if DataFrame.

        See Also
        --------
        numpy.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
        )r   r  r   s    r   r  zNDFrame.ndim  s    , y~r   c                N    t          t          j        | 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
        --------
        numpy.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
        )r   npprodrG  r   s    r   sizezNDFrame.size  s    0 274:&&'''r   )r   r   c               \    |                      |           |                     ||d          S )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. For `Series`
            this parameter is unused and defaults to 0.

        copy : bool, default False
            This keyword is now ignored; changing its value will have no
            impact on the method.

            .. deprecated:: 3.0.0

                This keyword is ignored and will be removed in pandas 4.0. Since
                pandas 3.0, this method always returns a new object using a lazy
                copy mechanism that defers copies until necessary
                (Copy-on-Write). See the `user guide on Copy-on-Write
                <https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html>`__
                for more details.

        Returns
        -------
        %(klass)s
            An object of type %(klass)s.

        See Also
        --------
        %(klass)s.rename_axis : Alter the name of the index%(see_also_sub)s.
        Fr   )r   _set_axis_nocheck)r   labelsr   r   s       r   set_axiszNDFrame.set_axis  s4    X 	$$T***%%fdE%BBBr   r   Literal[False]c                    d S r   r  r   rS  r   r   s       r   rR  zNDFrame._set_axis_nocheck  	     sr   Literal[True]c                    d S r   r  rW  s       r   rR  zNDFrame._set_axis_nocheck  s    UXUXr   Self | Nonec                    d S r   r  rW  s       r   rR  zNDFrame._set_axis_nocheck  s    SVSVr   c                    |r&t          | |                     |          |           d S |                     d          }t          ||                    |          |           |S NFr   )setattrr  r   )r   rS  r   r   r   s        r   rR  zNDFrame._set_axis_nocheck  sg     	D$--d33V<<<4iiUi##S''--v666
r   rS  AnyArrayLike | listc                Z    t          |          }| j                            ||           dS )z
        This is called from the cython code when we set the `index` attribute
        directly, e.g. `series.index = [1, 2, 3]`.
        N)r~   r   rT  )r   r   rS  s      r   	_set_axiszNDFrame._set_axis  s/     f%%	4(((((r   r%  r)   c                    |                      |          }|                    |          }|                     ||          S )a  
        Return Series/DataFrame with requested index / column level(s) removed.

        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.

            For `Series` this parameter is unused and defaults to 0.

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

        See Also
        --------
        DataFrame.replace : Replace values given in `to_replace` with `value`.
        DataFrame.pivot : Return reshaped DataFrame organized by given
            index / column values.

        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
        r   )r  	droplevelrT  )r   r%  r   rS  
new_labelss        r   rd  zNDFrame.droplevel   s?    D %%%%e,,
}}Zd}333r   itemr   Series | Anyc                    | |         }| |= |S r   r  )r   rf  results      r   popzNDFrame.popF  s    dJr   Axis | NoneScalar | Series | DataFramec                (   |t          | j                  n|                     |          f| j        t	          fdt          | j                  D                                }t          |t                    r|	                    | 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. For `Series` this parameter is unused and defaults to `None`.

        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()
        np.int64(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()
        np.int64(1)
        Nc              3  n   K   | ]/\  }}|v rt          |          d k    rdnt          d          V  0dS )r   r   N)r   slice)r  r"  r   r   s      r   rE  z"NDFrame.squeeze.<locals>.<genexpr>  s[        Aq $YY3q66Q;;E$KK     r   squeezemethod)
ranger   r  ilocrF  r  r   r   r   r8  )r   r   ri  r   s      @r   rp  zNDFrame.squeezeL  s    P )-uT^$$$4;P;PQU;V;V:X    %di00    
 fg&& 	A((i(@@Fr   .)r   r  r   r   r%  errorsmapperRenamer | Noner   r  Level | Noneru  c                   d S r   r  r   rv  r   r  r   r   r%  ru  s           r   _renamezNDFrame._rename  	     sr   )r   r  r   r%  ru  c                   d S r   r  rz  s           r   r{  zNDFrame._rename  r|  r   c                   d S r   r  rz  s           r   r{  zNDFrame._rename  	     cr   ignorec               4   |||t          d          ||#|t          d          |t          d          n |r|                     |          dk    r|}n|}|                     |           |r| n|                     d          }t	          ||f          D ]J\  }	}
|
	|                     |	          }t          j        |
          }||                    |          }t          |
t                    r|
j        j        st          d          t          |
          s|j        r+|)|                    |                              |
          n|                    |
          |dk    rFt%          d	k                       r-fd
t	          |
          D             }t'          | d          |                    ||          }|                    ||	d           L|r|                     |           d S |                    | d          S )Nzmust pass an index to rename:Cannot specify both 'axis' and any of 'index' or 'columns'z<Cannot specify both 'mapper' and any of 'index' or 'columns'r   Fr   z2Cannot rename with a Series with non-unique index.raisec                2    g | ]\  }}|         d k    |S )r  r  )r  r   labelindexers      r   rJ  z#NDFrame._rename.<locals>.<listcomp>"  s6     & & &(E5"5>R// ///r    not found in axisr%  Tr   r   renamerq  )	TypeErrorr  *_check_inplace_and_allows_duplicate_labelsr   r  r  ro   get_rename_function_get_level_numberr   rh   r   	is_uniquer  callable	_is_multir  get_indexer_forr   r  _transform_indexrR  _update_inplacer8  )r   rv  r   r  r   r   r%  ru  ri  axis_noreplacementsaxfmissing_labels	new_indexr  s                  @r   r{  zNDFrame._rename  s    >em:;;; 3P   !R   "
  	d++D11Q66GGE77@@@ ;diiUi&;&;%.w/?%@%@ 	L 	L!G\#((B*<88A ,,U33,	22 W<;M;W W !UVVV L)) J< ?E$5 11%88HHVVGG 00>>GW$$WW]-C)D)D$& & & &,5l,C,C& & &N
 #n#H#H#HIII++AU+;;I$$YWd$KKKK 	>  (((4&&tH&===r   )r   r  r   r   r   IndexLabel | lib.NoDefaultc                   d S r   r  r   rv  r   r  r   r   r   s          r   rename_axiszNDFrame.rename_axis2  	     sr   )r   r  r   r   c                   d S r   r  r  s          r   r  zNDFrame.rename_axis>  r  r   c                   d S r   r  r  s          r   r  zNDFrame.rename_axisJ  s	     cr   c               :   |                      |           ||d}||                     |          }t          |d          }|t          j        urWt          |          pt          |          ot          |           }|r|                     |||          S t          d          |r| n| 
                    d          }	t          | j                  D ]}|                    |                     |                    }
|
t          j        u r9t          |
          pt          |
          ot          |
           }|r|
}n<t          j        |
          |                     |          j        }fd|D             }|	                    ||d	           |s|	S dS )
a  
        Set the name of the axis for the index or columns.

        Parameters
        ----------
        mapper : scalar, list-like, optional
            Value to set the axis name attribute.

            Use either ``mapper`` and ``axis`` to
            specify the axis to target with ``mapper``, or ``index``
            and/or ``columns``.
        index : scalar, list-like, dict-like or function, optional
            A scalar, list-like, dict-like or functions transformations to
            apply to that axis' values.
        columns : scalar, list-like, dict-like or function, optional
            A scalar, list-like, dict-like or functions transformations to
            apply to that axis' values.
        axis : {0 or 'index', 1 or 'columns'}, default 0
            The axis to rename.
        copy : bool, default False
            This keyword is now ignored; changing its value will have no
            impact on the method.

            .. deprecated:: 3.0.0

                This keyword is ignored and will be removed in pandas 4.0. Since
                pandas 3.0, this method always returns a new object using a lazy
                copy mechanism that defers copies until necessary
                (Copy-on-Write). See the `user guide on Copy-on-Write
                <https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html>`__
                for more details.

        inplace : bool, default False
            Modifies the object directly, instead of creating a new Series
            or DataFrame.

        Returns
        -------
        DataFrame, or None
            The same type as the caller or None if ``inplace=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
        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
        --------
        **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   r  Nr   r  z,Use `.rename` to alter labels with a mapper.Fr   c                &    g | ]} |          S r  r  )r  r#  r  s     r   rJ  z'NDFrame.rename_axis.<locals>.<listcomp>  s!    ===D$===r   T)r   r  rS   r   
no_defaultrb   r^   r\   _set_axis_namer  r   rs  r   getr  ro   r  r  r  )r   rv  r   r  r   r   r   r   
non_mapperri  r0  newnamescurnamesr  s                @r   r  zNDFrame.rename_axisV  s   B 	$$T***733((..D%gy99''"6** V$$A\&-A-A)A   Q**6g*NNN !OPPP %?TT$)))*?*?Fdn-- I IHHT006677&&&q\\Vl1oo.UlSTooBU
 > HH2155A#~~d339H====H===H%%hT4%HHHH 4r   rQ  c                   d S r   r  r   r#  r   r   s       r   r  zNDFrame._set_axis_name  rX  r   c                   d S r   r  r  s       r   r  zNDFrame._set_axis_name  rX  r   c                   d S r   r  r  s       r   r  zNDFrame._set_axis_name  s	     cr   c                  |                      |          }|                     |                              |          }t          |d          }|r| n|                     d          }|dk    r||_        n||_        |s|S dS )a  
        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
        r   Fr   r   N)r  r  	set_namesrS   r   r   r  )r   r#  r   r   idxrenameds         r   r  zNDFrame._set_axis_name  s    j $$T**nnT"",,T22%gy99!<$$tyyey'<'<199GMM!GO 	Ntr   c                H     t           fd j        D                       S )Nc              3     K   | ]?}                     |                                                   |                    V  @d S r   )r  equals)r  r   otherr   s     r   rE  z(NDFrame._indexed_same.<locals>.<genexpr>T  sZ       
 
=>DNN1$$U__Q%7%788
 
 
 
 
 
r   )allr   r   r  s   ``r   _indexed_samezNDFrame._indexed_sameR  sD     
 
 
 
 
BFBS
 
 
 
 
 	
r   r  r   c                    t          |t          |                     st          | t          |                    sdS t          t          |          }| j                            |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 row/column index do not need to have the same type, as long
        as the values are considered equal. Corresponding columns and
        index must be of 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.

        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

        DataFrames with NaN in the same locations compare equal.

        >>> df_nan1 = pd.DataFrame({"a": [1, np.nan], "b": [3, np.nan]})
        >>> df_nan2 = pd.DataFrame({"a": [1, np.nan], "b": [3, np.nan]})
        >>> df_nan1.equals(df_nan2)
        True

        If the NaN values are not in the same locations, they compare unequal.

        >>> df_nan3 = pd.DataFrame({"a": [1, np.nan], "b": [3, 4]})
        >>> df_nan1.equals(df_nan3)
        False
        F)r   typer   r   r   r  r  s     r   r  zNDFrame.equalsX  s`    x 5$t**-- 	D$u++1N1N 	5We$$y
+++r   c                    dd}| j                             |          }|                     ||j                  }|                    | d          S )Nr   r   c                z    t          | j                  rt          j        |           S t          j        |           S r   )r[   r   operatorinvnegr   s    r   blk_funcz!NDFrame.__neg__.<locals>.blk_func  s8    V\** 	,  |F+++
  |F+++r   r   __neg__rq  r   r   r   apply_constructor_from_mgrr   r8  r   r  new_dataress       r   r  zNDFrame.__neg__  s^    
	, 
	, 
	, 
	, 9??8,,(((FFY777r   c                    dd}| j                             |          }|                     ||j                  }|                    | d          S )Nr   r   c                z    t          | j                  r|                                 S t          j        |           S r   )r[   r   r   r  posr  s    r   r  z!NDFrame.__pos__.<locals>.blk_func  s4    V\** ,{{}}$
  |F+++r   r  __pos__rq  r  r  r  s       r   r  zNDFrame.__pos__  s^    	, 	, 	, 	, 9??8,,(((FFY777r   c                    | j         s|                     d          S | j                            t          j                  }|                     ||j                  }|                    | d          S )NFr   r  
__invert__rq  )	rO  r   r   r  r  invertr  r   r8  )r   r  r  s      r   r  zNDFrame.__invert__  sh    y 	)99%9(((9??8?33(((FF\:::r   r   c                L    t          dt          |           j         d          )NzThe truth value of a zC is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().)r  r  r   r   s    r   __bool__zNDFrame.__bool__  s7    CDJJ$7 C C C
 
 	
r   c                    | j                             t          j                  }|                     ||j                                      | d          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[us]

        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  abs)r#  )r   r  rM  r  r  r   r8  )r   res_mgrs     r   r  zNDFrame.abs  sR    D )//"&))))')EERRu S 
 
 	
r   c                *    |                                  S r   )r  r   s    r   __abs__zNDFrame.__abs__5  s    xxzzr   decimalsc                V    |                      |                              | d          S )N	__round__rq  )roundr8  )r   r  s     r   r  zNDFrame.__round__9  s'    zz(##00k0JJJr   r$  r-   c                    |                      |          }|duo:t          |          o+|| j        |         j        v o|                     ||           S )a|  
        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 : Hashable
            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
        Nr   )r  ri   r   r  _is_label_reference)r   r$  r   axis_ints       r   _is_level_referencezNDFrame._is_level_referenceE  so    , ((.. tO AC  Aty*00A ,,Sx,@@@		
r   c                                           |          fdt           j                  D             }t                    ot	           fd|D                       S )aR  
        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 : Hashable
            Potential label name, i.e. Index entry.
        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
        c              3  (   K   | ]}|k    |V  d S r   r  r  r  r  s     r   rE  z.NDFrame._is_label_reference.<locals>.<genexpr>z  '      KKRB(NNbNNNNKKr   c              3  6   K   | ]}j         |         v V  d S r   r  r  r  r$  r   s     r   rE  z.NDFrame._is_label_reference.<locals>.<genexpr>|  s.      'R'Rty}(<'R'R'R'R'R'Rr   )r  rs  r   ri   any)r   r$  r   
other_axesr  s   ``  @r   r  zNDFrame._is_label_referenced  sp    * ((..KKKK5#8#8KKK
3RC'R'R'R'R'Rz'R'R'R$R$RRr   c                ^    |                      ||          p|                     ||          S )a8  
        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 : Hashable
            Potential label or level name
        axis : int, default 0
            Axis that levels are associated with (0 for index, 1 for columns)

        Returns
        -------
        bool
        r   )r  r  )r   r$  r   s      r   _is_label_or_level_referencez$NDFrame._is_label_or_level_reference~  sA    * ''$'77 
4;S;Sd <T <
 <
 	
r   c                z   	                       |          		fdt           j                  D             }zt                    rm j        	         j        v r[t           fd|D                       rA	dk    rdnd\  }}	dk    rdnd\  }}d d| d	| d
| d	| d}t          |          dS dS dS dS )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 : Hashable
            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
        c              3  (   K   | ]}|k    |V  d S r   r  r  s     r   rE  z:NDFrame._check_label_or_level_ambiguity.<locals>.<genexpr>  r  r   Nc              3  6   K   | ]}j         |         v V  d S r   r  r  s     r   rE  z:NDFrame._check_label_or_level_ambiguity.<locals>.<genexpr>  s.      >>RC49R=(>>>>>>r   r   )anr   )r   column'z
' is both  z level and z label, which is ambiguous.)r  rs  r   ri   r   r  r  r  )
r   r$  r   r  level_article
level_typelabel_article
label_typemsgr  s
   ``       @r   _check_label_or_level_ambiguityz'NDFrame._check_label_or_level_ambiguity  sC   ( ((..KKKK5#8#8KKK
 OC   ty*000>>>>>:>>>>> 1
 $,q==o &M:
 $,q==o &M:
KC K K= K K: K K K K#-K K K  S//!% OOO0000r   r   c                   |                                t          fdt          | j                  D             d          }|                     |          rE|                     |           |t          d          |                     ||          j        }nL| 	                    |          r&| j
                                     |          j        }nt          |          |j        dk    rQ|+t          |                     |          t                     rd}nd}dk    rd	nd
}t          d| 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 : Hashable
            Label or level name.
        axis : int, default 0
            Axis that levels are associated with (0 for index, 1 for columns)

        Returns
        -------
        np.ndarray or ExtensionArray

        Raises
        ------
        KeyError
            if `key` matches neither a label nor a level
        ValueError
            if `key` matches multiple labels
        c              3  (   K   | ]}|k    |V  d S r   r  )r  r  r   s     r   rE  z5NDFrame._get_label_or_level_values.<locals>.<genexpr>  s'      >>B2::R::::>>r   Nr   zaxis matched all axesr   zX
For a multi-index, the label must be a tuple with elements corresponding to each level. r   r  r   zThe z label 'z' is not unique.)r  nextrs  r   r  r  r  xs_valuesr  r   r  r  r  r   r  r{   )r   r$  r   first_other_axesr   multi_messagelabel_axis_names     `    r   _get_label_or_level_valuesz"NDFrame._get_label_or_level_values  s   @ $$T**>>>>%//>>>
 
 ##Cd#33 	 0040@@@' !8999WWS'7W88@FF%%c%55 	 Yt_55c::BFF3-- ;??+
/00*1 1+G  !#*.!))hhOTTTTT]TT   r   c                n                                    t          j        |          } fd|D             }|rt          d d|            fd|D             } fd|D             }                     d          }dk    r5|r|                    |d	d	
           |r|                    |dd	           nt|rXt          |j        t                    r |j        
                    |          |_        nt          |j        j                  |_        |r|                    |dd	           |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
        c                B    g | ]}                     |           |S r   )r  r  r/  r   r   s     r   rJ  z2NDFrame._drop_labels_or_levels.<locals>.<listcomp>%  sA     
 
 
4#D#DQT#D#R#R

 
 
r   z;The following keys are not valid labels or levels for axis z: c                B    g | ]}                     |           |S r  r  r  s     r   rJ  z2NDFrame._drop_labels_or_levels.<locals>.<listcomp>0  s1    TTTT-E-Ead-E-S-ST!TTTr   c                B    g | ]}                     |           |S r  r	  r  s     r   rJ  z2NDFrame._drop_labels_or_levels.<locals>.<listcomp>2  s2    XXX1I1I!RV1I1W1WX!XXXr   Fr   r   T)dropr   r   r  )r  ro   maybe_make_listr  r   reset_indexr  r   r  r{   rd  r}   rO  )r   keysr   invalid_keyslevels_to_droplabels_to_dropdroppeds   ` `    r   _drop_labels_or_levelszNDFrame._drop_labels_or_levels  s   6 $$T** %d++
 
 
 
 

 
 
  	:#': :+7: :   UTTTTTTTTXXXXXTXXX
 )))''199 M##Nt#LLL  C^!TBBB  Jgoz:: J&-o&?&?&O&OGOO '4GO4H&I&IGO  C^!TBBBr   zClassVar[None]__hash__r   c                *    t          | j                  S )a  
        Iterate over info axis.

        Returns
        -------
        iterator
            Info axis as iterator.

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

        Examples
        --------
        >>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
        >>> for x in df:
        ...     print(x)
        A
        B
        )iterr@  r   s    r   __iter__zNDFrame.__iter__Z  s    , DO$$$r   c                    | j         S )a  
        Get the 'info axis' (see Indexing for more).

        This is index for Series, columns for DataFrame.

        Returns
        -------
        Index
            Info axis.

        See Also
        --------
        DataFrame.index : The index (row labels) of the DataFrame.
        DataFrame.columns: The column labels of the DataFrame.

        Examples
        --------
        >>> d = pd.DataFrame(
        ...     data={"A": [1, 2, 3], "B": [0, 4, 8]}, index=["a", "b", "c"]
        ... )
        >>> d
           A  B
        a  1  0
        b  2  4
        c  3  8
        >>> d.keys()
        Index(['A', 'B'], dtype='str')
        r@  r   s    r   r  zNDFrame.keyss  s    : r   c              #  6   K   | j         D ]}|| |         fV  dS )z
        Iterate over (label, values) on info axis

        This is index for Series and columns for DataFrame.

        Returns
        -------
        Generator
        Nr  )r   hs     r   r   zNDFrame.items  s:        	 	AT!W*	 	r   c                *    t          | j                  S )zReturns length of info axis)r   r@  r   s    r   __len__zNDFrame.__len__  s    4?###r   c                    || j         v S )z#True if the key is in the info axisr  )r   r$  s     r   __contains__zNDFrame.__contains__  s     do%%r   c                D     t           fd j        D                       S )a  
        Indicator whether Series/DataFrame is empty.

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

        Returns
        -------
        bool
            If Series/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 Series/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

        >>> ser_empty = pd.Series({"A": []})
        >>> ser_empty
        A    []
        dtype: object
        >>> ser_empty.empty
        False
        >>> ser_empty = pd.Series()
        >>> ser_empty.empty
        True
        c              3  d   K   | ]*}t                              |                    d k    V  +dS )r   NrD  r  s     r   rE  z NDFrame.empty.<locals>.<genexpr>  s<      JJ13t~~a(())Q.JJJJJJr   )r  r   r   s   `r   emptyzNDFrame.empty  s,    t JJJJ8IJJJJJJr   i  __array_priority__npt.DTypeLike | None
np.ndarrayc                   |du r"| j         j        s| j        st          d          | j        }|t          j        ||          }nt          j        |||          }|durt          |j	        |j	                  rk| j         j        r_t          | j
        j        d         |j	                  r:t          |j	        |j	                  r |                                }d|j        _        |S )NFz:Unable to avoid copy while creating an array as requested.r   )r   r   Tr   )r   is_single_blockr"  r  r  rM  asarrayarrayrU   r   r;  rt  viewr   	writeable)r   r   r   r   arrs        r   	__array__zNDFrame.__array__  s     5==!:=4:= L   <*V5111CC(6T:::C v|SY77 	) 
 dk.q16<@@ ,^ciF F , hhjj&+	#
r   ufuncnp.ufuncrr  inputsr	   c                0    t          j        | ||g|R i |S r   )rn   array_ufunc)r   r.  rr  r0  r   s        r   __array_ufunc__zNDFrame.__array_ufunc__  s)     $T5&L6LLLVLLLr   dict[str, Any]c                      fd j         D             } j         j         j          j         fd j        j        D             d|S )Nc                4    i | ]}|t          |d           S r   )r  r  r/  r   s     r   r  z(NDFrame.__getstate__.<locals>.<dictcomp>  s'    BBBa74D))BBBr   c                ,    i | ]}|j         |         S r  )r   r7  s     r   r  z(NDFrame.__getstate__.<locals>.<dictcomp>  s!    BBBAq$*Q-BBBr   )r   r   r   r   r   )r   r   r   r   r   _keys)r   metas   ` r   __getstate__zNDFrame.__getstate__  sg    BBBB4>BBBIIZBBBB1ABBB
 
 
 	
r   c           	     @   t          |t                    r	|| _        d S t          |t                    rGd|v rd|vr|                    d          |d<   |                    d          }| |                    di           }|i }t                              | d|           |                    dddi          }t                              | dt          | fi |           t          | j
        | j        z             }|D ]0}||v r*|dk    r$||         }t                              | ||           1|                                D ]%\  }}||vrt                              | ||           &d S t          d          t          |          d	k    rt          d          d S )
N_datar   r   r   r   r   Tz(Pre-0.12 pickles are no longer supportedr  )r   r   r   r   rj  r  r   r   rx   setr   r   r   r   r   )r   statetypr   r   r:  r/  r0  s           r   __setstate__zNDFrame.__setstate__  s   e\**  	RDIIIt$$ 	R%F%$7$7 %		' 2 2f))F##C		(B//=E""45999		(-F,MNN""453G3G3G3GHHH 4/$.@AA 7 7AEzza8mm!!H**4A666!KKMM 7 7DAq}}**4A6667 7
 **TUUUZZ1__%&PQQQ _r   c                    dd                     t          t          |                      d}t          |           j         d| dS )N[,]())joinmapr   r  r   )r   preprs     r   __repr__zNDFrame.__repr__D  sJ     9CHHSt4455888t**%000000r   c                ^    t          j        d          dk    r|                                 S dS )z
        Returns a LaTeX representation for a particular object.
        Mainly for use with nbconvert (jupyter notebook conversion to pdf).
        zstyler.render.reprlatexN)r   
get_optionto_latexr   s    r   _repr_latex_zNDFrame._repr_latex_J  s.     122g====??"4r   c                   t          j        d          rm|                     t          j        d                    }|                    d          }t	          t
          |          }t          |t          j                  S dS )zh
        Not a real Jupyter special repr method, but we use the same
        naming convention.
        zdisplay.html.table_schemazdisplay.max_rowstable)orient)object_pairs_hookN)	r   rN  headto_jsonr   r   r   collectionsOrderedDict)r   r   as_jsons      r   _repr_data_resource_zNDFrame._repr_data_resource_U  sz     899 	M99V./ABBCCDll'l22G3((GK4KLLLL	M 	Mr   Sheet1r  Tinf)
sheet_namena_repfloat_formatr  headerr   index_labelstartrowstartcolenginemerge_cellsinf_repfreeze_panesstorage_optionsengine_kwargs
autofilterexcel_writer)FilePath | WriteExcelBuffer | ExcelWriterr]  r^  r_  
str | NoneSequence[Hashable] | Noner`  Sequence[Hashable] | boolra  IndexLabel | Nonerb  rc  rd  (Literal['openpyxl', 'xlsxwriter'] | Nonere  rf  rg  tuple[int, int] | Nonerh  StorageOptions | Noneri  dict[str, Any] | Nonerj  c                   |i }t          | t                    r| n|                                 }ddlm}  |||||||||||
  
        }|                    |||	|
||||           dS )a5  
        Write object to an Excel sheet.

        To write a single object 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 overwrite the existing file because the default mode is write.

        Parameters
        ----------
        excel_writer : path-like, file-like, 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`` or
            ``io.excel.xlsm.writer``.
        merge_cells : bool or 'columns', default False
            If True, write MultiIndex index and columns as merged cells.
            If 'columns', merge MultiIndex column cells only.
        inf_rep : str, default 'inf'
            Representation for infinity (there is no native representation for
            infinity in Excel).
        freeze_panes : tuple of int (length 2), optional
            Specifies the one-based bottommost row and rightmost column that
            is to be frozen.
        storage_options : dict, optional
            Extra options that make sense for a particular storage connection, e.g.
            host, port, username, password, etc. For HTTP(S) URLs the key-value pairs
            are forwarded to ``urllib.request.Request`` as header options. For other
            URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are
            forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more
            details, and for more examples on storage options refer `here
            <https://pandas.pydata.org/docs/user_guide/io.html?
            highlight=storage_options#reading-writing-remote-files>`_.

        engine_kwargs : dict, optional
            Arbitrary keyword arguments passed to excel engine.
        autofilter : bool, default False
            If True, add automatic filters to all columns.

        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.
        io.formats.style.Styler.to_excel : Add styles to Excel sheet.

        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 to write further
        data without rewriting the whole workbook.

        pandas will check the number of rows, columns,
        and cell character count does not exceed Excel's limitations.
        All other limitations must be checked by the user.

        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
        ...     df1.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
        Nr   )ExcelFormatter)	r^  colsr`  r_  r   ra  re  rf  rj  )r]  rb  rc  rg  rd  rh  ri  )r   rg   to_framepandas.io.formats.excelrv  write)r   rk  r]  r^  r_  r  r`  r   ra  rb  rc  rd  re  rf  rg  rh  ri  rj  r   rv  	formatters                        r   to_excelzNDFrame.to_excele  s    `  Ml33HTT::::::"N%##!
 
 
	 	!%+' 	 		
 		
 		
 		
 		
r   
   msinferw)rS  date_formatdouble_precisionforce_ascii	date_unitdefault_handlerlinescompressionr   indentrh  modepath_or_buf7FilePath | WriteBuffer[bytes] | WriteBuffer[str] | NonerS  ILiteral['split', 'records', 'index', 'table', 'columns', 'values'] | Noner  r  r  r  r@   r  (Callable[[Any], JSONSerializable] | Noner  r  r   r  
int | Noner  Literal['a', 'w']c                  ddl m} |	|dk    rd}n|^d}| j        dk    r| j        n| j        g}t          d |D                       r(t          j        d	t          t                      
           n.|dk    r(t          j        dt          t                      
           t          j        |           |pd}|                    || ||||||||	|
|||          S )aN&  
        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, path object, file-like object, or None, default None
            String, path object (implementing os.PathLike[str]), or file-like
            object implementing a write() function. If None, 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'``.

        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'.

            .. deprecated:: 3.0.0
                'epoch' date format is deprecated and will be removed in a future
                version, please use 'iso' instead.

        double_precision : int, default 10
            The number of decimal places to use when encoding
            floating point values. The possible maximal value is 15.
            Passing double_precision greater than 15 will raise a ValueError.
        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 : str or dict, default 'infer'
            For on-the-fly compression of the output data. If 'infer' and
            'path_or_buf' is path-like, then detect compression from the following
            extensions: '.gz',
            '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2'
            (otherwise no compression).
            Set to ``None`` for no compression.
            Can also be a dict with key ``'method'`` set to one of
            {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``, ``'xz'``, ``'tar'``} and
            other key-value pairs are forwarded to
            ``zipfile.ZipFile``, ``gzip.GzipFile``,
            ``bz2.BZ2File``, ``zstandard.ZstdCompressor``, ``lzma.LZMAFile`` or
            ``tarfile.TarFile``, respectively.
            As an example, the following could be passed for faster compression and
            to create a reproducible gzip archive:
            ``compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}``.

        index : bool or None, default None
            The index is only used when 'orient' is 'split', 'index', 'column',
            or 'table'. Of these, 'index' and 'column' do not support
            `index=False`. The string 'index' as a column name with empty :class:`Index`
            or if it is 'index' will raise a ``ValueError``.

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

        storage_options : dict, optional
            Extra options that make sense for a particular storage connection, e.g.
            host, port, username, password, etc. For HTTP(S) URLs the key-value pairs
            are forwarded to ``urllib.request.Request`` as header options. For other
            URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are
            forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more
            details, and for more examples on storage options refer `here
            <https://pandas.pydata.org/docs/user_guide/io.html?
            highlight=storage_options#reading-writing-remote-files>`_.

        mode : str, default 'w' (writing)
            Specify the IO mode for output when supplying a path_or_buf.
            Accepted args are 'w' (writing) and 'a' (append) only.
            mode='a' is only supported when lines is True and orient is 'records'.

        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.

        ``orient='table'`` contains a 'pandas_version' field under 'schema'.
        This stores the version of `pandas` used in the latest revision of the
        schema.

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

        >>> result = df.to_json(orient="split")
        >>> parsed = loads(result)
        >>> 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 = loads(result)
        >>> 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 = loads(result)
        >>> 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 = loads(result)
        >>> 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 = loads(result)
        >>> dumps(parsed, indent=4)  # doctest: +SKIP
        [
            [
                "a",
                "b"
            ],
            [
                "c",
                "d"
            ]
        ]

        Encoding with Table Schema:

        >>> result = df.to_json(orient="table")
        >>> parsed = loads(result)
        >>> 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": "1.4.0"
            }},
            "data": [
                {{
                    "index": "row 1",
                    "col 1": "a",
                    "col 2": "b"
                }},
                {{
                    "index": "row 2",
                    "col 1": "c",
                    "col 2": "d"
                }}
            ]
        }}
        r   )jsonNrR  isoepochr  c              3  (   K   | ]}|j         d v V  dS )mMNr   )r  r   s     r   rE  z"NDFrame.to_json.<locals>.<genexpr>8
  s)      ::%5:%::::::r   z|The default 'epoch' date format is deprecated and will be removed in a future version, please use 'iso' date format instead.
stacklevelzp'epoch' date format is deprecated and will be removed in a future version, please use 'iso' date format instead.)r  r   rS  r  r  r  r  r  r  r  r   r  rh  r  )	pandas.ior  r  r;  r   r  warningswarnrL   rP   r   is_nonnegative_intrV  )r   r  rS  r  r  r  r  r  r  r  r   r  rh  r  r  r;  s                   r   rV  zNDFrame.to_json	  s6   | 	#"""""6W#4#4KK !K$(INNT[[F::6::::: Q"/11	    G##MA+--	    	!&)))1||##-#+#+  
 
 	
r   r   r9  zUTF-8r  	complevelcomplibappendformatr   min_itemsizenan_repdropnadata_columnsru  encodingFilePath | HDFStoreLiteral['a', 'w', 'r+']r  r  /Literal['zlib', 'lzo', 'bzip2', 'blosc'] | Noner  r   Literal['fixed', 'table'] | Noner  int | dict[str, int] | Noner  r   Literal[True] | list[str] | Noner2   r  c               Z    ddl m} |                    ||| |||||||	|
||||           dS )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.

        .. warning::

           One can store a subclass of ``DataFrame`` or ``Series`` to HDF5,
           but the type of the subclass is lost upon storing.

        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}, default None
            Specifies a compression level for data.
            A value of 0 or None disables compression.
        complib : {'zlib', 'lzo', 'bzip2', 'blosc'}, default 'zlib'
            Specifies the compression library to be used.
            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".
        index : bool, default True
            Write DataFrame index as a column.
        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.
        dropna : bool, default False, optional
            Remove missing values.
        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:`Query via data columns<io.hdf5-query-data-columns>`. for
            more information.
            Applicable only to format='table'.
        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"
            Set character encoding.

        See Also
        --------
        read_hdf : Read from HDF file.
        DataFrame.to_orc : Write a DataFrame to the binary orc format.
        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"]
        ... )  # doctest: +SKIP
        >>> df.to_hdf("data.h5", key="df", mode="w")  # doctest: +SKIP

        We can add another object to the same file:

        >>> s = pd.Series([1, 2, 3, 4])  # doctest: +SKIP
        >>> s.to_hdf("data.h5", key="s")  # doctest: +SKIP

        Reading from HDF file:

        >>> pd.read_hdf("data.h5", "df")  # doctest: +SKIP
        A  B
        a  1  4
        b  2  5
        c  3  6
        >>> pd.read_hdf("data.h5", "s")  # doctest: +SKIP
        0    1
        1    2
        2    3
        3    4
        dtype: int64
        r   )pytablesr  N)r  r  to_hdf)r   r  r$  r  r  r  r  r  r   r  r  r  r  ru  r  r  s                   r   r  zNDFrame.to_hdf\
  sk    H 	'&&&&& 	%% 	 	
 	
 	
 	
 	
r   failschema	if_existsr   ra  	chunksizer   rr  r#  r  r  3Literal['fail', 'replace', 'append', 'delete_rows']r  DtypeArg | None"Literal['multi'] | Callable | Nonec               L    ddl m}
 |
                    | |||||||||	
  
        S )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.

        .. warning::
            The pandas library does not attempt to sanitize inputs provided via a to_sql call.
            Please refer to the documentation for the underlying database driver to see if it
            will properly prevent injection, or alternatively be advised of a security risk when
            executing arbitrary commands in a to_sql call.

        Parameters
        ----------
        name : str
            Name of SQL table.
        con : ADBC connection, sqlalchemy.engine.(Engine or Connection) or sqlite3.Connection
            ADBC provides high performance I/O with native type support, where available.
            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/20/core/connections.html>`_.
            If passing a sqlalchemy.engine.Connection which is already in a transaction,
            the transaction will not be committed.  If passing a sqlite3.Connection,
            it will not be possible to roll back the record insertion.

        schema : str, optional
            Specify the schema (if database flavor supports this). If None, use
            default schema.
        if_exists : {'fail', 'replace', 'append', 'delete_rows'}, 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.
            * delete_rows: If a table exists, delete all records and insert data.

        index : bool, default True
            Write DataFrame index as a column. Uses `index_label` as the column
            name in the table. Creates a table index for this column.
        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 to the database connection at a time.
            By default, all rows will be written at once. Also see the method keyword.
        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>`.

        Returns
        -------
        None or int
            Number of rows affected by to_sql. None is returned if the callable
            passed into ``method`` does not return an integer number of rows.

            The number of returned rows affected is the sum of the ``rowcount``
            attribute of ``sqlite3.Cursor`` or SQLAlchemy connectable which may not
            reflect the exact number of written rows as stipulated in the
            `sqlite3 <https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.rowcount>`__ or
            `SQLAlchemy <https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.CursorResult.rowcount>`__.

        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.

        Not all datastores support ``method="multi"``. Oracle, for example,
        does not support multi-value insert.

        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(name='users', con=engine)
        3
        >>> from sqlalchemy import text
        >>> with engine.connect() as conn:
        ...     conn.execute(text("SELECT * FROM users")).fetchall()
        [(0, 'User 1'), (1, 'User 2'), (2, 'User 3')]

        An `sqlalchemy.engine.Connection` can also be passed to `con`:

        >>> with engine.begin() as connection:
        ...     df1 = pd.DataFrame({'name' : ['User 4', 'User 5']})
        ...     df1.to_sql(name='users', con=connection, if_exists='append')
        2

        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(name='users', con=engine, if_exists='append')
        2
        >>> with engine.connect() as conn:
        ...     conn.execute(text("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(name='users', con=engine, if_exists='replace',
        ...            index_label='id')
        2
        >>> with engine.connect() as conn:
        ...     conn.execute(text("SELECT * FROM users")).fetchall()
        [(0, 'User 6'), (1, 'User 7')]

        Delete all rows before inserting new records with ``df3``

        >>> df3 = pd.DataFrame({"name": ['User 8', 'User 9']})
        >>> df3.to_sql(name='users', con=engine, if_exists='delete_rows',
        ...            index_label='id')
        2
        >>> with engine.connect() as conn:
        ...     conn.execute(text("SELECT * FROM users")).fetchall()
        [(0, 'User 8'), (1, 'User 9')]

        Use ``method`` to define a callable insertion method to do nothing
        if there's a primary key conflict on a table in a PostgreSQL database.

        >>> from sqlalchemy.dialects.postgresql import insert
        >>> def insert_on_conflict_nothing(table, conn, keys, data_iter):
        ...     # "a" is the primary key in "conflict_table"
        ...     data = [dict(zip(keys, row)) for row in data_iter]
        ...     stmt = insert(table.table).values(data).on_conflict_do_nothing(index_elements=["a"])
        ...     result = conn.execute(stmt)
        ...     return result.rowcount
        >>> df_conflict.to_sql(name="conflict_table", con=conn, if_exists="append",  # noqa: F821
        ...                    method=insert_on_conflict_nothing)  # doctest: +SKIP
        0

        For MySQL, a callable to update columns ``b`` and ``c`` if there's a conflict
        on a primary key.

        >>> from sqlalchemy.dialects.mysql import insert   # noqa: F811
        >>> def insert_on_conflict_update(table, conn, keys, data_iter):
        ...     # update columns "b" and "c" on primary key conflict
        ...     data = [dict(zip(keys, row)) for row in data_iter]
        ...     stmt = (
        ...         insert(table.table)
        ...         .values(data)
        ...     )
        ...     stmt = stmt.on_duplicate_key_update(b=stmt.inserted.b, c=stmt.inserted.c)
        ...     result = conn.execute(stmt)
        ...     return result.rowcount
        >>> df_conflict.to_sql(name="conflict_table", con=conn, if_exists="append",  # noqa: F821
        ...                    method=insert_on_conflict_update)  # doctest: +SKIP
        2

        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(name='integers', con=engine, index=False,
        ...           dtype={"A": Integer()})
        3

        >>> with engine.connect() as conn:
        ...     conn.execute(text("SELECT * FROM integers")).fetchall()
        [(1,), (None,), (2,)]

        .. versionadded:: 2.2.0

           pandas now supports writing via ADBC drivers

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

        >>> from adbc_driver_sqlite import dbapi  # doctest:+SKIP
        >>> with dbapi.connect("sqlite://") as conn:  # doctest:+SKIP
        ...     df.to_sql(name="users", con=conn)
        3
        r   )sqlr  )r  r  to_sql)r   r#  conr  r  r   ra  r  r   rr  r  s              r   r  zNDFrame.to_sql
  sP    h 	"!!!!!zz#  
 
 	
r   r  protocolrh  pathFilePath | WriteBuffer[bytes]r  c               2    ddl m}  || ||||           dS )a9  
        Pickle (serialize) object to file.

        Parameters
        ----------
        path : str, path object, or file-like object
            String, path object (implementing ``os.PathLike[str]``), or file-like
            object implementing a binary ``write()`` function. File path where
            the pickled object will be stored.

        compression : str or dict, default 'infer'
            For on-the-fly compression of the output data. If 'infer' and
            'path_or_buf' is path-like, then detect compression from the following
            extensions: '.gz',
            '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2'
            (otherwise no compression).
            Set to ``None`` for no compression.
            Can also be a dict with key ``'method'`` set to one of
            {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``, ``'xz'``, ``'tar'``} and
            other key-value pairs are forwarded to
            ``zipfile.ZipFile``, ``gzip.GzipFile``,
            ``bz2.BZ2File``, ``zstandard.ZstdCompressor``, ``lzma.LZMAFile`` or
            ``tarfile.TarFile``, respectively.
            As an example, the following could be passed for faster compression and
            to create a reproducible gzip archive:
            ``compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}``.

        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, 5. 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.

        storage_options : dict, optional
            Extra options that make sense for a particular storage connection, e.g.
            host, port, username, password, etc. For HTTP(S) URLs the key-value pairs
            are forwarded to ``urllib.request.Request`` as header options. For other
            URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are
            forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more
            details, and for more examples on storage options refer `here
            <https://pandas.pydata.org/docs/user_guide/io.html?
            highlight=storage_options#reading-writing-remote-files>`_.

        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)}}
        ... )  # doctest: +SKIP
        >>> original_df  # doctest: +SKIP
           foo  bar
        0    0    5
        1    1    6
        2    2    7
        3    3    8
        4    4    9
        >>> original_df.to_pickle("./dummy.pkl")  # doctest: +SKIP

        >>> unpickled_df = pd.read_pickle("./dummy.pkl")  # doctest: +SKIP
        >>> unpickled_df  # doctest: +SKIP
           foo  bar
        0    0    5
        1    1    6
        2    2    7
        3    3    8
        4    4    9
        r   )	to_pickler  N)pandas.io.pickler  )r   r  r  r  rh  r  s         r   r  zNDFrame.to_pickle  sI    h 	/.....	#+	
 	
 	
 	
 	
 	
r   excelsepr  r  c               4    ddl m}  |j        | f||d| dS )a  
        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_csv.

        Notes
        -----
        Requirements for your platform.

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

        This method uses the processes developed for the package `pyperclip`. A
        solution to render any output string format is given in the examples.

        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

        Using the original `pyperclip` package for any string output format.

        .. code-block:: python

           import pyperclip

           html = df.style.to_html()
           pyperclip.copy(html)
        r   )
clipboardsr  N)r  r  to_clipboard)r   r  r  r   r  s        r   r  zNDFrame.to_clipboardW  s?    L 	)(((((
EEsEEfEEEEEr   c                    t          d          }| j        dk    r|j                            |           S |j                            |           S )aA  
        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()  # doctest: +SKIP
        <xarray.Dataset>
        Dimensions:    (index: 4)
        Coordinates:
          * index      (index) int64 32B 0 1 2 3
        Data variables:
            name       (index) object 32B 'falcon' 'parrot' 'lion' 'monkey'
            class      (index) object 32B 'bird' 'bird' 'mammal' 'mammal'
            max_speed  (index) float64 32B 389.0 24.0 80.5 nan
            num_legs   (index) int64 32B 2 2 4 4

        >>> df["max_speed"].to_xarray()  # doctest: +SKIP
        <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()  # doctest: +SKIP
        <xarray.Dataset>
        Dimensions:  (date: 2, animal: 2)
        Coordinates:
          * date     (date) datetime64[s] 2018-01-01 2018-01-02
          * animal   (animal) object 'falcon' 'parrot'
        Data variables:
            speed    (date, animal) int64 350 18 361 15
        xarrayr   )rG   r  	DataArrayfrom_seriesDatasetfrom_dataframe)r   r  s     r   	to_xarrayzNDFrame.to_xarray  sJ    h ,H559>>#//555>00666r   )r  r`  r   r^  
formattersr_  sparsifyindex_names	bold_rowscolumn_format	longtableescaper  decimalmulticolumnmulticolumn_formatmultirowcaptionr  positionbufbool | SequenceNotStr[str]r  FormattersType | NoneFloatFormatType | Noner  r  r  r  r  r  r  r  r  r  r  str | tuple[str, str] | Noner  r  c                   d S r   r  r   r  r  r`  r   r^  r  r_  r  r  r  r  r  r  r  r  r  r  r  r  r  r  s                         r   rO  zNDFrame.to_latex  	    2 cr   FilePath | WriteBuffer[str]c                   d S r   r  r  s                         r   rO  zNDFrame.to_latex  	    2 sr   NaN."FilePath | WriteBuffer[str] | Nonec               @  $% | j         dk    r|                                 } |t          j        d          dk    }|t          j        d          dk    }|t          j        d          }|t          j        d          }|t          j        d	          }|$t	          |t
                    st          d
          t          | j                  nt                    }t	          |t          t          f          r6t          |          |k    r#t          d| dt          |           d          ||rdnd|d}ddi|}ddi|}t	          t
                    rfd%n%%fd$d}t	          t                    r"$fdt          | j                  D             }nt	          t                    r                    dd          }                    dd          }||                    d|i           ||                    d|i           }|                     d          j        }|D ]/}|                                vr|                    |%i           0nt#          $d           }||g}||g} g }!g }"r)|!                    fd| j        D             dd           |du r|!                    ddi           n7t	          |t          t          f          r|"                    |dd           |g}|du r|!                    dd i           |	du r|!                    d!d d"           d!|||rdnd|r|nd#| |rd$nd%||||||rt	          | j        t(                    rd&nd|
d'}#|                     ||!|"d|i||| |#(          S ))a:  
        Render object to a LaTeX tabular, longtable, or nested table.

        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:: 2.0.0
           Refactored to use the Styler implementation via jinja2 templating.

        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.
        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. Braces must be escaped.
        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
            Use a longtable environment instead of tabular. Requires
            adding a \usepackage{longtable} to your LaTeX preamble.
            By default, the value will be read from the pandas config
            module, and set to `True` if the option ``styler.latex.environment`` is
            `"longtable"`.

            .. versionchanged:: 2.0.0
               The pandas option affecting this argument has changed.
        escape : bool, optional
            By default, the value will be read from the pandas config
            module and set to `True` if the option ``styler.format.escape`` is
            `"latex"`. When set to False prevents from escaping latex special
            characters in column names.

            .. versionchanged:: 2.0.0
               The pandas option affecting this argument has changed, as has the
               default value to `False`.
        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, and is set
            as the option ``styler.sparse.columns``.

            .. versionchanged:: 2.0.0
               The pandas option affecting this argument has changed.
        multicolumn_format : str, default 'r'
            The alignment for multicolumns, similar to `column_format`
            The default will be read from the config module, and is set as the option
            ``styler.latex.multicol_align``.

            .. versionchanged:: 2.0.0
               The pandas option affecting this argument has changed, as has the
               default value to "r".
        multirow : bool, default True
            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, and is set as the option
            ``styler.sparse.index``.

            .. versionchanged:: 2.0.0
               The pandas option affecting this argument has changed, as has the
               default value to `True`.
        caption : str or tuple, optional
            Tuple (full_caption, short_caption),
            which results in ``\caption[short_caption]{full_caption}``;
            if a single string is passed, no short caption will be set.
        label : str, optional
            The LaTeX label to be placed inside ``\label{}`` in the output.
            This is used with ``\ref{}`` in the main ``.tex`` file.

        position : str, optional
            The LaTeX positional argument for tables, to be placed after
            ``\begin{}`` in the output.

        Returns
        -------
        str or None
            If buf is None, returns the result as a string. Otherwise returns None.

        See Also
        --------
        io.formats.style.Styler.to_latex : Render a DataFrame to LaTeX
            with conditional formatting.
        DataFrame.to_string : Render a DataFrame to a console-friendly
            tabular output.
        DataFrame.to_html : Render a DataFrame as an HTML table.

        Notes
        -----
        As of v2.0.0 this method has changed to use the Styler implementation as
        part of :meth:`.Styler.to_latex` via ``jinja2`` templating. This means
        that ``jinja2`` is a requirement, and needs to be installed, for this method
        to function. It is advised that users switch to using Styler, since that
        implementation is more frequently updated and contains much more
        flexibility with the output.

        Examples
        --------
        Convert a general DataFrame to LaTeX with formatting:

        >>> df = pd.DataFrame(dict(name=['Raphael', 'Donatello'],
        ...                        age=[26, 45],
        ...                        height=[181.23, 177.65]))
        >>> print(df.to_latex(index=False,
        ...                   formatters={"name": str.upper},
        ...                   float_format="{:.1f}".format,
        ...                   ))  # doctest: +SKIP
        \begin{tabular}{lrr}
        \toprule
        name & age & height \\
        \midrule
        RAPHAEL & 26 & 181.2 \\
        DONATELLO & 45 & 177.7 \\
        \bottomrule
        \end{tabular}
        r   Nzstyler.latex.environmentr  zstyler.format.escaperM  zstyler.sparse.columnszstyler.latex.multicol_alignzstyler.sparse.indexz&`column_format` must be str or unicodezWriting z cols but got z aliases)r^  r  r  r   r   c                    | z  S r   r  )xr_  s    r   <lambda>z"NDFrame.to_latex.<locals>.<lambda>  s    |a7G r   c                l    t          | t          t          f          r |           S  ||           S r   )r   floatcomplex)r  alt_format_float_format_s     r   _wrapzNDFrame.to_latex.<locals>._wrap  s=    !eW-.. &=3L$}Q'''"{1~~%r   c                F    i | ]\  }}|t          |                    S )r  r   )r  r"  cr  r  s      r   r  z$NDFrame.to_latex.<locals>.<dictcomp>	  s@       Aq 75jm<<<  r   	__index____columns__r{  r  )includec                    | S r   r  r0  s    r   r  z"NDFrame.to_latex.<locals>.<lambda>  s    q r   r  c                    g | ]}|v|	S r  r  )r  r  r  s     r   rJ  z$NDFrame.to_latex.<locals>.<listcomp>%  s#    KKKQ!7:J:Jq:J:J:Jr   r  )subsetr   F)rS  r   r   T)r  r   znaive-tnaivezskip-last;data)hrulessparse_indexsparse_columnsenvironmentmulticol_alignmultirow_alignr  r  r  r  r  clinesr  hiderelabel_indexr  format_indexformat_index_namesrender_kwargs)r  rx  r   rN  r   r   r  r   r  listrF  r  r   rj  r  select_dtypesr  r   r  r   r{   _to_latex_via_styler)&r   r  r  r`  r   r^  r  r_  r  r  r  r  r  r  r  r  r  r  r  r  r  r  lengthbase_format_index_format_column_format_formatters_index_formattercolumn_formatterfloat_columnscolformat_index_format_index_names_hide_relabel_index_render_kwargs_r  r  s&     `   ``                            @@r   rO  zNDFrame.to_latex2  s   \ 9>>==??D)*DEETI>&'=>>'IF +,CDDK%!'!23P!Q!Q()>??H$Zs-K-K$EFFF&-oT\"""3w<<ftUm,, 	UV1F1FSSSc&kkSSSTTT !'1ggT
 

 *0(Cl(C*0!)D|)DlC(( 	)-G-G-G-GMM(M	& 	& 	& 	& 	& >Bj$'' 	B    %dl33  KK 
D)) 	B(nn[$??O)~~mTBB*$$k?%CDDD+%%{4D&EFFF$K ..w.??GM$ = =joo////&&]';<<<= L$<!%[[AAAK&7,n= %' 	LLKKKK$,KKK%    U??LL&),----u.. 	,!!VY"G"GHHH*OME>>LL&'*+++%LL499::: $&*3=;;/00.,..%-:cc7  *'
J??&&"#
 
( (((==&2( ) 
 
 	
r   r  r	  dict | list[dict] | Noner
  r  r  r  dict | Nonec                  ddl m} t          d|           }  || d          }	dD ]r}
t                      |
         }t	          |t
                    r t          |	|
          di | Bt	          |t                    r|D ]} t          |	|
          di | s|i n|}|                    d          r|		                    d	             |	j
        dd
|i|S )a"  
        Render object to a LaTeX tabular, longtable, or nested table.

        Uses the ``Styler`` implementation with the following, ordered, method chaining:

        .. code-block:: python
           styler = Styler(DataFrame)
           styler.hide(**hide)
           styler.relabel_index(**relabel_index)
           styler.format(**format)
           styler.format_index(**format_index)
           styler.to_latex(buf=buf, **render_kwargs)

        Parameters
        ----------
        buf : str, Path or StringIO-like, optional, default None
            Buffer to write to. If None, the output is returned as a string.
        hide : dict, list of dict
            Keyword args to pass to the method call of ``Styler.hide``. If a list will
            call the method numerous times.
        relabel_index : dict, list of dict
            Keyword args to pass to the method of ``Styler.relabel_index``. If a list
            will call the method numerous times.
        format : dict, list of dict
            Keyword args to pass to the method call of ``Styler.format``. If a list will
            call the method numerous times.
        format_index : dict, list of dict
            Keyword args to pass to the method call of ``Styler.format_index``. If a
            list will call the method numerous times.
        render_kwargs : dict
            Keyword args to pass to the method call of ``Styler.to_latex``.

        Returns
        -------
        str or None
            If buf is None, returns the result as a string. Otherwise returns None.
        r   )Stylerr   r  )uuid)r	  r
  r  r  r  Nr  c                    dS )Nztextbf:--rwrap;r  r  s    r   r  z.NDFrame._to_latex_via_styler.<locals>.<lambda>  s    '8 r   r  r  )pandas.io.formats.styler"  r   varsr   r   r  r  rj  	map_indexrO  )r   r  r	  r
  r  r  r  r  r"  stylerkw_namekwsub_kws                r   r  zNDFrame._to_latex_via_stylerR  s/   b 	322222K&&2&&&
 	7 	7G B"d## 7(((..2....B%% 7  7 7F,GFG,,66v6666 ,3[)) 	:88999v8838-888r   )r  r^  r_  r  r`  r   ra  r  r  r  quoting	quotecharlineterminatorr  r  doublequote
escapecharr  ru  rh  str | Callable | Nonebool | list[str]r,  r-  r.  r/  r0  r9   c                   d S r   r  r   r  r  r^  r_  r  r`  r   ra  r  r  r  r,  r-  r.  r  r  r/  r0  r  ru  rh  s                         r   to_csvzNDFrame.to_csv  r  r   0FilePath | WriteBuffer[bytes] | WriteBuffer[str]c                   d S r   r  r4  s                         r   r5  zNDFrame.to_csv  r  r   rD  "c                   t          | t                    r| n|                                 }t          ||||||          }t	          |                              ||||
||||||	||||||          S )a  
        Write object to a comma-separated values (csv) file.

        Parameters
        ----------
        path_or_buf : str, path object, file-like object, or None, default None
            String, path object (implementing os.PathLike[str]), or file-like
            object implementing a write() function. If None, the result is
            returned as a string. If a non-binary file object is passed, it should
            be opened with `newline=''`, disabling universal newlines. If a binary
            file object is passed, `mode` might need to contain a `'b'`.
        sep : str, default ','
            String of length 1. Field delimiter for the output file.
        na_rep : str, default ''
            Missing data representation.
        float_format : str, Callable, default None
            Format string for floating point numbers. If a Callable is given, it takes
            precedence over other numeric formatting parameters, like decimal.
        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.
        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 : {{'w', 'x', 'a'}}, default 'w'
            Forwarded to either `open(mode=)` or `fsspec.open(mode=)` to control
            the file opening. Typical values include:

            - 'w', truncate the file first.
            - 'x', exclusive creation, failing if the file already exists.
            - 'a', append to the end of file if it exists.

        encoding : str, optional
            A string representing the encoding to use in the output file,
            defaults to 'utf-8'. `encoding` is not supported if `path_or_buf`
            is a non-binary file object.

        compression : str or dict, default 'infer'
            For on-the-fly compression of the output data. If 'infer' and
            'path_or_buf' is path-like, then detect compression from the following
            extensions: '.gz',
            '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2'
            (otherwise no compression).
            Set to ``None`` for no compression.
            Can also be a dict with key ``'method'`` set to one of
            {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``, ``'xz'``, ``'tar'``} and
            other key-value pairs are forwarded to
            ``zipfile.ZipFile``, ``gzip.GzipFile``,
            ``bz2.BZ2File``, ``zstandard.ZstdCompressor``, ``lzma.LZMAFile`` or
            ``tarfile.TarFile``, respectively.
            As an example, the following could be passed for faster compression and
            to create a reproducible gzip archive:
            ``compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}``.

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

               Passing compression options as keys in dict is
               supported for compression modes 'gzip', 'bz2', 'zstd', and '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.
        lineterminator : 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.).
        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.

        storage_options : dict, optional
            Extra options that make sense for a particular storage connection, e.g.
            host, port, username, password, etc. For HTTP(S) URLs the key-value pairs
            are forwarded to ``urllib.request.Request`` as header options. For other
            URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are
            forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more
            details, and for more examples on storage options refer `here
            <https://pandas.pydata.org/docs/user_guide/io.html?
            highlight=storage_options#reading-writing-remote-files>`_.

        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
        --------
        Create 'out.csv' containing 'df' without indices

        >>> df = pd.DataFrame(
        ...     [["Raphael", "red", "sai"], ["Donatello", "purple", "bo staff"]],
        ...     columns=["name", "mask", "weapon"],
        ... )
        >>> df.to_csv("out.csv", index=False)  # doctest: +SKIP

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

        >>> df.to_csv(index=False)
        'name,mask,weapon\nRaphael,red,sai\nDonatello,purple,bo staff\n'
        >>> compression_opts = dict(
        ...     method="zip", archive_name="out.csv"
        ... )  # doctest: +SKIP
        >>> df.to_csv(
        ...     "out.zip", index=False, compression=compression_opts
        ... )  # doctest: +SKIP

        To write a csv file to a new folder or nested folder you will first
        need to create it using either Pathlib or os:

        >>> from pathlib import Path  # doctest: +SKIP
        >>> filepath = Path("folder/subfolder/out.csv")  # doctest: +SKIP
        >>> filepath.parent.mkdir(parents=True, exist_ok=True)  # doctest: +SKIP
        >>> df.to_csv(filepath)  # doctest: +SKIP

        >>> import os  # doctest: +SKIP
        >>> os.makedirs("folder/subfolder", exist_ok=True)  # doctest: +SKIP
        >>> df.to_csv("folder/subfolder/out.csv")  # doctest: +SKIP

        Format floats to two decimal places:

        >>> df.to_csv("out1.csv", float_format="%.2f")  # doctest: +SKIP

        Format floats using scientific notation:

        >>> df.to_csv("out2.csv", float_format="{{:.2e}}".format)  # doctest: +SKIP
        )framer`  r   r^  r_  r  )r.  r  r  ru  r  r,  r  ra  r  r  r-  r  r/  r0  rh  )r   rg   rx  r   r   r5  )r   r  r  r^  r_  r  r`  r   ra  r  r  r  r,  r-  r.  r  r  r/  r0  r  ru  rh  r   r{  s                           r   r5  zNDFrame.to_csv  s    l  l33HTT&%
 
 
	 !++22)####!+! 3 
 
 	
r   c                (   t          j        d|           t          |t                    r$t	          t          |           j         d          t          j        |t          j	                  }|dk    r>|j
        dk    r3t          |t          |                     r|                     d          S | j                            ||                     |          d	          }|                     ||j        
                              | d          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'}, default 0
            The axis on which to select elements. ``0`` means that we are
            selecting rows, ``1`` means that we are selecting columns.
            For `Series` this parameter is unused and defaults to 0.
        **kwargs
            For compatibility with :meth:`numpy.take`. Has no effect on the
            output.

        Returns
        -------
        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
        r  z1.take requires a sequence of integers, not slice.r   r   r   Fr   Tr   verifyr  takerq  )nvvalidate_taker   ro  r  r  r   rM  r(  intpr  r   r   r   r   r>  r   r  r   r8  )r   indicesr   r   r  s        r   r>  zNDFrame.take  s   ` 	V$$$gu%% 	::&      *WBG444199**/?T/S/S*99%9(((9>>--d33 " 
 

 ))()GGTT U 
 
 	
r   
drop_levelc                   |                      |          }|                     |          }t          |t                    rt	          d          |t          |t
                    st	          d          |                    |||          \  }}t          d          g| j        z  }|||<   t          |          }	| j
        |	         }
t          |
|
                    |          |           |
S |dk    r|r| |         S | j        }n| j        }t          |t
                    rG|                    |d          \  }}|s*t!          j        |          r|||dz            }n||         }n|                    |          }t          |t&          j                  rY|j        t&          j        k    r-|                                \  }|                     ||          S |                     ||          S t3          |          s||         }t3          |          r||dk    rv| j        dk    r| j        |         S | j                            |          }|                     ||j        	          }
| j        |         |
_        |
                     |           }
n^t3          |          r#| j
        ddt          ||dz             f         }
n,|dk    r| j
        dd|f         }
n| j
        |         }
||
_        |
S )
aZ  
        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", "walks"))
        num_legs     4
        num_wings    0
        Name: (mammal, dog, walks), dtype: int64

        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
        z7list keys are not supported in xs, pass a tuple insteadNzIndex must be a MultiIndex)r%  rC  r   r   r  r   r  )!r  r  r   r  r  r{   get_loc_levelro  r  rF  rt  r_  r  r  r   _get_loc_levelr   
is_integerget_locrM  ndarrayr   bool_nonzeror>  rb   r  r   fast_xs_constructor_sliced_from_mgrr   r   r8  )r   r$  r   r%  rC  rS  locnew_ax_indexerr  ri  r   r  indsnew_mgrs                  r   r  z
NDFrame.xs  s   V $$T**%%c4   	WUVVVfj11 > <=== ..s%J.WWKC d}ty0H HTNHooGYw'FFF11$77@@@M199 !Cy LEEJEeZ(( 	'"11#Q1??NC +>#&& + %cC!Gm 4II %c
I--$$C#rz** 59((!kkmmGT99T955599St9444S>> '!#J	S>> 	%daiiyA~~ |C((i'',,G66wW\6RRF:c?FL((..FFs^^ 	%Yqqq%S1W"5"556FFQYYYqqq#v&FFYs^F$FLr   c                     t          |           r   r   )r   rf  s     r   __getitem__zNDFrame.__getitem__      !$'''r   ro  c                |   | j                             |d          }t          |t          j                  rrt          j        |                    t          j                  t          |                     }t          |t          j                  r| 
                    |d          S |}|                     |          S )zK
        __getitem__ for the case where the key is a slice object.
        getitemr  r   r   )r   _convert_slice_indexerr   rM  rI  r   maybe_indices_to_slicer   rA  r   r>  _slice)r   r$  slobjr  s       r   _getitem_slicezNDFrame._getitem_slice  s     
11#I1FFeRZ(( 	0bg1F1FD		RRG'2:.. 2yyqy111E{{5!!!r   r[  c                "   t          |t                    sJ t          |                      |                     |          }| j                            ||          }|                     ||j                  }|                    |           }|S )zp
        Construct a slice of this container.

        Slicing with this method is *always* positional.
        r   r  )	r   ro  r  r   r   	get_slicer  r   r8  )r   r[  r   rR  ri  s        r   rZ  zNDFrame._slice  s     %''44e44'++D11)%%e$%77++G',+GG$$T**r   c                   d}d}| j         dk    r:t          | j        t                    r 	 || j        j        v}n# t
          $ r Y nw xY w|rWt          |t                    s|f}| j        D ]7}t          |t                    r |dt          |                   |k    r| |= d}8|sA| j        d         	                    |          }| j
                            |          | _
        dS dS )z
        Delete item
        Fr  NTr  )r  r   r  r{   _enginer  rF  r   r   rH  r   idelete)r   r$  deletedmaybe_shortcutr  rN  s         r   __delitem__zNDFrame.__delitem__  s   
 9>>jzBB> "%DL,@!@     	# c5)) f| # #c5)) #c*CHH*o.D.DS	"G 	/ )B-'',,C	))#..DIII	/ 	/s   : 
AAc                D    |r| j         j        st          d          d S d S )NzQCannot specify 'inplace=True' when 'self.flags.allows_duplicate_labels' is False.)r   r   r  )r   r   s     r   r  z2NDFrame._check_inplace_and_allows_duplicate_labels  sB     	4:= 	A  	 	 	 	r   c                R    	 | |         S # t           t          t          f$ r |cY S w xY w)a  
        Get item from object for given key (ex: DataFrame column).

        Returns ``default`` value if not found.

        Parameters
        ----------
        key : object
            Key for which item should be returned.
        default : object, default None
            Default value to return if key is not found.

        Returns
        -------
        same type as items contained in object
            Item for given key or ``default`` value, if key is not found.

        See Also
        --------
        DataFrame.get : Get item from object for given key (ex: DataFrame column).
        Series.get : Get item from object for given key (ex: DataFrame column).

        Examples
        --------
        >>> df = 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"),
        ... )

        >>> df
                    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

        >>> df.get(["temp_celsius", "windspeed"])
                    temp_celsius windspeed
        2014-02-12          24.3      high
        2014-02-13          31.0      high
        2014-02-14          22.0    medium
        2014-02-15          35.0    medium

        >>> ser = df["windspeed"]
        >>> ser.get("2014-02-13")
        'high'

        If the key isn't found, the default value will be used.

        >>> df.get(["temp_celsius", "temp_kelvin"], default="default_value")
        'default_value'

        >>> ser.get("2014-02-10", "[unknown]")
        '[unknown]'
        )r  r  
IndexError)r   r$  defaults      r   r  zNDFrame.get  s=    ~	9*j1 	 	 	NNN	s   
 &&c                v    | t           j        ur*t          j        dt          t                                 d S d S )NzThe copy keyword is deprecated and will be removed in a future version. Copy-on-Write is active in pandas since 3.0 which utilizes a lazy copy mechanism that defers copies until necessary. Use .copy() to make an eager copy if necessary.r  )r   r  r  r  rL   rP   r   s    r   r   zNDFrame._check_copy_deprecationP  sM    s~%%M> +--      &%r   )new_arg_name>Literal['backfill', 'bfill', 'pad', 'ffill', 'nearest'] | Nonelimitc                    |                      |           |                    | j        |||          } | j        di |S )aO  
        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.

            .. deprecated:: 3.0.0

            * 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 False
            This keyword is now ignored; changing its value will have no
            impact on the method.

            .. deprecated:: 3.0.0

                This keyword is ignored and will be removed in pandas 4.0. Since
                pandas 3.0, this method always returns a new object using a lazy
                copy mechanism that defers copies until necessary
                (Copy-on-Write). See the `user guide on Copy-on-Write
                <https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html>`__
                for more details.

        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 must
            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
        )r   rr  rm  	tolerancer  )r   r
  r   reindex)r   r  rr  r   rm  ro  r	  s          r   reindex_likezNDFrame.reindex_like]  s\    j 	$$T***&&"	 ' 
 
 t|  a   r   )r   r   r  r%  ru  IndexLabel | ListLiker'   c                   d S r   r  r   rS  r   r   r  r%  r   ru  s           r   r  zNDFrame.drop  r|  r   )r   r   r  r%  r   ru  c                   d S r   r  rt  s           r   r  zNDFrame.drop  r|  r   c                   d S r   r  rt  s           r   r  zNDFrame.drop  r  r   r  c                  t          |d          }|-||t          d          |                     |          }||i}	n=||*|dk    rt          d          d|i}	| j        dk    r||	d<   nt          d          | }
|	                                D ] \  }}||
                    ||||	          }
!|r|                     |
           d S |
S )
Nr   z2Cannot specify both 'labels' and 'index'/'columns'r   z0Cannot specify both 'axis' and 'index'/'columns'r   r  r  z>Need to specify at least one of 'labels', 'index' or 'columns'r%  ru  )rS   r  r  r  r   
_drop_axisr  )r   rS  r   r   r  r%  r   ru  r2  r   r   s              r   r  zNDFrame.drop  s    &gy99 G$7 !UVVV++D11Iv&DD'"5qyy !STTTU#DyA~~")YP    JJLL 	O 	OLD&!nnVTvnNN 	  %%%4Jr   
only_slicec                   |                      |          }|                     |          }|j        rm|=t          |t                    st          d          |                    |||          }n|                    ||          }|                    |          }nt          |          pt          |t                    }	t          t          j        |                    }|zt          |t                    st          d          |                    |                              |           }
|dk    r&|
                                rt!          | d          nt          |t                    r7|j        dk    r,|	s*|                    d                              |           }
n[|                    |           }
|                    |          d	k                                    }|dk    r|rt!          | d          t          |
j        t(                    r|
                    t,          
          }
|
                                d         }|                    |          }| j        |z
  dz
  }| j                            |||d|          }|                     ||j                  }| j        dk    r| j        |_        |                     |           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.
        only_slice : bool, default False
            Whether indexing along columns should be view-only.

        Nzaxis must be a MultiIndexrx  ru  r  r  r   r   r  r   r   T)r   
allow_dupsrz  r  )!r  r  r  r   r{   AssertionErrorr  get_indexerrj   rF  rW   ro   index_labels_to_arrayr  isinr  r  r   r  r  re   to_numpyr   rK  r>  r  r   reindex_indexerr  r   r#  r   r8  )r   rS  r   r%  ru  rz  axis_numnew_axisr  is_tuple_labelsmasklabels_missingr   rR  ri  s                  r   ry  zNDFrame._drop_axis,  s   2 ((..~~d##> *	* !$
33 F()DEEE99V59HH99VF9;;&&x00GG 2&99VZPU=V=VO"6#?#G#GHHF !$
33 F()DEEE--e4499&AAA W$$$"f#@#@#@AAA4,,BLH,,' - --a0055f===		&)))"&"6"6v">">""D!I!I!K!KW$$$"f#@#@#@AAA$*n55 1}}4}00llnnQ'Gyy))H)h&*)++! , 
 
 ++G',+GG9>>9FL""4(((r   c                    |j         | _         dS )z
        Replace self internals with result.

        Parameters
        ----------
        result : same type as self
        N)r   )r   ri  s     r   r  zNDFrame._update_inplace  s     K			r   r!  c                l    fd}| j         }||                     |          }||i} | j        di |S )a6  
        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.
        axis : {0 or 'index', 1 or 'columns', None}, default None
            Axis to add prefix on

            .. versionadded:: 2.0.0

        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
        c                     |  S r   r  )r  r!  s    r   r  z$NDFrame.add_prefix.<locals>.<lambda>  s    nnn r   Nr  r   r  r{  )r   r!  r   r  r2  rv  s    `    r   
add_prefixzNDFrame.add_prefix  sX    v %$$$(	++D11IQ
 t|%%f%%%r   suffixc                l    fd}| j         }||                     |          }||i} | j        di |S )a5  
        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.
        axis : {0 or 'index', 1 or 'columns', None}, default None
            Axis to add suffix on

            .. versionadded:: 2.0.0

        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
        c                    |   S r   r  )r  r  s    r   r  z$NDFrame.add_suffix.<locals>.<lambda>  s    nFnn r   Nr  r  )r   r  r   r  r2  rv  s    `    r   
add_suffixzNDFrame.add_suffix  sX    v %$$$(	++D11IQ t|%%f%%%r   )r   	ascendingr   r   na_positionignore_indexr$  r  bool | Sequence[bool]r   r8   r  r0   r  rA   c                   d S r   r  r   r   r  r   r   r  r  r$  s           r   sort_valueszNDFrame.sort_values  r|  r   )r   r  r   r  r  r$  c                   d S r   r  r  s           r   r  zNDFrame.sort_values+  r|  r   c                   d S r   r  r  s           r   r  zNDFrame.sort_values8  r  r   	quicksortlastValueKeyFunc | Nonec                    t          |           )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', 'stable'}, default 'quicksort'
             Choice of sorting algorithm. See also :func:`numpy.sort` for more
             information. `mergesort` and `stable` are the only stable algorithms. 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.
        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. The values in the
            returned Series will be used as the keys for sorting.

        Returns
        -------
        DataFrame or None
            DataFrame with sorted values or None if ``inplace=True``.

        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

        Natural sort with the key argument,
        using the `natsort <https://github.com/SethMMorton/natsort>` package.

        >>> df = pd.DataFrame(
        ...     {
        ...         "hours": ["0hr", "128hr", "0hr", "64hr", "64hr", "128hr"],
        ...         "mins": [
        ...             "10mins",
        ...             "40mins",
        ...             "40mins",
        ...             "40mins",
        ...             "10mins",
        ...             "10mins",
        ...         ],
        ...         "value": [10, 20, 30, 40, 50, 60],
        ...     }
        ... )
        >>> df
           hours    mins  value
        0    0hr  10mins     10
        1  128hr  40mins     20
        2    0hr  40mins     30
        3   64hr  40mins     40
        4   64hr  10mins     50
        5  128hr  10mins     60
        >>> from natsort import natsort_keygen
        >>> df.sort_values(
        ...     by=["hours", "mins"],
        ...     key=natsort_keygen(),
        ... )
           hours    mins  value
        0    0hr  10mins     10
        2    0hr  40mins     30
        4   64hr  10mins     50
        3   64hr  40mins     40
        5  128hr  10mins     60
        1  128hr  40mins     20
        r   r  s           r   r  zNDFrame.sort_valuesE  s    J "$'''r   )r   r%  r  r   r  sort_remainingr  r$  r  r(   c       	            d S r   r  
r   r   r%  r  r   r   r  r  r  r$  s
             r   
sort_indexzNDFrame.sort_index  	     sr   )	r   r%  r  r   r   r  r  r  r$  c       	            d S r   r  r  s
             r   r  zNDFrame.sort_index  r  r   c       	            d S r   r  r  s
             r   r  zNDFrame.sort_index
  s	     cr   IndexKeyFunc | Nonec       	   	     D   t          |d          }|                     |          }t          |          }|                     |          }
t	          |
||||||	          }|q|r| }n|                     d          }|rN|dk    r't          t          | j                            |_        n!t          t          |                     |_	        |rd S |S | 
                    |          }| j                            ||d          }|s |j        |                                         }nt          t          |                    }|                    ||           |                     ||j                  }|r|                     |          S |                    | d          S )	Nr   Fr   r   r<  r  r  rq  )rS   r  rR   r  r   r   r}   r   r  r   r   r   r>  r   _sort_levels_monotonicrT  r  r  r8  )r   r   r%  r  r   r   r  r  r  r$  targetr  ri  baxisr  r  s                   r   r  zNDFrame.sort_index  s    &gy99$$T**&y11	%%%E9dK
 
 ? /.. <199%23t|3D3D%E%EFNN#0T#;#;FL t,,T229>>'e>DD  	3}U+BBDDHH$S\\22H%***++H8=+II 	B''///&&tL&AAAr   )	r   r  r   rr  r   r%  
fill_valuerm  ro  ReindexMethod | Noner  Scalar | Nonec       	            |P|Nt          |t                    r9t           j        t                    s j        j        |j        v r j        j        }                     |           |||t          d          |||t          d          |||}n#|}n |r                     |          dk    r|}n|}||d}t          |          }t           fd|
                                D                       r                     d          S                      |||          r                     ||          S                      |||	|
||                               d	
          S )a   
        Conform Series/DataFrame 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
        ----------
        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 False
            This keyword is now ignored; changing its value will have no
            impact on the method.

            .. deprecated:: 3.0.0

                This keyword is ignored and will be removed in pandas 4.0. Since
                pandas 3.0, this method always returns a new object using a lazy
                copy mechanism that defers copies until necessary
                (Copy-on-Write). See the `user guide on Copy-on-Write
                <https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html>`__
                for more details.

        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
        -------
        Series/DataFrame
            Series/DataFrame 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"]
        >>> columns = ["http_status", "response_time"]
        >>> df = pd.DataFrame(
        ...     [[200, 0.04], [200, 0.02], [404, 0.07], [404, 0.08], [301, 1.0]],
        ...     columns=columns,
        ...     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.
        Nz3Cannot specify all of 'labels', 'index', 'columns'.r  r   r  c              3  r   K   | ]1\  }}|                     |                              |          V  2d S r   )r  	identical)r  r2  r  r   s      r   rE  z"NDFrame.reindex.<locals>.<genexpr>X  sO       
 
	2~ NN9%%//33~~~
 
r   Fr   rp  rq  )r   r{   r   r#  r  r   r  r  r   r  r   r   _needs_reindex_multi_reindex_multi_reindex_axesr8  )r   rS  r   r  r   rr  r   r%  r  rm  ro  r   s   `           r   rp  zNDFrame.reindexQ  s   L M!5*-- "tz:66 " 
5;..JOE$$T***!49KQRRR'"5P   !$$GG"E 	d++D11Q66GGE8
 8
 +622  
 
 
 
!%
 
 
 
 
 	)
 99%9((( $$T6599 	9&&tZ888 !!%	6:
 

,tI,
.
.	/r   c                    | }| j         D ]p}||         }	|	|                     |          }
|
                    |	||||          \  }}|                     |          }|                    |||gi|d          }q|S )z%Perform the reindex for all the axes.N)r%  rm  ro  rr  Fr  r}  )r   r  rp  r  _reindex_with_indexers)r   r   r%  rm  ro  rr  r  r   r   rS  r  r  r  r   s                 r   r  zNDFrame._reindex_axesh  s     " 	 	A!WF~""B!#e5If ", " "Iw ((++D,,	7+,%  -  CC 
r   c                r    t          j        |                                 | j        k    o|du o
|du o| j        S )z$Check if we do need a multi reindex.N)ro   count_not_noner   r   _can_fast_transpose)r   r   rr  r%  s       r   r  zNDFrame._needs_reindex_multi  sH     "DKKMM2dnD )$))
 (	
r   c                     t          |           r   r   )r   r   r  s      r   r  zNDFrame._reindex_multi  rU  r   r}  c                   | j         }t          |                                          D ]_}||         \  }}|                     |          }|%t	          |          }|t          |          }|                    |||||          }`|| j         u r|                    d          }|                     ||j	                  
                    |           S )z*allow_dups indicates an internal call hereN)r   r  r}  Fr   r  )r   sortedr  r   r~   rX   r  r   r  r   r8  )	r   
reindexersr  r}  r  r   r   r  r  s	            r   r  zNDFrame._reindex_with_indexers  s     9:??,,-- 	 	D'-NE70066E} ''E"-g66  //%% 0  HH ty  }}%}00H))()GGTT
 
 	
r   likeregexc                  
 t          j        ||          }|dk    rt          d          || j        }|                     |          }|s|                     |          }t          |                              |          }t          |          dk    r|	                    |j
                  } | j        di ||iS r7dfd}|                    |          }	|                     |          |	         S |rKd
fd	}t          j        |          
|                    |          }	|                     |          |	         S t          d
          )a  
        Subset the DataFrame or Series according to the specified index labels.

        For DataFrame, filter rows or columns depending on ``axis`` argument.
        Note that this routine does not filter based on content.
        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, 'columns' for
            ``DataFrame``. For ``Series`` this parameter is unused and defaults to
            ``None``.

        Returns
        -------
        Same type as caller
            The filtered subset of the DataFrame or Series.

        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 exclusiveNr   r   r   c                .    J t          |           v S r   )rY   )r  r  s    r   r  zNDFrame.filter.<locals>.f  s     '''z!}},,r   r   c                L                         t          |                     d uS r   )searchrY   )r  matchers    r   r  zNDFrame.filter.<locals>.f!  s     ~~jmm44D@@r   z,Must pass either `items`, `like`, or `regex`r  r   r   )ro   r  r  r   r  r  rz   intersectionr   r   r   rp  rI  rN  recompile)r   r   r  r  r   nkwrS  r#  r  r   r  s     `       @r   filterzNDFrame.filter  s   V #E47777V   <'D%%&&t,,D%LL--f55E5zzQV\224<004-000 	L- - - - - - ZZ]]F888&&v.. 		LA A A A A A j''GZZ]]F888&&v..JKKKr      nc                D    | j         d|                                         S )aa  
        Return the first `n` rows.

        This function exhibits the same behavior as ``df[:n]``, returning the
        first ``n`` rows based on position. It is useful for quickly checking
        if your object has the right type of data in it.

        When ``n`` is positive, it returns the first ``n`` rows. For ``n`` equal to 0,
        it returns an empty object. When ``n`` is negative, it returns
        all rows except the last ``|n|`` rows, mirroring the behavior of ``df[:n]``.

        If ``n`` is larger than the number of rows, this function returns all rows.

        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rt  r   r   r  s     r   rU  zNDFrame.head*  s!    n y!}!!###r   c                    |dk    r!| j         dd                                         S | j         | d                                         S )a  
        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|:]``.

        If ``n`` is larger than the number of rows, this function returns all rows.

        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
        r   Nr  r  s     r   tailzNDFrame.tail  sH    l 669QqS>&&(((y!~""$$$r   fracfloat | Nonereplacerandom_stateRandomState | Nonec                   |d}|                      |          }| j        |         }t          j        |          }	t	          j        |||          }
|
|J t          ||z            }
|t	          j        | ||          }t	          j        ||
|||	          }|                     ||          }|r!t          t          |                    |_        |S )ug  
        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.
            When replace = False will not allow ``(n * max(weights) / sum(weights)) > 1``
            in order to avoid biased results. See the Notes below for more details.
        random_state : int, array-like, BitGenerator, np.random.RandomState, np.random.Generator, optional
            If int, array-like, or BitGenerator, seed for random number generator.
            If np.random.RandomState or np.random.Generator, use as given.
            Default ``None`` results in sampling with the current state of np.random.
        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. For `Series` this parameter is unused and defaults to `None`.
        ignore_index : bool, default False
            If True, the resulting index will be labeled 0, 1, …, n - 1.

        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`.

        When replace = False will not allow ``(n * max(weights) / sum(weights)) > 1``,
        since that would cause results to be biased. E.g. sampling 2 items without replacement
        with weights [100, 1, 1] would yield two last items in 1/2 of cases, instead of 1/102.
        This is similar to specifying `n=4` without replacement on a Series with 3 elements.

        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
        Nr   r   )r  rG  ro   r  rs   process_sampling_sizer  preprocess_weightsr>  r}   r   r   )r   r  r  r  weightsr  r   r  obj_lenrsrO  sampled_indicesri  s                r   rs   zNDFrame.sample  s    D <D$$T***T"  ..+AtW==<###((D/gtDDG -wLL?66 	6(V55FLr   func!Callable[Concatenate[Self, P], T]argsP.argsP.kwargsr;   c                    d S r   r  r   r  r  r   s       r   pipezNDFrame.pipex  	     Cr   tuple[Callable[..., T], str]c                    d S r   r  r  s       r   r  zNDFrame.pipe  r  r   @Callable[Concatenate[Self, P], T] | tuple[Callable[..., T], str]c                V    t          j        |                     d          |g|R i |S )a  
        Apply chainable functions that expect Series or DataFrames.

        Parameters
        ----------
        func : function
            Function to apply to the Series/DataFrame.
            ``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 Series/DataFrame.
        *args : iterable, optional
            Positional arguments passed into ``func``.
        **kwargs : mapping, optional
            A dictionary of keyword arguments passed into ``func``.

        Returns
        -------
        The return type of ``func``.
            The result of applying ``func`` to the Series or DataFrame.

        See Also
        --------
        DataFrame.apply : Apply a function along input axis of DataFrame.
        DataFrame.map : 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.

        Examples
        --------
        Constructing an income DataFrame from a dictionary.

        >>> data = [[8000, 1000], [9500, np.nan], [5000, 2000]]
        >>> df = pd.DataFrame(data, columns=["Salary", "Others"])
        >>> df
           Salary  Others
        0    8000  1000.0
        1    9500     NaN
        2    5000  2000.0

        Functions that perform tax reductions on an income DataFrame.

        >>> def subtract_federal_tax(df):
        ...     return df * 0.9
        >>> def subtract_state_tax(df, rate):
        ...     return df * (1 - rate)
        >>> def subtract_national_insurance(df, rate, rate_increase):
        ...     new_rate = rate + rate_increase
        ...     return df * (1 - new_rate)

        Instead of writing

        >>> subtract_national_insurance(
        ...     subtract_state_tax(subtract_federal_tax(df), rate=0.12),
        ...     rate=0.05,
        ...     rate_increase=0.02,
        ... )  # doctest: +SKIP

        You can write

        >>> (
        ...     df.pipe(subtract_federal_tax)
        ...     .pipe(subtract_state_tax, rate=0.12)
        ...     .pipe(subtract_national_insurance, rate=0.05, rate_increase=0.02)
        ... )
            Salary   Others
        0  5892.48   736.56
        1  6997.32      NaN
        2  3682.80  1473.12

        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 ``national_insurance`` takes its data as ``df``
        in the second argument:

        >>> def subtract_national_insurance(rate, df, rate_increase):
        ...     new_rate = rate + rate_increase
        ...     return df * (1 - new_rate)
        >>> (
        ...     df.pipe(subtract_federal_tax)
        ...     .pipe(subtract_state_tax, rate=0.12)
        ...     .pipe(
        ...         (subtract_national_insurance, "df"), rate=0.05, rate_increase=0.02
        ...     )
        ... )
            Salary   Others
        0  5892.48   736.56
        1  6997.32      NaN
        2  3682.80  1473.12
        Fr   )ro   r  r   r  s       r   r  zNDFrame.pipe  s5    L {499%900$HHHHHHHr   c           
        t          |t                    r|j        rt          |j                  | _        | j        j        o|j        j        | j        _        t          | j                  t          |j                  z  D ]D}t          |t                    sJ t          
                    | |t          ||d                     Ent          |d          r|j        }t          d |D                       rF|d         j        t          fd|dd         D                       }|rt                    | _        t          d |D                       }|| j        _        | S )a  
        Propagate metadata from other to self.

        This is the default implementation. Subclasses may override this method to
        implement their own metadata handling.

        Parameters
        ----------
        other : the object from which to get the attributes that we are going
            to propagate. If ``other`` has an ``input_objs`` attribute, then
            this attribute must contain an iterable of objects, each with an
            ``attrs`` attribute.
        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.

        Notes
        -----
        In case ``other`` has an ``input_objs`` attribute, this method only
        propagates its metadata if each object in ``input_objs`` has the exact
        same metadata as the others.
        N
input_objsc              3  >   K   | ]}t          |j                  V  d S r   )r   r   )r  r   s     r   rE  z'NDFrame.__finalize__.<locals>.<genexpr>#  s*      33s4	??333333r   r   c              3  .   K   | ]}|j         k    V  d S r   )r   )r  r   r   s     r   rE  z'NDFrame.__finalize__.<locals>.<genexpr>&  s*      %M%MSci5&8%M%M%M%M%M%Mr   r   c              3  .   K   | ]}|j         j        V  d S r   )r   r   )r  r  s     r   rE  z'NDFrame.__finalize__.<locals>.<genexpr>*  s'      )X)Xa!'*I)X)X)X)X)X)Xr   )r   r   r   r   r   r   r>  r   r   r   r   r  hasattrr  r  )	r   r  rr  r   r#  objshave_same_attrsr   r   s	           @r   r8  zNDFrame.__finalize__  sv   : eW%% 	I{ 3
 &ek22

2 8K7 J.
 DN++c%/.B.BB K K!$,,,,,""4wudD/I/IJJJJK UL)) 	I#D33d33333 1Q"%%M%M%M%MDH%M%M%M"M"M" 1!)%DJ&))X)XSW)X)X)X&X&X#1HDJ.r   c                    || j         vr4|| j        vr+|| j        vr"| j                            |          r| |         S t
                              | |          S )z
        After regular attribute access, try looking up the name
        This allows simpler access to columns for interactive use.
        )r   r   r   r@  $_can_hold_identifiers_and_holds_namer   __getattribute__)r   r#  s     r   __getattr__zNDFrame.__getattr__/  sf     000DN**DO++DDTJJ , :&&tT222r   c                   	 t                               | |           t                               | ||          S # t          $ r Y nw xY w|| j        v rt                               | ||           dS || j        v rt                               | ||           dS 	 t          | |          }t          |t                    rt                               | ||           dS || j	        v r|| |<   dS t                               | ||           dS # t          t          f$ rf t          | t                    r1t          |          r"t          j        dt                                 t                               | ||           Y dS w xY w)z
        After regular attribute access, try setting the name
        This allows simpler access to columns for interactive use.
        zPandas doesn't allow columns to be created via a new attribute name - see https://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-accessr  N)r   r  r   AttributeErrorr   r   r  r   rz   r@  r  rg   r^   r  r  rP   )r   r#  r   existings       r   r   zNDFrame.__setattr__@  s   	##D$///%%dD%888 	 	 	D	
 4+++tT511111T^##tT5111116"4..h.. :&&tT599999T_,,!&DJJJ&&tT599999"I. 	6 	6 	6dL11 |E7J7J M@ $4#5#5    ""4u555555	6s/   69 
AAAD	 D	 +D	 	A3F ?F c                    t                                                      }| j        j        r|                    | j        j                   |S )z
        add the string-like attributes from the info_axis.
        If info_axis is a MultiIndex, its first level values are used.
        )super_dir_additionsr@  _can_hold_stringsr  _dir_additions_for_owner)r   	additions	__class__s     r   r  zNDFrame._dir_additionsj  sG     GG**,,	?, 	GT_EFFFr   c                B    | j                                         | _         dS )z)Consolidate data in place and return NoneN)r   consolidater   s    r   _consolidate_inplacezNDFrame._consolidate_inplacex  s     I))++			r   c                    | j                                         }|                     ||j                                      |           S )z
        Compute NDFrame with "consolidated" internals (data of each dtype
        grouped together in a single ndarray).

        Returns
        -------
        consolidated : same type as caller
        r  )r   r  r  r   r8  )r   	cons_datas     r   _consolidatezNDFrame._consolidate~  sG     I))++	)))).)IIVV
 
 	
r   c                t    | j         j        rdS | j         j        rdS | j                                        dk    S )NFTr   )r   r'  any_extension_typesr;  nuniquer   s    r   _is_mixed_typezNDFrame._is_mixed_type  sC     9$ 	59( 	 4{""$$q((r   c                    | j                                         }|                     ||j                                      |           S Nr  )r   get_numeric_datar  r   r8  r   rR  s     r   _get_numeric_datazNDFrame._get_numeric_data  s?    ),,..))')EERRSWXXXr   c                    | j                                         }|                     ||j                                      |           S r  )r   get_bool_datar  r   r8  r  s     r   _get_bool_datazNDFrame._get_bool_data  s?    )))++))')EERRSWXXXr   c                     t          |           r   r   r   s    r   r   zNDFrame.values  s    !$'''r   c                     t          |           )zinternal implementationr   r   s    r   r  zNDFrame._values  s     "$'''r   c                    | j                                         }|                     || j        t          j                  S )a  
        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.

        See Also
        --------
        Series.dtypes : Return the dtype object of the underlying data.

        Examples
        --------
        >>> df = pd.DataFrame(
        ...     {
        ...         "float": [1.0],
        ...         "int": [1],
        ...         "datetime": [pd.Timestamp("20180310")],
        ...         "string": ["foo"],
        ...     }
        ... )
        >>> df.dtypes
        float              float64
        int                  int64
        datetime    datetime64[us]
        string              str
        dtype: object
        )r   r   )r   
get_dtypes_constructor_slicedr@  rM  object_r   s     r   r;  zNDFrame.dtypes  s7    H y##%%''DO2:'VVVr   c                   |                      |           t                    r^| j        dk    rOt                    dk    s	| j        vrt          d          | j                 }|                     |          S ddlm}  |t                    }|j
        D ]}|| vrt          d| d          |                    | j        d	
          }g }t          |                                           D ]\  }	\  }}
|j        |	         }t!          |          r|
                    d          }n:	 |
                    |          }n!# t$          $ r}| d| df|_         d	}~ww xY w|                    |           nt+                    r| j        dk    rt-                    t/          t0                    r;t3          fd| j        j        D                       r|                     d          S fd|                                 D             }nO| j                                      }|                     ||j                  }|                    | d          S |s|                     d          S t?          |d          }|                      |          }| j        |_        |                    | d          }tC          tD          |          S )a  
        Cast a pandas object to a specified dtype ``dtype``.

        This method allows the conversion of the data types of pandas objects,
        including DataFrames and Series, to the specified dtype. It supports casting
        entire objects to a single data type or applying different data types to
        individual columns using a mapping.

        Parameters
        ----------
        dtype : str, data type, Series or Mapping of column name -> data type
            Use a str, numpy.dtype, pandas.ExtensionDtype or Python type to
            cast entire pandas object to the same type. Alternatively, use a
            mapping, e.g. {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 False
            This keyword is now ignored; changing its value will have no
            impact on the method.

            .. deprecated:: 3.0.0

                This keyword is ignored and will be removed in pandas 4.0. Since
                pandas 3.0, this method always returns a new object using a lazy
                copy mechanism that defers copies until necessary
                (Copy-on-Write). See the `user guide on Copy-on-Write
                <https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html>`__
                for more details.

        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
        -------
        same type as caller
            The pandas object casted to the specified ``dtype``.

        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.

        Notes
        -----
        .. versionchanged:: 2.0.0

            Using ``astype`` to convert from timezone-naive dtype to
            timezone-aware dtype will raise an exception.
            Use :meth:`Series.dt.tz_localize` instead.

        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, int32): [1, 2]

        Convert to ordered categorical type with custom ordering:

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

        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[us]
        r   zFOnly the Series name can be used for the key in Series dtype mappings.r|  r   r6  r   zJOnly a column name can be used for the key in a dtype mappings argument. 'z' not found in columns.N)r  Fr   )r   ru  z': Error while type casting for column 'r  c              3  8   K   | ]}|j         j        k    V  d S r   )r   r   )r  blockr   s     r   rE  z!NDFrame.astype.<locals>.<genexpr>  s>       9 905"e+9 9 9 9 9 9r   c                D    g | ]\  }}|                                S )r|  )r   )r  _serr   ru  s      r   rJ  z"NDFrame.astype.<locals>.<listcomp>  s-    SSSFAsszz%z77SSSr   r  r   rq  r   )#r   r\   r  r   r#  r  r   pandasr   r   r   rp  r  r  r   iatrk   r   r  r  r  r]   rc   r   re   r  r   r   r  r   r8  r   r   r   r   )r   r   r   ru  new_typer   	dtype_sercol_nameresultsr"  r  cdtres_colexr  r  ri  s    ` `             r   r   zNDFrame.astype  sl   | 	$$T*** 8	;yA~~u::>>TYe%;%;"<   !+{{8F{;;; &%%%%%uF333I%O  4''">$> > >   ( "))$,4)HHIG&/

&=&= ( ("?HcmA&99 	!hhEh22GG"%**3v*"F"F%   !UU(UUU# 	
 w''''( &e,, 	;Q ''E%00 -S 9 9 9 99=9I9 9 9 6 6 - yyey,,, TSSSSdjjllSSSGG y''eF'CCH,,XHM,JJC##D#:::  	)99%9((( a((( ""6**$$T($;;D&!!!s   6E
E,E''E,r   c                    | j                             |          }|                     ||j                                      | d          S )a  
        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). With Copy-on-Write, changes to the original
        will *not* be reflected in the shallow copy (and vice versa). The
        shallow copy uses a lazy (deferred) copy mechanism that copies the
        data only when any changes to the original or shallow copy are made,
        ensuring memory efficiency while maintaining data integrity.

        .. note::
            In pandas versions prior to 3.0, the default behavior without
            Copy-on-Write was different: changes to the original *were* reflected
            in the shallow copy (and vice versa). See the :ref:`Copy-on-Write
            user guide <copy_on_write>` for more information.

        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
        -------
        Series or DataFrame
            Object type matches caller.

        See Also
        --------
        copy.copy : Return a shallow copy of an object.
        copy.deepcopy : Return a deep copy of an object.

        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.

        Since pandas is not thread safe, see the
        :ref:`gotchas <gotchas.thread-safety>` when copying in a threading
        environment.

        Copy-on-Write protects shallow copies against accidental modifications.
        This means that any changes to the copied data would make a new copy
        of the data upon write (and vice versa). Changes made to either the
        original or copied variable would not be reflected in the counterpart.
        See :ref:`Copy_on_Write <copy_on_write>` for more information.

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

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

        Due to Copy-on-Write, shallow copies still protect data modifications.
        Note shallow does not get modified below.

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

        When the data has object dtype, even a deep copy does not copy the
        underlying Python objects. 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   r  r   rq  )r   r   r  r   r8  )r   r   r   s      r   r   zNDFrame.copy  sR    N y~~4~(())$TY)??LL M 
 
 	
r   c                .    |                      d          S r^  rj  r   s    r   __copy__zNDFrame.__copy__  s    yyey$$$r   c                .    |                      d          S )zq
        Parameters
        ----------
        memo, default None
            Standard signature. Unused
        Tr   rj  )r   memos     r   __deepcopy__zNDFrame.__deepcopy__  s     yydy###r   c                    |                      |           | j                                        }|                     ||j                  }|                    | d          S )ar  
        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.

        Parameters
        ----------
        copy : bool, default False
            This keyword is now ignored; changing its value will have no
            impact on the method.

            .. deprecated:: 3.0.0

                This keyword is ignored and will be removed in pandas 4.0. Since
                pandas 3.0, this method always returns a new object using a lazy
                copy mechanism that defers copies until necessary
                (Copy-on-Write). See the `user guide on Copy-on-Write
                <https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html>`__
                for more details.

        Returns
        -------
        same type as input object
            Returns an object of the same type as the 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
        r  infer_objectsrq  )r   r   convertr  r   r8  )r   r   rR  r  s       r   r/  zNDFrame.infer_objects  s_    n 	$$T***)##%%((w|(DD_===r   numpy_nullabler/  convert_stringconvert_integerconvert_booleanconvert_floatingdtype_backendr    c                    t          |           | j                            ||||||          }|                     ||j                  }|                    | d          S )a  
        Convert columns from numpy dtypes to the best dtypes that support ``pd.NA``.

        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()``.
        convert_floating : bool, defaults True
            Whether, if possible, conversion can be done to floating extension types.
            If `convert_integer` is also True, preference will be give to integer
            dtypes if the floats can be faithfully casted to integers.
        dtype_backend : {'numpy_nullable', 'pyarrow'}, default 'numpy_nullable'
            Back-end data type applied to the resultant :class:`DataFrame` or
            :class:`Series` (still experimental). Behaviour is as follows:

            * ``"numpy_nullable"``: returns nullable-dtype-backed
              :class:`DataFrame` or :class:`Serires`.
            * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype`
              :class:`DataFrame` or :class:`Series`.

            .. versionadded:: 2.0

        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``, ``convert_boolean`` and
        ``convert_floating``, it is possible to turn off individual conversions
        to ``StringDtype``, the integer extension types, ``BooleanDtype``
        or floating extension types, 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
        or floating 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. Otherwise, convert to an
        appropriate floating 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   <NA>
        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: str

        Obtain a Series with dtype ``StringDtype``.

        >>> s.convert_dtypes()
        0       a
        1       b
        2    <NA>
        dtype: string
        )r/  r2  r3  r4  r5  r6  r  convert_dtypesrq  )rQ   r   r8  r  r   r8  )	r   r/  r2  r3  r4  r5  r6  rR  r  s	            r   r8  zNDFrame.convert_dtypesV  sw    T 	M***)**')++-' + 
 
 ((w|(DD-=>>>r   r   r   rm  
limit_area,Literal['ffill', 'bfill', 'pad', 'backfill']None | Axis
None | intr:  #Literal['inside', 'outside'] | Nonec                  |d}|                      |          }t          |          }|dk    r9| j        j        s	|rt          | j                            |||          j        }|S | j                            ||||          }|                     ||j	                  }|r| 
                    |           | S |                    | d          S )Nr   r   )rr  rm  r:  )rr  rm  r:  r   r  fillnarq  )r  r   r   r'  r   r;   _pad_or_backfillpad_or_backfillr  r   r  r8  )r   rr  r   r   rm  r:  ri  rR  s           r   rA  zNDFrame._pad_or_backfill  s     <D$$T**"6**1999, * *))V,,Uz -    M)++!	 , 
 
 ++G',+GG 	>  (((K&&tH&===r   )r   r   rm  'Hashable | Mapping | Series | DataFramec                   t          |d          }|rYt          sRt          j        |           t          k    r5t          j        |           s!t          j        t          t          d           t          |t          t          f          r%t          dt          |          j         d          |d}|                     |          }| j        dk    rt          |t&          t(          f          r\t+          |          s|r| n|                     d	
          S ddlm}  ||          }|                    | j                  }|j        }n5t9          |          sn%t          dt          |          j         d          | j                            |||          }nt          |t&          t(          f          r|r| n|                     d	
          }|dk    rt?          j         | j        !                                          }t+          |          dk    rtE          dt          |                     tG          |j$        dddf         |          s(|%                                }	tE          | d|	           |j&                            |          j&        }|r| '                    |           | }n|(                                D ]\  }
}|
|vr||
                             ||          }|s|||
<   0t          |t(                    r+|j)        ||
         j)        k    r||j*        dd|
f<   j|||
<   p|j+        ,                    |
          }t          |tZ                    r!t]          | j/        d                   |         }n~t          |t`          j1                  r+|j)        j2        dk    r|3                                d         }n9t          |t`          j1                  r|j)        j2        dk    sti          d          tk          |          D ]\\  }}|j$        dd|f         }| j$        dd|f         }|j)        |j)        k    r||j$        dd|f<   F|6                    ||           ]|S t9          |          sM|dk    r)| j&                            ||          j&        }|j        }n| j                            |||          }nmt          |tn                    r9| j        dk    r.| 8                    | 9                                |          j        }ntE          dt          |                     | :                    ||j;                  }|r| '                    |           | S |<                    | d          S )a  
        Fill NA/NaN values with `value`.

        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.
        axis : {0 or 'index'} for Series, {0 or 'index', 1 or 'columns'} for DataFrame
            Axis along which to fill missing values. For `Series`
            this parameter is unused and defaults to 0.
        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
            This is the maximum number of entries along the entire axis
            where NaNs will be filled. Must be greater than 0 if not None.

        Returns
        -------
        Series/DataFrame
            Object with missing values filled.

        See Also
        --------
        ffill : Fill values by propagating the last valid observation to next valid.
        bfill : Fill values by using the next valid observation to fill the gap.
        interpolate : Fill NaN values using interpolation.
        reindex : Conform object to new index.
        asfreq : Convert TimeSeries to specified frequency.

        Notes
        -----
        For non-object dtype, ``value=None`` will use the NA value of the dtype.
        See more details in the :ref:`Filling missing data<missing_data.fillna>`
        section.

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

        Replace all NaN elements with 0s.

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

        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.0
        1  3.0  4.0  2.0  1.0
        2  0.0  1.0  2.0  3.0
        3  0.0  3.0  2.0  4.0

        Only replace the first NaN element.

        >>> df.fillna(value=values, limit=1)
             A    B    C    D
        0  0.0  2.0  2.0  0.0
        1  3.0  4.0  NaN  1.0
        2  NaN  1.0  NaN  3.0
        3  NaN  3.0  NaN  4.0

        When filling using a DataFrame, replacement happens along
        the same column names and same indices

        >>> df2 = pd.DataFrame(np.zeros((4, 4)), columns=list("ABCE"))
        >>> df.fillna(df2)
             A    B    C    D
        0  0.0  2.0  0.0  0.0
        1  3.0  4.0  0.0  1.0
        2  0.0  0.0  0.0  NaN
        3  0.0  3.0  0.0  4.0

        Note that column D is not affected since it is not present in df2.
        r   r  r  z>"value" parameter must be a scalar or dict, but you passed a "r8  Nr   r   Fr   r6  zF"value" parameter must be a scalar, dict or Series, but you passed a ")r   rm  r   z6All columns must have the same dtype, but got dtypes: z" not a suitable type to fill into )r   )rm  br"  zVUnexpected get_loc result, please report a bug at https://github.com/pandas-dev/pandas)r   rm  zinvalid fill value with a r  r@  rq  )=rS   rE   sysgetrefcountrF   ro   is_local_in_caller_framer  r  rM   rJ   r   r  rF  r  r  r   r  r  r   rh   r   r   r  r   rp  r   r  r^   r   r@  algosuniquer  r  rV   rt  rf  r;   r  r   r   rN  r  rH  ro  rs  rG  rM  rI  r   rK  r   r  isetitemrg   whererl   r  r   r8  )r   r   r   r   rm  r   r  ri  unique_dtypesframe_dtyper/  r0  res_klocsr"  rN  res_locr  s                     r   r@  zNDFrame.fillna  s   \ &gy99 		+ ? %& &.4.Md.S.S& M6.#$    edE]++ 	9!%e!59 9 9   <D$$T**9>>%$	!233 5zz F#*E44		u	0E0EE))))))udj11!%(( 0U,0 0 0   y''e5''RRHHi011 K	I$?TT$)))*?*?Fqyy !&TY-A-A-C-C D D}%%))$1..1 1   (AAAqD(95AA "/"4"4"6"6K$ QQKQQ    u557 "((000!F!KKMM (> (>DAq "1I,,Qe,<<E" ">$)q		 $E955 > ;&)/99/4FJqqq!t,, ).F1II  &~55a88%dE22 #(A#7#7#=DD'bj99 	djoQT>T>T#'<<>>!#4DD&tRZ88=AZ_PS=S=S #6!G# # 
 '0oo > >FAs&+jA&6G%)Yqqq#v%6F&}<<6=AAAsF 3 3 &W = = = => Me$$ 		IqyyU%@@B!;9++%ug+VV|,, 	Iazz$**,,66;HHG$u++GGHHH++H8=+II 	>  (((K&&tH&===r   c                  t          |d          }|rYt          sRt          j        |           t          k    r5t          j        |           s!t          j        t          t          d           |                     d||||          S )a	  
        Fill NA/NaN values by propagating the last valid observation to next valid.

        Parameters
        ----------
        axis : {0 or 'index'} for Series, {0 or 'index', 1 or 'columns'} for DataFrame
            Axis along which to fill missing values. For `Series`
            this parameter is unused and defaults to 0.
        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.
        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:: 2.2.0

        Returns
        -------
        Series/DataFrame
            Object with missing values filled.

        See Also
        --------
        DataFrame.bfill : Fill NA/NaN values by using the next valid observation
            to fill the gap.

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

        >>> df.ffill()
             A    B   C    D
        0  NaN  2.0 NaN  0.0
        1  3.0  4.0 NaN  1.0
        2  3.0  4.0 NaN  1.0
        3  3.0  3.0 NaN  4.0

        >>> ser = pd.Series([1, np.nan, 2, 3])
        >>> ser.ffill()
        0   1.0
        1   1.0
        2   2.0
        3   3.0
        dtype: float64
        r   r  r  ffillr9  rS   rE   rF  rG  rF   ro   rH  r  r  rM   rJ   rA  r   r   r   rm  r:  s        r   rS  zNDFrame.ffill  s    d &gy99 		+ ? %& &.4.Md.S.S& M6.#$    $$! % 
 
 	
r   c                  t          |d          }|rYt          sRt          j        |           t          k    r5t          j        |           s!t          j        t          t          d           |                     d||||          S )a
  
        Fill NA/NaN values by using the next valid observation to fill the gap.

        This method fills missing values in a backward direction along the
        specified axis, propagating non-null values from later positions to
        earlier positions containing NaN.

        Parameters
        ----------
        axis : {0 or 'index'} for Series, {0 or 'index', 1 or 'columns'} for DataFrame
            Axis along which to fill missing values. For `Series`
            this parameter is unused and defaults to 0.
        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.
        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:: 2.2.0

        Returns
        -------
        Series/DataFrame
            Object with missing values filled.

        See Also
        --------
        DataFrame.ffill : Fill NA/NaN values by propagating the last valid
            observation to next valid.

        Examples
        --------
        For Series:

        >>> s = pd.Series([1, None, None, 2])
        >>> s.bfill()
        0    1.0
        1    2.0
        2    2.0
        3    2.0
        dtype: float64
        >>> s.bfill(limit=1)
        0    1.0
        1    NaN
        2    2.0
        3    2.0
        dtype: float64

        With DataFrame:

        >>> df = pd.DataFrame({"A": [1, None, None, 4], "B": [None, 5, None, 7]})
        >>> df
              A     B
        0   1.0	  NaN
        1   NaN	  5.0
        2   NaN   NaN
        3   4.0   7.0
        >>> df.bfill()
              A     B
        0   1.0   5.0
        1   4.0   5.0
        2   4.0   7.0
        3   4.0   7.0
        >>> df.bfill(limit=1)
              A     B
        0   1.0   5.0
        1   NaN   5.0
        2   4.0   7.0
        3   4.0   7.0
        r   r  r  bfillr9  rT  rU  s        r   rW  zNDFrame.bfillj  s    z &gy99 		+ ? %& &.4.Md.S.S& M6.#$    $$! % 
 
 	
r   r   r  c                   t          |          st          d          t                    sBt                    s3t	                    s$t          dt                    j                  t          j	        u rBt                    s3t          |          s$t          t                     j         d          t          |d          }|rYt          sRt          j                   t          k    r5t!          j                   s!t%          j        t(          t*          d           t          j	        u r	t                    s|d}t-                                                    }|rt1          |d	di\  }}ng g }}d
 |D             }t3          |          rt5          |          st          d          i }	i }
|D ][\  }}t-          t1          |                                d	di          pg g f\  }}t-          |          |	|<   t-          |          |
|<   \|	|
cn||c                     ||          S  j        s|r n                     d          S t                    rt                    r]t=           t>                    rt          d           fd                                 D             } !                    |||          S t	                    sQ j"        dk    rt          d          fd                                D             } !                    |||          S t          d          t	                    rt	                    sgtG                    z  tG                    tG                    k    r0t          dtG                     dtG                     d           j$        %                    ||          }nMjt          |          sBt	          |          s3t          |          s$t          dt          |          j                                       ||d          S t                    rQ j"        dk    rt          d          fd                                D             } !                    |||          S t	                    sNtM          |          }|r j$        '                    |          }nB j$                            |          }n$t          dt                    j                   (                    ||j)                  }|r *                    |            S |+                     d           S )!a )  
        Replace values given in `to_replace` with `value`.

        Values of the Series/DataFrame 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: regexes 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 regexes 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 optional `value`
                  parameter should not be given.
                - 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 optional `value`
                  parameter should not be specified 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, performs operation inplace.
        regex : bool or same types as `to_replace`, default False
            Whether to interpret `to_replace` and/or `value` as regular
            expressions. Alternatively, this could be a regular expression or a
            list, dict, or array of regular expressions in which case
            `to_replace` must be ``None``.

        Returns
        -------
        Series/DataFrame
            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
        --------
        Series.fillna : Fill NA values.
        DataFrame.fillna : Fill NA values.
        Series.where : Replace values based on boolean condition.
        DataFrame.where : Replace values based on boolean condition.
        DataFrame.map: Apply a function to a Dataframe elementwise.
        Series.map: Map values of Series according to an input mapping or function.
        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([1, 2, 3, 4, 5])
        >>> s.replace(1, 5)
        0    5
        1    2
        2    3
        3    4
        4    5
        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

        **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

        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)``:

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

        If ``None`` is explicitly passed for ``value``, it will be respected:

        >>> s.replace("a", None)
        0      10
        1    None
        2    None
        3       b
        4    None
        dtype: object

        When ``regex=True``, ``value`` is not ``None`` and `to_replace` is a string,
        the replacement will be applied in all columns of the DataFrame.

        >>> df = pd.DataFrame(
        ...     {
        ...         "A": [0, 1, 2, 3, 4],
        ...         "B": ["a", "b", "c", "d", "e"],
        ...         "C": ["f", "g", "h", "i", "j"],
        ...     }
        ... )

        >>> df.replace(to_replace="^[a-g]", value="e", regex=True)
            A  B  C
        0  0  e  e
        1  1  e  e
        2  2  e  h
        3  3  e  i
        4  4  e  j

        If ``value`` is not ``None`` and `to_replace` is a dictionary, the dictionary
        keys will be the DataFrame columns that the replacement will be applied.

        >>> df.replace(to_replace={"B": "^[a-c]", "C": "^[h-j]"}, value="e", regex=True)
            A  B  C
        0  0  e  f
        1  1  e  g
        2  2  e  e
        3  3  d  e
        4  4  e  e
        Nz4'to_replace' must be 'None' if 'regex' is not a boolzYExpecting 'to_replace' to be either a scalar, array-like, dict or None, got invalid type zU.replace must specify either 'value', a dict-like 'to_replace', or dict-like 'regex'.r   r  r  Tr9  c                ,    g | ]}t          |          S r  )r\   )r  r0  s     r   rJ  z#NDFrame.replace.<locals>.<listcomp>9  s    <<<LOO<<<r   zSIf a nested mapping is passed, all values of the top level mapping must be mappingsrX  Fr   z;to_replace and value cannot be dict-like for Series.replacec                f    i | ]-}|                                 v |v ||         |         f.S r  )r  )r  r  r   
to_replacer   s     r   r  z#NDFrame.replace.<locals>.<dictcomp>b  sK       %**,,..3$;; jouSz:3>;;r   r   zISeries.replace cannot specify both a dict-like 'to_replace' and a 'value'c                     i | ]
\  }}||fS r  r  )r  r  to_repr   s      r   r  z#NDFrame.replace.<locals>.<dictcomp>q  s0       1<ffe_  r   z.value argument must be scalar, dict, or Seriesz2Replacement lists must match in length. Expecting z got r  )src_list	dest_listr   r  z|'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_replacec                     i | ]
\  }}||fS r  r  )r  r  valr\  s      r   r  z#NDFrame.replace.<locals>.<dictcomp>  s$    PPPhc33S 1PPPr   )r\  r   r   zInvalid "to_replace" type: r  r  rq  ),rZ   r  rb   ra   r^   r  r  r   r   r  r\   rS   rE   rF  rG  rF   ro   rH  r  r  rM   rJ   r  r   r<  r  r  r  rO  r   r   rh   r  _replace_columnwiser  r   r   replace_listrt   replace_regexr  r   r  r8  )r   r\  r   r   r  r   r  r   are_mappingsto_rep_dict
value_dictr/  r0  mappingr  ri  s   ```             r   r  zNDFrame.replace  s   \	 u~~ 	U*"8STTT j!!		
++		 J''		
 1
##,1 1   CN""$$ #(4U(;(; # ::& B B B   &gy99 		+ ? %& &.4.Md.S.S& M6.#$    CN""
++  #
))++,,E ("E7$77ff "Bf<<V<<<L<   1<(( #D  
 !
! 	1 	1DAq $(QWWYY(Dt(D(D#E#E $JLD&
 &*$ZZKN$(LLJqMM$/!
EE$(&!
E<<
E7%<PPP 9 B&AttDII5I,A,AAJ'' W&& V!$	22 (-       #-??#4#4  G
  33GWeLLL &e,, VyA~~(9     @J@P@P@R@R  G  33GWeLLL#$TUUUj)) 8#E** 6 #Gc*oo5E z??c%jj00$I%(__I I;>u::I I I    911'##	 2   #$U++	#E**	 $E**	
 $A(,U(<A A  
 ||E5'|NNNe$$ 9>>$V   QPPP%++--PPP//%HHH!%(( (
;; 	#y66#-# '  7    HH  $y00#-UG  1    HH  O$z2B2B2KOO   ++H8=+II 	?  (((K&&tI&>>>r   linear)r   rm  r   limit_directionr:  r*   rk  -Literal['forward', 'backward', 'both'] | Nonec          
     L   t          |d          }|rYt          sRt          j        |           t          k    r5t          j        |           s!t          j        t          t          d           |                     |          }| j        r|r| n|                                 S t          |t                    st!          d          |dk    r	| j        dfn| df\  }}	t          |j        t&                    r|dk    rt!          d	          t)          j        ||          }t)          j        ||j                  }
 |j        j        d||
||||d
|}|                     ||j                  }|	r|j        }|r|                     |           | S |                    | d          S )a~  
        Fill NaN values using an interpolation method.

        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. This interpolates values based on
              time interval between observations.
            * 'index': The interpolation uses the numerical values
              of the DataFrame's index to linearly calculate missing values.
            * 'values': Interpolation based on the numerical values
              in the DataFrame, treating them as equally spaced along the index.
            * 'nearest', 'zero', 'slinear', 'quadratic', 'cubic',
              'barycentric', 'polynomial': Passed to
              `scipy.interpolate.interp1d`, whereas 'spline' is passed to
              `scipy.interpolate.UnivariateSpline`. 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)``. Note that,
              `slinear` method in Pandas refers to the Scipy first order `spline`
              instead of Pandas first order `spline`.
            * '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`.

        axis : {{0 or 'index', 1 or 'columns', None}}, default None
            Axis to interpolate along. For `Series` this parameter is unused
            and defaults to 0.
        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, default 'forward'
            Consecutive NaNs will be filled in this direction.

        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).

        **kwargs : optional
            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>`__.

        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 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
        r   r  r  z&'method' should be a string, not None.r   TFrj  z@Only `method=linear` interpolation is supported on MultiIndexes.)rr  r   rm  rk  r:  r   r  interpolaterq  Nr  )rS   rE   rF  rG  rF   ro   rH  r  r  rM   rJ   r  r"  r   r   r   r  r;   r   r{   rq   infer_limit_directionget_interp_indexr   rn  r  r   r  r8  )r   rr  r   rm  r   rk  r:  r   r   should_transposer   r  ri  s                r   rn  zNDFrame.interpolate  s   R &gy99 		+ ? %& &.4.Md.S.S& M6.#$    $$T**: 	4"344		3&#&& 	GEFFF26!))$ci,, 	81C1CR   "7PP(;;'38' 
+!
 
 
 
 ++H8=+II 	XF 	C  (((K&&tM&BBBr   c                |   t          |t                    rt          |          }| j        j        st          d          t          | t                    }|r|t          d          n|| j        }t          |          s|g}t          |          }|s| j        d         }t          | j        t                    rt          || j        j                  }||k     r5|s'|                     | j        |t          j                  S t          j        S |rq| j                            |d          }|dk    r|d	z  }| j        }|dk    r5t%          ||                   r |d	z  }|dk    rt%          ||                    ||         S t          |t&                    s!|rt'          |          nt'          |g          }|r|                                 n-| |                                                             d	
          }|                                r|r7t-          d|           } |                     t          j        || j                  S |r7t-          d|           } |                     t          j        || j                  S t-          d|           } |                     t          j        | j        |d                   S | j                            ||j                   }	|	dk    }
|                     |	          }||_        |
                                rt          j        |j        |
<   |r|n|j        d         S )aZ  
        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

        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)
        np.float64(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)
        np.float64(2.0)

        Take all columns into consideration

        >>> df = pd.DataFrame(
        ...     {
        ...         "a": [10.0, 20.0, 30.0, 40.0, 50.0],
        ...         "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
        zasof requires a sorted indexNzsubset is not valid for Seriesr   )freq)r   r#  r   right)sider   r   r   )r   r#  r   r  r  )r   r   r   r   is_monotonic_increasingr  rh   r  r^   r|   r   rs  r  rM  float64nansearchsortedr  rk   rz   r  r  r   r   r#  	asof_locsr>  rN  rt  )r   rL  r  	is_seriesis_liststartrN  r   nullsrP  r  r   s               r   asofzNDFrame.asof  s5   N eS!! 	%e$$Ez1 	=;<<<tY//	 	"! !ABBB " ~'' " u%% 	#JqME$*k22 <u4:?;;;u}}  33"lbj 4    v  #j--e'-BB771HCAgg$vc{"3"3g1HC Agg$vc{"3"3gc{"%'' 	@$+?E%LLLwE(M		d6l.?.?.A.A.E.E1.E.M.M99;; 	 
Hd++((u49(MMM K..((udl(SSSK..//F$,U1X 0    z##EEM>:: rzyy
88:: 	$  VDHTN1ttDIbM1r   c                J    t          |                               | d          S )a  
        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.

        Returns
        -------
        Series/DataFrame
            Mask of bool values for each element in Series/DataFrame
            that indicates whether an element is an NA value.

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

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

        >>> df = pd.DataFrame(
        ...     dict(
        ...         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        NaN
        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
        rk   rq  rk   r8  r   s    r   rk   zNDFrame.isnaM   s$    J Dzz&&tF&;;;r   c                J    t          |                               | d          S )a!  
        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.

        Returns
        -------
        Series/DataFrame
            Mask of bool values for each element in Series/DataFrame
            that indicates whether an element is an NA value.

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

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

        >>> df = pd.DataFrame(
        ...     dict(
        ...         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        NaN
        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
        isnullrq  r  r   s    r   r  zNDFrame.isnull   s$    J Dzz&&tH&===r   c                J    t          |                               | d          S ):  
        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.
        NA values, such as None or :attr:`numpy.NaN`, get mapped to False
        values.

        Returns
        -------
        Series/DataFrame
            Mask of bool values for each element in Series/DataFrame
            that indicates whether an element is not an NA value.

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

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

        >>> df = pd.DataFrame(
        ...     dict(
        ...         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        NaN
        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
        rl   rq  rl   r8  r   s    r   rl   zNDFrame.notna   s$    J T{{''W'===r   c                J    t          |                               | d          S )r  notnullrq  r  r   s    r   r  zNDFrame.notnull"!  s$    J T{{''Y'???r   c                h   |!t          j        t          |                    s#|0t          j        t          |                    rt          d          | }|                                 }|!|| |k    z  }|                    |||          }|!|| |k    z  }|                    |||          }|S )Nz*Cannot use an NA value as a clip thresholdrQ  )rM  r  rk   r  rL  )r   lowerupperr   ri  r  conds          r   _clip_with_scalarzNDFrame._clip_with_scalari!  s    "&e"5"5"&e"5"5IJJJyy{{45=)D\\$w\??F45=)D\\$w\??Fr   c                   ||                      |          }t          |          rJt          |          r;|j        dk    r|                     d ||          S |                     |d |          S t          |t                    s_t          |          rPt          | t                    r|                     || j	                  }n| 
                    ||d           d         }t          |          r:|j        dk    rt          j        nt          j         }|                    |          }n|} |||          t          |           z  }|                     ||||          S )NlerQ  )r   )flexr   r   r  )r  rb   r_   r   r  r   rh   r^   r   r   _align_for_oprM  r\  r@  rk   rL  )r   	thresholdrr  r   r   r  threshold_infr  s           r   _clip_with_one_boundzNDFrame._clip_with_one_bound|!  sv   ((..D Y 	LIi$8$8 	L$&&--dIw-OOO)))T7)KKK
 9i00 	Nl96M6M 	N$	** N --itz-JJ		 ..y$T.JJ1M	 	"" 	&#)?d#:#:J%,,Z88MM%MD111DJJ> zz&)$zHHHr   r  c                  t          |d          }|rYt          sRt          j        |           t          k    r5t          j        |           s!t          j        t          t          d           t          j        |d|          }||                     |          }t          |          }t          |          st!          j        |          rd}nt!          j        |          rd}t          |          }t          |          st!          j        |          rd}nt!          j        |          rd}|@|>t'          |          r/t'          |          r t)          ||          t+          ||          }}|t-          |          r)|t-          |          r|                     |||          S | }||                    || j        ||          }|"|r| }|                    || j        ||          }|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. A missing
            threshold (e.g `NA`) will not clip the value.
        upper : float or array-like, default None
            Maximum threshold value. All values above this
            threshold will be set to it. A missing
            threshold (e.g `NA`) will not clip the value.
        axis : {{0 or 'index', 1 or 'columns', None}}, default None
            Align object with lower and upper along the given axis.
            For `Series` this parameter is unused and defaults to `None`.
        inplace : bool, default False
            Whether to perform the operation in place on the data.
        **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:

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

        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

        Clips using specific lower threshold per column element, with missing values:

        >>> t = pd.Series([2, -4, np.nan, 6, 3])
        >>> t
        0    2.0
        1   -4.0
        2    NaN
        3    6.0
        4    3.0
        dtype: float64

        >>> df.clip(t, axis=0)
        col_0  col_1
        0      9.0    2.0
        1     -3.0   -4.0
        2      0.0    6.0
        3      6.0    8.0
        4      5.0    3.0
        r   r  r  r  NrQ  )rr  r   r   )rS   rE   rF  rG  rF   ro   rH  r  r  rM   rJ   r?  validate_clip_with_axisr  rk   r^   rM  r  r  rb   minmaxr_   r  r  ger  )	r   r  r  r   r   r   
isna_lower
isna_upperri  s	            r   clipzNDFrame.clip!  s;   l &gy99 		+ ? %& &.4.Md.S.S& M6.#$    )$F;;((..D %[[
E"" 	vj!! VJ 	E%[[
E"" 	vj!! VJ 	E !%   "%   " ue,,c%.?.?5E MYu--MEMYuEUEUM))%)HHH00dgD' 1  F  00dgD' 1  F r   rs  r&   FillnaOptions | NonehowLiteral['start', 'end'] | None	normalizeHashable | Nonec                0    ddl m}  || |||||          S )a  
        Convert time series to specified frequency.

        Returns the original data conformed to a new index with the specified
        frequency.

        If the index of this Series/DataFrame is a :class:`~pandas.PeriodIndex`, the
        new index is the result of transforming the original index with
        :meth:`PeriodIndex.asfreq <pandas.PeriodIndex.asfreq>` (so the original index
        will map one-to-one to the new index).

        Otherwise, the new index will be equivalent to ``pd.date_range(start, end,
        freq=freq)`` where ``start`` and ``end`` are, respectively, the min and
        max entries in the original index (see :func:`pandas.date_range`). The
        values corresponding to any timesteps in the new index which were not present
        in the original index will be null (``NaN``), unless a method for filling
        such unknowns is provided (see the ``method`` parameter below).

        The :meth:`resample` method is more appropriate if an operation on each group of
        timesteps (such as an aggregate) 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 based on the order of the index
            * '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
        -------
        Series/DataFrame
            Series/DataFrame object reindexed 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
        :ref:`this link<timeseries.offset_aliases>`.

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

        >>> index = pd.date_range("1/1/2000", periods=4, freq="min")
        >>> 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)rr  r  r  r  )pandas.core.resampler  )r   rs  rr  r  r  r  r  s          r   r  zNDFrame.asfreqQ"  sB    d 	0/////v!
 
 
 	
r   r  c                   |d}|                      |          }|                     |          }t          |t                    st	          d          |                    ||          }|                     ||          S )a  
        Select values at particular time of day (e.g., 9:30AM).

        Parameters
        ----------
        time : datetime.time or str
            The values to select.
        asof : bool, default False
            This parameter is currently not supported.
        axis : {0 or 'index', 1 or 'columns'}, default 0
            For `Series` this parameter is unused and defaults to 0.

        Returns
        -------
        Series or DataFrame
            The values with the specified time.

        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
        Nr   Index must be DatetimeIndex)r  r   )r  r  r   ry   r  indexer_at_timer>  )r   timer  r   r   r  s         r   at_timezNDFrame.at_time"  s    ` <D$$T**t$$%// 	;9:::''4'88yyty,,,r   both	inclusiver+   c                *   |d}|                      |          }|                     |          }t          |t                    st	          d          t          |          \  }}|                    ||||          }|                     ||          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.
        inclusive : {"both", "neither", "left", "right"}, default "both"
            Include boundaries; whether to set each bound as closed or open.
        axis : {0 or 'index', 1 or 'columns'}, default 0
            Determine range time on index or columns value.
            For `Series` this parameter is unused and defaults to 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
        Nr   r  )include_startinclude_endr   )r  r  r   ry   r  rT   indexer_between_timer>  )	r   
start_timeend_timer  r   r   left_inclusiveright_inclusiver  s	            r   between_timezNDFrame.between_time
#  s    H <D$$T**t$$%// 	;9:::*<Y*G*G',,('	 - 
 
 yyty,,,r   r}  	start_dayclosedLiteral['right', 'left'] | None
convention!Literal['start', 'end', 's', 'e']onoriginstr | TimestampConvertibleTypesoffset TimedeltaConvertibleTypes | None
group_keysr   c
                T    ddl m}
  |
t          d|           |||||||||	
  
        S )a3  
        Resample time-series data.

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

        Parameters
        ----------
        rule : DateOffset, Timedelta or str
            The offset string or object representing target conversion.
        closed : {{'right', 'left'}}, default None
            Which side of bin interval is closed. The default is 'left'
            for all frequency offsets except for 'ME', 'YE', 'QE', 'BME',
            'BA', 'BQE', 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 'ME', 'YE', 'QE', 'BME',
            'BA', 'BQE', 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`.
        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 : 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 string, must be Timestamp convertible or one of the following:

            - '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

            - 'end': `origin` is the last value of the timeseries
            - 'end_day': `origin` is the ceiling midnight of the last day

            .. note::

                Only takes effect for Tick-frequencies (i.e. fixed frequencies like
                days, hours, and minutes, rather than months or quarters).
        offset : Timedelta or str, default is None
            An offset timedelta added to the origin.

        group_keys : bool, default False
            Whether to include the group keys in the result index when using
            ``.apply()`` on the resampled object.

            .. versionchanged:: 2.0.0

                ``group_keys`` now defaults to ``False``.

        Returns
        -------
        pandas.api.typing.Resampler
            :class:`~pandas.core.Resampler` object.

        See Also
        --------
        Series.resample : Resample a Series.
        DataFrame.resample : Resample a DataFrame.
        groupby : Group Series/DataFrame by mapping, function, label, or list of labels.
        asfreq : Reindex a Series/DataFrame with the given frequency without grouping.

        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="min")
        >>> 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: min, dtype: int64

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

        >>> series.resample("3min").sum()
        2000-01-01 00:00:00     3
        2000-01-01 00:03:00    12
        2000-01-01 00:06:00    21
        Freq: 3min, 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).

        >>> series.resample("3min", 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: 3min, dtype: int64

        To include this value close the right side of the bin interval,
        as shown below.

        >>> series.resample("3min", 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: 3min, 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 ``ffill`` method.

        >>> series.resample("30s").ffill()[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(arraylike):
        ...     return np.sum(arraylike) + 5
        >>> series.resample("3min").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: 3min, 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="Y", periods=2)
        ... )
        >>> s
        2012    1
        2013    2
        Freq: Y-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.

        >>> df = pd.DataFrame([10, 11, 9, 13, 14, 18, 17, 19], columns=["price"])
        >>> df["volume"] = [50, 60, 40, 100, 50, 100, 40, 50]
        >>> 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("ME", 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")
        >>> df2 = pd.DataFrame(
        ...     [
        ...         [10, 50],
        ...         [11, 60],
        ...         [9, 40],
        ...         [13, 100],
        ...         [14, 50],
        ...         [18, 100],
        ...         [17, 40],
        ...         [19, 50],
        ...     ],
        ...     columns=["price", "volume"],
        ...     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: 7min, 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: 17min, 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: 17min, 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: 17min, 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: 17min, 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: 17min, dtype: int64

        If you want to take the largest Timestamp as the end of the bins:

        >>> ts.resample("17min", origin="end").sum()
        2000-10-01 23:35:00     0
        2000-10-01 23:52:00    18
        2000-10-02 00:09:00    27
        2000-10-02 00:26:00    63
        Freq: 17min, dtype: int64

        In contrast with the `start_day`, you can use `end_day` to take the ceiling
        midnight of the largest Timestamp as the end of the bins and drop the bins
        not containing data:

        >>> ts.resample("17min", origin="end_day").sum()
        2000-10-01 23:38:00     3
        2000-10-01 23:55:00    15
        2000-10-02 00:12:00    45
        2000-10-02 00:29:00    45
        Freq: 17min, dtype: int64
        r   )get_resamplerzSeries | DataFrame)	rs  r  r  r  r$  r%  r  r  r  )r  r  r   )r   ruler  r  r  r  r%  r  r  r  r  s              r   resamplezNDFrame.resample_#  sY    \ 	766666}%t,,!!
 
 
 	
r   averagekeep2Literal['average', 'min', 'max', 'first', 'dense']numeric_only	na_option Literal['keep', 'top', 'bottom']pctc                   
                       |          
dvrd}t          |          
 fd}|rC j        dk    r#t           j                  st          d                                           }	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.
            For `Series` this parameter is unused and defaults to 0.
        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, default False
            For DataFrame objects, rank only numeric columns if set to True.

            .. versionchanged:: 2.0.0
                The default value of ``numeric_only`` is now ``False``.

        na_option : {'keep', 'top', 'bottom'}, default 'keep'
            How to rank NaN values:

            * keep: assign NaN rank to NaN values
            * top: assign lowest rank to NaN values
            * bottom: assign highest rank to NaN values

        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.DataFrameGroupBy.rank : Rank of values within each group.
        core.groupby.SeriesGroupBy.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

        Ties are assigned the mean of the ranks (by default) for the group.

        >>> s = pd.Series(range(5), index=list("abcde"))
        >>> s["d"] = s["b"]
        >>> s.rank()
        a    1.0
        b    2.5
        c    4.0
        d    2.5
        e    5.0
        dtype: float64

        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
        >   topr  bottomz3na_option must be one of 'keep', 'top', or 'bottom'c                :   | j         dk    r| j        }n| j        }t          |t                    r|                              }nt          j        |          } 	j        |fi | 	                                }|
                    	d          S )Nr  )r   rr  r  r  r  rankrq  )r  r   r  r   ru   _rankrI  r  r   r
  r8  )
r   r   ranks	ranks_objr  r  rr  r  r  r   s
       r   rankerzNDFrame.rank.<locals>.rankerR%  s    yA~~ &.11 !!'' %   
!!''   *)%OO43L3L3N3NOOI))$v)>>>r   r   zDSeries.rank does not allow numeric_only=True with non-numeric dtype.)r  r  r  r`   r   r  r  )r   r   rr  r  r  r  r  r  r  r   r  s   ` ` ```   @r   r  zNDFrame.rank$  s    ` ((..555GCS//!	? 	? 	? 	? 	? 	? 	? 	? 	? 	?:  		yA~~&6tz&B&B~)   ))++DDDvd||r   r   r  
align_axis
keep_shape
keep_equalresult_namesr:   c           	        t          |           t          |          urAt          |           j        t          |          j        }}t          d| d| d| d          | |k    |                                 |                                z  z   }|                    dd           |s*|                     |          } |                    |          }|snt          | t                    rI|                                }	|                    d          }
| j	        |
|	f         } |j	        |
|	f         }n| |         } ||         }t          |t                    s t          d	t          |           d
          |dv rd}n|                     |          }t          | |g||          }|| j        k    r|S |                    |          }t          j        |j                  }t          j        t'          |                    |_        g t)          d|j                  d}t          |t                    r|                    ||          }n|                    |          }||         |                    |          _        t          j        |j        |                                       d|j        |         dz  g          j                            d          }|                    ||          }|S )a  
        Compare to another Series/DataFrame and show the differences.

        Parameters
        ----------
        other : Series/DataFrame
            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.

        result_names : tuple, default ('self', 'other')
            Set the dataframes names in the comparison.
        zcan only compare 'z' (not 'z	') with 'r  TrQ  r   r   zPassing 'result_names' as a z= is not supported. Provide 'result_names' as a tuple instead.)r   r  )r   r  r   r  r  )r  r   r  rk   r@  rL  r   rg   r  rN  rF  r  r   r  r  rM  r)  r  aranger   rs  nlevelsreorder_levelsrG  reshaper;   r>  )r   r  r  r  r  r  cls_self	cls_otherr  cmaskrmaskr   diffr  ax_namesorderrB  s                    r   comparezNDFrame.compare|%  s   F ::T%[[(("&t**"5tE{{7KiHVXVVyVV8VVV  
 %-DIIKK%**,,$>?@D$''' 	&::d##DKK%%E 	$$-- $

a((xu-	%,/Dzd,.. 	HtL/A/A H H H  
 ''DD((44D 5M
 
 
 49 K^^D!!8BH%% 9S]]++ +%2:&&**dL)) 	.&&u4&88DD&&u--D +35/D!!' Idj&''WaD)Q./00wwr{{ 	
 yyty,,r   outerr1   rH  r   tuple[Self, NDFrameT]c                   |                      |           ||                     |          }t          |t                    r|                     |||||          \  }}}	nSt          |t
                    r|                     |||||          \  }}}	nt          dt          |                     t          t          |          }
| j        dk    s|dk    rut          |j        j        t                    rV|j        j        |
j        j        k    r<|	:|                    d          }|
                    d          }
|	|_        |	|
_        |                    |           }|
                    |          }
||
fS )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
            The object to align with.
        join : {{'outer', 'inner', 'left', 'right'}}, default 'outer'
            Type of alignment to be performed.

            * left: use only keys from left frame, preserve key order.
            * right: use only keys from right frame, preserve key order.
            * outer: use union of keys from both frames, sort keys lexicographically.
            * inner: use intersection of keys from both frames,
              preserve the order of the left keys.

        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 False
            This keyword is now ignored; changing its value will have no
            impact on the method.

            .. deprecated:: 3.0.0

                This keyword is ignored and will be removed in pandas 4.0. Since
                pandas 3.0, this method always returns a new object using a lazy
                copy mechanism that defers copies until necessary
                (Copy-on-Write). See the `user guide on Copy-on-Write
                <https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html>`__
                for more details.

        fill_value : scalar, default np.nan
            Value to use for missing values. Defaults to NaN, but can be any
            "compatible" value.

        Returns
        -------
        tuple of (Series/DataFrame, type of other)
            Aligned objects.

        See Also
        --------
        Series.align : Align two objects on their axes with specified join method.
        DataFrame.align : Align two objects on their axes with specified join method.

        Examples
        --------
        >>> df = pd.DataFrame(
        ...     [[1, 2, 3, 4], [6, 7, 8, 9]], columns=["D", "B", "E", "A"], index=[1, 2]
        ... )
        >>> other = pd.DataFrame(
        ...     [[10, 20, 30, 40], [60, 70, 80, 90], [600, 700, 800, 900]],
        ...     columns=["A", "B", "C", "D"],
        ...     index=[2, 3, 4],
        ... )
        >>> df
           D  B  E  A
        1  1  2  3  4
        2  6  7  8  9
        >>> other
            A    B    C    D
        2   10   20   30   40
        3   60   70   80   90
        4  600  700  800  900

        Align on columns:

        >>> left, right = df.align(other, join="outer", axis=1)
        >>> left
           A  B   C  D  E
        1  4  2 NaN  1  3
        2  9  7 NaN  6  8
        >>> right
            A    B    C    D   E
        2   10   20   30   40 NaN
        3   60   70   80   90 NaN
        4  600  700  800  900 NaN

        We can also align on the index:

        >>> left, right = df.align(other, join="outer", axis=0)
        >>> left
            D    B    E    A
        1  1.0  2.0  3.0  4.0
        2  6.0  7.0  8.0  9.0
        3  NaN  NaN  NaN  NaN
        4  NaN  NaN  NaN  NaN
        >>> right
            A      B      C      D
        1    NaN    NaN    NaN    NaN
        2   10.0   20.0   30.0   40.0
        3   60.0   70.0   80.0   90.0
        4  600.0  700.0  800.0  900.0

        Finally, the default `axis=None` will align on both index and columns:

        >>> left, right = df.align(other, join="outer", axis=None)
        >>> left
             A    B   C    D    E
        1  4.0  2.0 NaN  1.0  3.0
        2  9.0  7.0 NaN  6.0  8.0
        3  NaN  NaN NaN  NaN  NaN
        4  NaN  NaN NaN  NaN  NaN
        >>> right
               A      B      C      D   E
        1    NaN    NaN    NaN    NaN NaN
        2   10.0   20.0   30.0   40.0 NaN
        3   60.0   70.0   80.0   90.0 NaN
        4  600.0  700.0  800.0  900.0 NaN
        NrH  r   r%  r  zunsupported type: r   r   Fr   )r   r  r   rg   _align_framerh   _align_seriesr  r  r   r1   r  r   r   rd   tzr   r8  )r   r  rH  r   r%  r   r  left_right
join_indexrt  s              r   alignzNDFrame.align%  s   z 	$$T*** ((..De\** 	@'+'8'8% (9 ( ($D&** y)) 		@'+'9'9% (: ( ($D&** >e>>???Xv&&9>>TQYY $**O<< 1:=EKN22!-  $yyey44 %


 6 6%/
&0  &&""5))U{r   r   $tuple[Self, DataFrame, Index | None]c                "   d\  }}d\  }}	d\  }
}t          | t                    }||dk    rF| j                            |j                  s'| j                            |j        ||d          \  }}}	||dk    rH|sF| j                            |j                  s'| j                            |j        ||d          \  }}
}|rd||gi}n	||g||
gd}|                     ||d          }|                    ||	g||gd|d          }|||fS )NNNr   Tr  r%  return_indexersr   )r   r   r  )r   rh   r   r  rH  r  r  )r   r  rH  r   r%  r  r  join_columnsilidxiridxclidxcridxr{  r  r  rt  s                   r   r  zNDFrame._align_frame&  sy    $. 
L!u!utY//	LDAIItz/@/@/M/MI'+zUD (7 ( ($Ju
 \TQYY 'L''66 ' *.):):4ud *; * *&L%  	Lj%01JJ(%0lE5JKKJ**:$ + 
 
 ,,U#u(=>>! - 
 

 UJ&&r   r   !tuple[Self, Series, Index | None]c                   t          | t                    }|s||dvrt          d          |r|dk    rt          d          |s| j                            |j                  rd\  }}}	n'| j                            |j        ||d          \  }}}	|r|                     ||          }
nT|||                     d	          }
n9| j        	                    ||d
          }| 
                    ||j                  }
|                    ||	          }n| j        }| j        d         }d\  }}	|                    |j                  s"|                    |j        ||d          \  }}}	|-|                     d          }|	                    |||
          }| 
                    ||j                  }
|                    ||	          }t          |          }|r*|
                    |          }
|                    |          }|
||fS )N)Nr   r   zMust specify axis=0 or 1r   z1cannot align series to a series other than axis 0NNNTr  Fr   r   r  r  )r   rh   r  r   r  rH  _reindex_indexerr   r   r  r  r   r   rl   r@  )r   r  rH  r   r%  r  r{  r  lidxridxr  rR  rt  fdatar   fill_nas                   r   r  zNDFrame._align_series&  sM    tY//	 	9dlt</G/G7888 	RPQQQ  #	=z  -- )9&
D$$)-KT *9 * *&
D$  N,,Z>>!3yyey,,)33J13MM11'1MM**:t<<EE IE1J#JD$$$U[11 )3KT *9 * *&
D$ 66q99--j$W-MM--e%*-EED**:t<<E 
## 	-;;z**DLL,,EUJ&&r   r   r   r%  c          	         t          |d          }|                     |          }t          j                   t	          t
                    rj        dk    rf j        dk    r[                    t          	                    t          t           j                                      d           j        _                             d          d	         ngt          d
          st          j                  j         j        k    rt%          d            j        fi                                  ddit+          |          }                    |                                          d}j        st	          t2                    s8t5                    s(t7          |                    j                            nj        j        D ]>}t5          |j                  s(t7          |                    |j                            ?j        j         r: j        !                    t*          |          fi                                 n"                    t*                    |r n#                     j$         j%                  t	          t
                    rj         j        k    r                     d||d          d         |&                               stN          j         j        k     rFj(        t	          t          j)                  rS|d	k    rt          j*        d          n|dk    rt          j*        d          t          j+         j                  n|d	k    r) fdt           j        d                   D             }	n.|dk    r( fdt           j        d                   D             }	                     t          tY          |	                              }
 j-        |
_-         j        |
_        |r .                    |
            S |
/                               S n<ta          d          t	          tb          t
          f          ste          d          t	          t          j)        tf          f          rOj         j        k    r j        dk    rt%          d          n$  j        fi                                  ddi|d	} j        ti          dd	          k    rd}n                     |          dk    }|rP j        5                    |          } 6                    ||j7                  } .                    |            S  j        8                    |          } 6                    ||j7                  }|/                               S )z
        Equivalent to public method `where`, except that `other` is not
        applied as a function even if callable. Used in __setitem__.
        r   Nr   r  Frj  rt  )rH  r   rG  z,Array conditional must be same shape as selfr   z5Boolean array expected for the condition, not {dtype}r   )r   na_valuer   r  r  )r  r   )r   r  c                x    g | ]6}j         d d |f                             j         d d |f                   7S r   )rt  _wherer  r"  r  r  r   s     r   rJ  z"NDFrame._where.<locals>.<listcomp>]'  s]     ( ( (
 %&	 !%	!!!Q$ 6 6$(IaaadO$)!" !"( ( (r   c           
         g | ]a}j         d d |f                             j         d d |f         ||dz                                t                                        bS )Nr   )rt  r  repeatr   r  s     r   rJ  z"NDFrame._where.<locals>.<listcomp>f'  s~     ( ( (
 %&	 !%	!!!Q$ 6 6$(IaaadO$)!a!e)$4$;$;CII$F$F!" !"( ( (r   z.cannot align with a higher dimensional NDFrameT)extract_numpyz4other must be the same shape as self when an ndarrayr  )r  newr  r  )r  r  r  )9rS   r  ro   apply_if_callabler   r   r  _constructor_expanddimr   fromkeysrs  r   r  r  r  rM  
asanyarrayrG  r  r   r
  r   r@  r/  r"  rg   r[   r  r  r   r   r   r  r  r   rp  r@  r   r  rK   r  rI  r  broadcast_tor  r   r  r8  r   r{   rw   ru   r  putmaskr  r   rL  )r   r  r  r   r   r%  r  r  r  res_colsr  r  r  ri  s   ```           r   r  zNDFrame._where&  s_    &gy99((..D 'd33dG$$ 	VyA~~$)q..22MM%DL(9(9":":DAA 3    $|::d:11!4DD4)) +}T**zTZ'' !OPPP$4$TUUT-F-F-H-HUUuUUUD ']]
{{:&&!!##Ez 	%dL11 $T** B#CJJTZJ$@$@AAAB "Y- G GE(55 G'


(E(EFFFG90 ,4,D:FF 3355 D ;;t$$D)uuT||DO$2H|II eW%% =	=zTY&&

# #    <(;(;D(A(A<++:	))!ME!%44 !6199$&Jug$>$>EE!QYY$&Jug$>$>E "tz B B  199( ( ( ( ( (
 */tz!})=)=( ( (HH "QYY( ( ( ( ( (
 */tz!})=)=( ( (H #//Yx5H5H0I0IJJ$(J	&*l" ( 00555#'K"//555G *N *D   EJ#899 	=!%t<<<Eebj.9:: 	{dj((9>>
 %N   " *) !6688 ?D   <D9vq1111EE))$//14E 	- y((dU(KKH//x}/MMF  (((K y '  H
 //x}/MMF&&t,,,r   c               6   t          |d          }|rYt          sRt          j        |           t          k    r5t          j        |           s!t          j        t          t          d           t          j        ||           }|                     |||||          S )a  
        Replace values where the condition is False.

        This method allows conditional replacement of values. Where the
        condition evaluates to True, the original values are retained; where
        it evaluates to False, values are replaced with corresponding entries
        from ``other``.

        Parameters
        ----------
        cond : bool Series/DataFrame, array-like, or callable
            Where `cond` is True, keep the original value. Where
            False, replace with corresponding value from `other`.
            If `cond` is callable, it is computed on the Series/DataFrame and
            should return boolean Series/DataFrame or array. The callable must
            not change input Series/DataFrame (though pandas doesn't check it).
        other : scalar, Series/DataFrame, or callable
            Entries where `cond` is False are replaced with
            corresponding value from `other`.
            If other is callable, it is computed on the Series/DataFrame and
            should return scalar or Series/DataFrame. The callable must not
            change input Series/DataFrame (though pandas doesn't check it).
            If not specified, entries will be filled with the corresponding
            NULL value (``np.nan`` for numpy dtypes, ``pd.NA`` for extension
            dtypes).
        inplace : bool, default False
            Whether to perform the operation in place on the data.
        axis : int, default None
            Alignment axis if needed. For `Series` this parameter is
            unused and defaults to 0.
        level : int, default None
            Alignment level if needed.

        Returns
        -------
        Series or DataFrame
            When applied to a Series, the function will return a Series,
            and when applied to a DataFrame, it will return a DataFrame.

        See Also
        --------
        :func:`DataFrame.mask` : Return an object of same shape as caller.
        :func:`Series.mask` : Return an object of same shape as caller.

        Notes
        -----
        The where method is an application of the if-then idiom. For each
        element in the caller, if ``cond`` is ``True`` the
        element is used; otherwise the corresponding element from
        ``other`` is used. If the axis of ``other`` does not align with axis of
        ``cond`` Series/DataFrame, the values of ``cond`` on misaligned index positions
        will be filled with False.

        The signature for :func:`Series.where` or
        :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 ``where`` documentation in
        :ref:`indexing <indexing.where_mask>`.

        The dtype of the object takes precedence. The fill value is casted to
        the object's dtype, if this can be done losslessly.

        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 = pd.Series(range(5))
        >>> t = pd.Series([True, False])
        >>> s.where(t, 99)
        0     0
        1    99
        2    99
        3    99
        4    99
        dtype: int64
        >>> s.mask(t, 99)
        0    99
        1     1
        2    99
        3    99
        4    99
        dtype: int64

        >>> s.where(s > 1, 10)
        0    10
        1    10
        2    2
        3    3
        4    4
        dtype: int64
        >>> s.mask(s > 1, 10)
        0     0
        1     1
        2    10
        3    10
        4    10
        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  )rS   rE   rF  rG  rF   ro   rH  r  r  rM   rJ   r  r  r   r  r  r   r   r%  s         r   rL  zNDFrame.where'  s    t &gy99 		+ ? %& &.4.Md.S.S& M6.#$    (55{{4d%{PPPr   c                  t          |d          }|rYt          sRt          j        |           t          k    r5t          j        |           s!t          j        t          t          d           t          j        ||           }t          j        ||           }t          |d          st          j        |          }|                     | ||||          S )a  
        Replace values where the condition is True.

        Parameters
        ----------
        cond : bool Series/DataFrame, array-like, or callable
            Where `cond` is False, keep the original value. Where
            True, replace with corresponding value from `other`.
            If `cond` is callable, it is computed on the Series/DataFrame and
            should return boolean Series/DataFrame or array. The callable must
            not change input Series/DataFrame (though pandas doesn't check it).
        other : scalar, Series/DataFrame, or callable
            Entries where `cond` is True are replaced with
            corresponding value from `other`.
            If other is callable, it is computed on the Series/DataFrame and
            should return scalar or Series/DataFrame. The callable must not
            change input Series/DataFrame (though pandas doesn't check it).
            If not specified, entries will be filled with the corresponding
            NULL value (``np.nan`` for numpy dtypes, ``pd.NA`` for extension
            dtypes).
        inplace : bool, default False
            Whether to perform the operation in place on the data.
        axis : int, default None
            Alignment axis if needed. For `Series` this parameter is
            unused and defaults to 0.
        level : int, default None
            Alignment level if needed.

        Returns
        -------
        Series or DataFrame
            When applied to a Series, the function will return a Series,
            and when applied to a DataFrame, it will return a DataFrame.

        See Also
        --------
        :func:`DataFrame.where` : Return an object of same shape as caller.
        :func:`Series.where` : Return an object of same shape as caller.

        Notes
        -----
        The mask method is an application of the if-then idiom. For each
        element in the caller, if ``cond`` is ``False`` the
        element is used; otherwise the corresponding element from
        ``other`` is used. If the axis of ``other`` does not align with axis of
        ``cond`` Series/DataFrame, the values of ``cond`` on misaligned index positions
        will be filled with True.

        The signature for :func:`Series.where` or
        :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 ``mask`` documentation in
        :ref:`indexing <indexing.where_mask>`.

        The dtype of the object takes precedence. The fill value is casted to
        the object's dtype, if this can be done losslessly.

        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 = pd.Series(range(5))
        >>> t = pd.Series([True, False])
        >>> s.where(t, 99)
        0     0
        1    99
        2    99
        3    99
        4    99
        dtype: int64
        >>> s.mask(t, 99)
        0    99
        1     1
        2    99
        3    99
        4    99
        dtype: int64

        >>> s.where(s > 1, 10)
        0    10
        1    10
        2    2
        3    3
        4    4
        dtype: int64
        >>> s.mask(s > 1, 10)
        0     0
        1     1
        2    10
        3    10
        4    10
        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  r   r   r%  )rS   rE   rF  rG  rF   ro   rH  r  r  rM   rJ   r  r  rM  r)  r  r  s         r   r  zNDFrame.maskS(  s    j &gy99 		+ ? %& &.4.Md.S.S& M6.#$    'd33(55 t\** 	"8D>>D{{E  
 
 	
r   periodsint | Sequence[int]Self | DataFramec                p   |                      |          }||t          j        urt          d          |dk    r|                     d          S t          |          r@t          | t                    r+|                                 	                    ||||          S t          t          |          }|j|                      |          }|dk    sJ | j        	                    ||          }|                     ||j                                      | d	
          S |                     |||          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 or Sequence
            Number of periods to shift. Can be positive or negative.
            If an iterable of ints, the data will be shifted once by each int.
            This is equivalent to shifting by one value at a time and
            concatenating all resulting frames. The resulting columns will have
            the shift suffixed to their column names. For multiple periods,
            axis must not be 1.
        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. For `Series` this parameter is unused and defaults to 0.
        fill_value : object, optional
            The scalar value to use for newly introduced missing values.
            the default depends on the dtype of `self`.
            For Boolean and numeric NumPy data types, ``np.nan`` is used.
            For datetime, timedelta, or period data, etc. :attr:`NaT` is used.
            For extension dtypes, ``self.dtype.na_value`` is used.
        suffix : str, optional
            If str and periods is an iterable, this is added after the column
            name and before the shift value for each shifted column name.
            For `Series` this parameter is unused and defaults to `None`.

        Returns
        -------
        Series/DataFrame
            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.

        Examples
        --------
        >>> df = pd.DataFrame(
        ...     [[10, 13, 17], [20, 23, 27], [15, 18, 22], [30, 33, 37], [45, 48, 52]],
        ...     columns=["Col1", "Col2", "Col3"],
        ...     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    13
        2020-01-02   NaN    20    23
        2020-01-03   NaN    15    18
        2020-01-04   NaN    30    33
        2020-01-05   NaN    45    48

        >>> 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

        >>> df["Col1"].shift(periods=[0, 1, 2])
                    Col1_0  Col1_1  Col1_2
        2020-01-01      10     NaN     NaN
        2020-01-02      20    10.0     NaN
        2020-01-03      15    20.0    10.0
        2020-01-04      30    15.0    20.0
        2020-01-05      45    30.0    15.0
        Nz=Passing a 'freq' together with a 'fill_value' is not allowed.r   Fr   )r  rs  r   r  )r  r  r  shiftrq  )r  r   r  r  r   r^   r   rh   rx  r  r   r   r   r  r   r8  _shift_with_freq)r   r  rs  r   r  r  r  s          r   r  zNDFrame.shift)  sI   t $$T**
#. @ @O   a<<99%9(((   	Zi%@%@ 	==??((d* )    sG$$<((..D19999yw:NNH--x} .  l4l001 $$WdD999r   c                   |                      |          }|dk    r8t          |dd           }|t          |dd           }|d}t          |          n;t          |t                    r&t          |t
                    }t          ||          }t          |t
                    rmt          |j                  }||k    r=|J t          dt          |          j	         dt          |          j	                   |
                    |          }n|
                    ||          }|                     ||          }	|	                    | d	
          S )Nr  rs  inferred_freqz6Freq was not set in the index hence cannot be inferred)	is_periodzGiven freq z! does not match PeriodIndex freq r   r  rq  )r  r  r  r   r   r|   r   rs  rf   _freqstrr  rT  r8  )
r   r  r   rs  r   r  r  	orig_freqrO  ri  s
             r   r  zNDFrame._shift_with_freq)  si    t$$7??5&$//D|uot<<|N oo%  c"" 	8"5+66ITY777De[)) 	0!%*--Iy   ,,, 9+d"3"3"< 9 9"9--69 9  
 "KK00FF[[$//FvD11""4"888r   c                   |                      |           |d}|                     |          }|                     |          }|j        s|j        st          d          |j        r ddlm} | ||          }| ||          }||||k    rt          d| d|           t          |          dk    r#|j        r|
                                dk    r||}}t          dd          g| j        z  }t          ||          ||<   | j        t          |                   }t          |t                     r8t#          ||                     |          |                    ||                     |                    d	          }|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.
            For `Series` this parameter is unused and defaults to 0.
        copy : bool, default False
            This keyword is now ignored; changing its value will have no
            impact on the method.

            .. deprecated:: 3.0.0

                This keyword is ignored and will be removed in pandas 4.0. Since
                pandas 3.0, this method always returns a new object using a lazy
                copy mechanism that defers copies until necessary
                (Copy-on-Write). See the `user guide on Copy-on-Write
                <https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html>`__
                for more details.

        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: str

        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
        Nr   z truncate requires a sorted index)to_datetimez
Truncate: z must be after r   Fr   )r   r  r  rv  is_monotonic_decreasingr  _is_all_datespandas.core.tools.datetimesr"  r   r	  ro  r   rN  rF  r   r{   r_  r  truncater   )	r   beforeafterr   r   r  r"  slicerri  s	            r   r&  zNDFrame.truncate)  s   Z 	$$T***<D$$T**^^D!! ) 	A"2L 	A?@@@  	+??????!$V,, #E**%"3H%HHHHIIIr77Q;;25;"**,,:J:J!6EFd##$t~5VU++t%--(b*%% 	SFD//55r{{657Q7QRRR%((r   c                                           |                                                                         } fd}t          |t                    rD|                    |          } ||j        |         |          }|                    ||          }n+|dd|j        fvrt          d| d           |||          } 
                    d          }|                    |	          }|                     d
          S )a  
        Convert tz-aware axis to target time zone.

        Parameters
        ----------
        tz : str or tzinfo object or None
            Target time zone. Passing ``None`` will convert to
            UTC and remove the timezone information.
        axis : {{0 or 'index', 1 or 'columns'}}, default 0
            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 False
            This keyword is now ignored; changing its value will have no
            impact on the method.

            .. deprecated:: 3.0.0

                This keyword is ignored and will be removed in pandas 4.0. Since
                pandas 3.0, this method always returns a new object using a lazy
                copy mechanism that defers copies until necessary
                (Copy-on-Write). See the `user guide on Copy-on-Write
                <https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html>`__
                for more details.

        Returns
        -------
        Series/DataFrame
            Object with time zone converted axis.

        Raises
        ------
        TypeError
            If the axis is tz-naive.

        See Also
        --------
        DataFrame.tz_localize: Localize tz-naive index of DataFrame to target time zone.
        Series.tz_localize: Localize tz-naive index of Series to target time zone.

        Examples
        --------
        Change to another time zone:

        >>> s = pd.Series(
        ...     [1],
        ...     index=pd.DatetimeIndex(["2018-09-15 01:30:00+02:00"]),
        ... )
        >>> s.tz_convert("Asia/Shanghai")
        2018-09-15 07:30:00+08:00    1
        dtype: int64

        Pass None to convert to UTC and get a tz-naive index:

        >>> s = pd.Series([1], index=pd.DatetimeIndex(["2018-09-15 01:30:00+02:00"]))
        >>> s.tz_convert(None)
        2018-09-14 23:30:00    1
        dtype: int64
        c                    t          | d          sLt          |           dk    r'                              }t          | d          t	          g |          } n|                     |          } | S )N
tz_convertr   , is not a valid DatetimeIndex or PeriodIndexr  )r  r   r  r  ry   r,  )r  r  ax_namer   r   s      r   _tz_convertz'NDFrame.tz_convert.<locals>._tz_convert*  s    2|,, 'r77Q;;"11$77G#"PPP   #2"---]]2&&Ir   r  Nr   
The level  is not validFr   r   r,  rq  )r   r  r  r   r{   r  levels
set_levelsr#  r  r   rT  r8  )	r   r  r   r%  r   r  r0  	new_levelri  s	   ` `      r   r,  zNDFrame.tz_converts*  s3   H 	$$T***$$T**^^D!!
	 
	 
	 
	 
	 
	 b*%% 	%((//E#BIe$4b99Iy66BBT1bg... !Be!B!B!BCCCR$$B&&$//""4"===r   	ambiguousr<   nonexistentr>   c                                          |           d}||vr)t          |t          j                  st	          d                                                                        } fd}	t          |t                    rF|                    |          } |	|j	        |         |||          }
|
                    |
|          }n-|dd|j        fvrt	          d| d           |	||||          }                     d	
          }|                    |          }|                     d          S )a  
        Localize time zone naive index of a Series or DataFrame to target time zone.

        This operation localizes the Index. To localize the values in a
        time zone naive Series, use :meth:`Series.dt.tz_localize`.

        Parameters
        ----------
        tz : str or tzinfo or None
            Time zone to localize. Passing ``None`` will remove the
            time zone information and preserve local time.
        axis : {{0 or 'index', 1 or 'columns'}}, default 0
            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 False
            This keyword is now ignored; changing its value will have no
            impact on the method.

            .. deprecated:: 3.0.0

                This keyword is ignored and will be removed in pandas 4.0. Since
                pandas 3.0, this method always returns a new object using a lazy
                copy mechanism that defers copies until necessary
                (Copy-on-Write). See the `user guide on Copy-on-Write
                <https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html>`__
                for more details.

        ambiguous : 'infer', bool, 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 (or 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 a ValueError 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 a ValueError if there are
              nonexistent times.

        Returns
        -------
        Series/DataFrame
            Same type as the input, with time zone naive or aware index, depending on
            ``tz``.

        Raises
        ------
        TypeError
            If the TimeSeries is tz-aware and tz is not None.

        See Also
        --------
        Series.dt.tz_localize: Localize the values in a time zone naive Series.
        Timestamp.tz_localize: Localize the Timestamp to a timezone.

        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

        Pass None to convert to tz-naive index and preserve local time:

        >>> s = pd.Series([1], index=pd.DatetimeIndex(["2018-09-15 01:30:00+02:00"]))
        >>> s.tz_localize(None)
        2018-09-15 01:30: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'`.

        >>> dti = pd.DatetimeIndex(
        ...     ["2015-03-29 02:30:00", "2015-03-29 03:30:00"], dtype="M8[ns]"
        ... )
        >>> s = pd.Series(range(2), index=dti)
        >>> 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 objectc                    t          | d          sLt          |           dk    r'                              }t          | d          t	          g |          } n|                     |||          } | S )Ntz_localizer   r-  r.  )r6  r7  )r  r   r  r  ry   r=  )r  r  r6  r7  r/  r   r   s        r   _tz_localizez)NDFrame.tz_localize.<locals>._tz_localize+  s    2}-- Vr77Q;;"11$77G#"PPP   #2"---^^B)^UUIr   r  Nr   r1  r2  Fr   r   r=  rq  )r   r   dt	timedeltar  r  r  r{   r  r3  r4  r#  r   rT  r8  )r   r  r   r%  r   r6  r7  nonexistent_optionsr  r>  r5  ri  s   ` `         r   r=  zNDFrame.tz_localize*  s~   T 	$$T***Q111*;
 ;
1 %   $$T**^^D!!
	 
	 
	 
	 
	 
	 b*%% 	>((//E$RYu%5r9kRRIy66BBT1bg... !Be!B!B!BCCCb"i==B&&$//""4">>>r   c                R    t          | |||                              | d          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, ``None``, will automatically
            return 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(exclude=['O'])``). To
              exclude pandas categorical columns, use ``'category'``
            - None (default) : The result will exclude nothing.

        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), 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.

        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()
        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              d
        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   r  excludepercentilesdescriberq  )r   r8  )r   rD  r  rC  s       r   rE  zNDFrame.describe+  s;    l  #	
 
 

 ,tJ,
/
/	0r   fill_methodc                V   |t          d|d          |                     |                    dd                    } | j        d
|||d|}| |z  dz
  }|:|j        |j                                                  }|                    |           }|                    | d	          S )a$  
        Fractional change between the current and a prior element.

        Computes the fractional change from the immediately previous row by
        default. This is useful in comparing the fraction of change in a time
        series of elements.

        .. note::

            Despite the name of this method, it calculates fractional change
            (also known as per unit change or relative change) and not
            percentage change. If you need the percentage change, multiply
            these values by 100.

        Parameters
        ----------
        periods : int, default 1
            Periods to shift for forming percent change.
        fill_method : None
            Must be None. This argument will be removed in a future version of pandas.
        freq : DateOffset, timedelta, or str, optional
            Increment to use from time series API (e.g. 'ME' or BDay()).
        **kwargs
            Additional keyword arguments are passed into
            `DataFrame.shift` or `Series.shift`.

        Returns
        -------
        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.ffill().pct_change()
        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", periods=-1)
                  2016      2015  2014
        GOOG  0.179241  0.094112   NaN
        APPL -0.252395 -0.011860   NaN
        Nz*fill_method must be None; got fill_method=r  r   r   )r  rs  r   r   
pct_changerq  r  )	r  r  rj  r  rN  r   
duplicatedrq  r8  )r   r  rF  rs  r   r   shiftedr  s           r   rH  zNDFrame.pct_change,  s    L "MkMMMNNN$$VZZ%@%@AA$*MW4dMMfMMG^a ,,.../B&&BtL999r   	bool_onlyskipnaSeries | boolc                   t          j        d||           t          |dd           | j        dk    r&|$ | j        ||fd||d|} |j        ||fd|i|S |d}| j        dk    rx|dk    rrt          | j        j                  dk    rUt          d	 | j        j        D                       r2|s0| }|r| 	                                }|
                    |||
          S |                     |||||d          S )Nr  fnamerL  Fnone_allowedr   r   r   rK  rL  c              3  6   K   | ]}|j         j        d k    V  dS )r  N)r   r  )r  r  s     r   rE  z(NDFrame._logical_func.<locals>.<genexpr>[-  s,      IIuEL%*IIIIIIr   rL  r   )r#  r   rL  r  filter_type)r?  validate_logical_funcrS   r  _logical_funcr   r   r   r  r  _reduce_axis1_reduce)	r   r#  r  r   rK  rL  r   r  r   s	            r   rX  zNDFrame._logical_func=-  su    	 V48888FH5AAAA9q==T\$$$d!"i JP C %3$d #)-3   \D IMM		DI$%%))II	8HIIIII *  * C ,))++$$T4$???||"  
 
 	
r   rS  c               :     | j         dt          j        |||fi |S )Nr  )rX  rr   nananyr   r   rK  rL  r   s        r   r  zNDFrame.anym-  5     "t!6=$	6
 
=C
 
 	
r   c               :     | j         dt          j        |||fi |S )Nr  )rX  rr   nanallr]  s        r   r  zNDFrame.ally-  r^  r   c                \   t          j        |          |d}n|                     |          }|dk    r | j        j        g|R ddj        S fd}| j                            |          }|                     ||j                  	                    |           S )Nr   r   )r   rL  c                    t          | d          r| j        n| }t          |t                    r |j        fdi}nt          j        |          }t          |d          r|j        n|}|S )Nr;   rL  rU  )r  r;   r   ru   _accumulaterr   na_accum_func)
blk_valuesr   ri  r  r   r#  rL  s      r   block_accum_funcz-NDFrame._accum_func.<locals>.block_accum_func-  s    %,Z%=%=MZ\\:F &.11 K++DJJJ6JJ-fd6JJJ!(!5!5AVXX6FMr   r  rq  )
r?  validate_cum_func_with_skipnar  r;   _accum_funcr   r  r  r   r8  )	r   r#  r  r   rL  r  r   rf  ri  s	    `` ` `  r   rh  zNDFrame._accum_func-  s    1&$MM<DD((..D199%46%
   	    
	 
	 
	 
	 
	 
	 
	 
	 !122))&v{)CCPP Q 
 
 	
r   c                H     | j         dt          j        j        ||g|R i |S )Ncummax)rh  rM  maximum
accumulater   r   rL  r  r   s        r   rj  zNDFrame.cummax-  A    tbj+T6
<@
 
 
DJ
 
 	
r   c                H     | j         dt          j        j        ||g|R i |S )Ncummin)rh  rM  minimumrl  rm  s        r   rp  zNDFrame.cummin-  rn  r   c                >     | j         dt          j        ||g|R i |S )Ncumsum)rh  rM  rs  rm  s        r   rs  zNDFrame.cumsum-  s-    t")T6SDSSSFSSSr   c                >     | j         dt          j        ||g|R i |S )Ncumprod)rh  rM  ru  rm  s        r   ru  zNDFrame.cumprod-  s-    t	2:tVUdUUUfUUUr   ddofSeries | floatc                    t          j        d||           t          |dd           |                     ||||||          S )Nr  rO  rL  FrQ  )r   r  rL  rv  )r?  validate_stat_ddof_funcrS   rZ  )r   r#  r  r   rL  rv  r  r   s           r   _stat_function_ddofzNDFrame._stat_function_ddof-  sZ     	"2vT::::FH5AAAA||$TVRV  
 
 	
r   )r   rL  rv  r  c               <     | j         dt          j        ||||fi |S )Nsem)rz  rr   nansemr   r   rL  rv  r  r   s         r   r|  zNDFrame.sem-  7     (t'6=$l
 
FL
 
 	
r   c               <     | j         dt          j        ||||fi |S )Nvar)rz  rr   nanvarr~  s         r   r  zNDFrame.var-  r  r   c               <     | j         dt          j        ||||fi |S )Nstd)rz  rr   nanstdr~  s         r   r  zNDFrame.std-  r  r   c                    |dv s
J |            t          j        |d|           t          |dd           |                     |||||          S )N)medianmeanr  r  kurtskewr  rL  FrQ  )r#  r   rL  r  r?  validate_funcrS   rZ  )r   r#  r  r   rL  r  r   s          r   _stat_functionzNDFrame._stat_function-  sn     GGGGGGG
r6***FH5AAAA||t$vL  
 
 	
r   )r   rL  r  c               :     | j         dt          j        |||fi |S )Nr  )r  rr   nanminr   r   rL  r  r   s        r   r  zNDFrame.min.  ;     #t"M
 
 
 
 	
r   c               :     | j         dt          j        |||fi |S )Nr  )r  rr   nanmaxr  s        r   r  zNDFrame.max.  r  r   c               :     | j         dt          j        |||fi |S )Nr  )r  rr   nanmeanr  s        r   r  zNDFrame.mean/.  5     #t"FND&,
 
BH
 
 	
r   c               :     | j         dt          j        |||fi |S )Nr  )r  rr   	nanmedianr  s        r   r  zNDFrame.median;.  s6     #t"f&fl
 
FL
 
 	
r   c               :     | j         dt          j        |||fi |S )Nr  )r  rr   nanskewr  s        r   r  zNDFrame.skewG.  r  r   c               :     | j         dt          j        |||fi |S )Nr  )r  rr   nankurtr  s        r   r  zNDFrame.kurtS.  r  r   	min_countc                    |dv s
J |            t          j        |d|           t          |dd           |                     ||||||          S )N)sumrN  r  rL  FrQ  )r#  r   rL  r  r  r  )r   r#  r  r   rL  r  r  r   s           r   _min_count_stat_functionz NDFrame._min_count_stat_functiona.  st     &&&&&&
r6***FH5AAAA||%  
 
 	
r   )r   rL  r  r  c               <     | j         dt          j        ||||fi |S )Nr  )r  rr   nansumr   r   rL  r  r  r   s         r   r  zNDFrame.sumz.  s7     -t,6=$i
 
KQ
 
 	
r   c               <     | j         dt          j        ||||fi |S )NrN  )r  rr   nanprodr  s         r   rN  zNDFrame.prod.  s>     -t,N
 
 
 
 	
r   singlewindow3int | dt.timedelta | str | BaseOffset | BaseIndexermin_periodscenterwin_typeIntervalClosedType | NonestepWindow | Rollingc	                f    |t          | ||||||||	  	        S t          | ||||||||	  	        S )a  
        Provide rolling window calculations.

        Parameters
        ----------
        window : int, timedelta, str, offset, or BaseIndexer subclass
            Interval of the moving window.

            If an integer, the delta between the start and end of each window.
            The number of points in the window depends on the ``closed`` argument.

            If a timedelta, str, or offset, the time period of each window. Each
            window will be a variable sized based on the observations included in
            the time-period. This is only valid for datetimelike indexes.
            To learn more about the offsets & frequency strings, please see
            :ref:`this link<timeseries.offset_aliases>`.

            If a BaseIndexer subclass, the window boundaries
            based on the defined ``get_window_bounds`` method. Additional rolling
            keyword arguments, namely ``min_periods``, ``center``, ``closed`` and
            ``step`` will be passed to ``get_window_bounds``.

        min_periods : int, default None
            Minimum number of observations in window required to have a value;
            otherwise, result is ``np.nan``.

            For a window that is specified by an offset, ``min_periods`` will default
            to 1.

            For a window that is specified by an integer, ``min_periods`` will default
            to the size of the window.

        center : bool, default False
            If False, set the window labels as the right edge of the window index.

            If True, set the window labels as the center of the window index.

        win_type : str, default None
            If ``None``, all points are evenly weighted.

            If a string, it must be a valid `scipy.signal window function
            <https://docs.scipy.org/doc/scipy/reference/signal.windows.html#module-scipy.signal.windows>`__.

            Certain Scipy window types require additional parameters to be passed
            in the aggregation function. The additional parameters must match
            the keywords specified in the Scipy window type method signature.

        on : str, optional
            For a DataFrame, a column label or Index level on which
            to calculate the rolling window, rather than the DataFrame's index.

            Provided integer column is ignored and excluded from result since
            an integer index is not used to calculate the rolling window.

        closed : str, default None
            Determines the inclusivity of points in the window

            If ``'right'``, uses the window (first, last] meaning the last point
            is included in the calculations.

            If ``'left'``, uses the window [first, last) meaning the first point
            is included in the calculations.

            If ``'both'``, uses the window [first, last] meaning all points in
            the window are included in the calculations.

            If ``'neither'``, uses the window (first, last) meaning the first
            and last points in the window are excluded from calculations.

            () and [] are referencing open and closed set
            notation respetively.

            Default ``None`` (``'right'``).

        step : int, default None
            Evaluate the window at every ``step`` result, equivalent to slicing as
            ``[::step]``. ``window`` must be an integer. Using a step argument other
            than None or 1 will produce a result with a different shape than the input.

        method : str {'single', 'table'}, default 'single'

            Execute the rolling operation per single column or row (``'single'``)
            or over the entire object (``'table'``).

            This argument is only implemented when specifying ``engine='numba'``
            in the method call.

        Returns
        -------
        pandas.api.typing.Window or pandas.api.typing.Rolling
            An instance of Window is returned if ``win_type`` is passed. Otherwise,
            an instance of Rolling is returned.

        See Also
        --------
        expanding : Provides expanding transformations.
        ewm : Provides exponential weighted functions.

        Notes
        -----
        See :ref:`Windowing Operations <window.generic>` for further usage details
        and examples.

        Examples
        --------
        >>> df = pd.DataFrame({"B": [0, 1, 2, np.nan, 4]})
        >>> df
             B
        0  0.0
        1  1.0
        2  2.0
        3  NaN
        4  4.0

        **window**

        Rolling sum with a window length of 2 observations.

        >>> df.rolling(2).sum()
             B
        0  NaN
        1  1.0
        2  3.0
        3  NaN
        4  NaN

        Rolling sum with a window span of 2 seconds.

        >>> df_time = pd.DataFrame(
        ...     {"B": [0, 1, 2, np.nan, 4]},
        ...     index=[
        ...         pd.Timestamp("20130101 09:00:00"),
        ...         pd.Timestamp("20130101 09:00:02"),
        ...         pd.Timestamp("20130101 09:00:03"),
        ...         pd.Timestamp("20130101 09:00:05"),
        ...         pd.Timestamp("20130101 09:00:06"),
        ...     ],
        ... )

        >>> df_time
                               B
        2013-01-01 09:00:00  0.0
        2013-01-01 09:00:02  1.0
        2013-01-01 09:00:03  2.0
        2013-01-01 09:00:05  NaN
        2013-01-01 09:00:06  4.0

        >>> df_time.rolling("2s").sum()
                               B
        2013-01-01 09:00:00  0.0
        2013-01-01 09:00:02  1.0
        2013-01-01 09:00:03  3.0
        2013-01-01 09:00:05  NaN
        2013-01-01 09:00:06  4.0

        Rolling sum with forward looking windows with 2 observations.

        >>> indexer = pd.api.indexers.FixedForwardWindowIndexer(window_size=2)
        >>> df.rolling(window=indexer, min_periods=1).sum()
             B
        0  1.0
        1  3.0
        2  2.0
        3  4.0
        4  4.0

        **min_periods**

        Rolling sum with a window length of 2 observations, but only needs a minimum
        of 1 observation to calculate a value.

        >>> df.rolling(2, min_periods=1).sum()
             B
        0  0.0
        1  1.0
        2  3.0
        3  2.0
        4  4.0

        **center**

        Rolling sum with the result assigned to the center of the window index.

        >>> df.rolling(3, min_periods=1, center=True).sum()
             B
        0  1.0
        1  3.0
        2  3.0
        3  6.0
        4  4.0

        >>> df.rolling(3, min_periods=1, center=False).sum()
             B
        0  0.0
        1  1.0
        2  3.0
        3  3.0
        4  6.0

        **step**

        Rolling sum with a window length of 2 observations, minimum of 1 observation to
        calculate a value, and a step of 2.

        >>> df.rolling(2, min_periods=1, step=2).sum()
             B
        0  0.0
        2  3.0
        4  4.0

        **win_type**

        Rolling sum with a window length of 2, using the Scipy ``'gaussian'``
        window type. ``std`` is required in the aggregation function.

        >>> df.rolling(2, win_type="gaussian").sum(std=3)
                  B
        0        NaN
        1   0.986207
        2   2.958621
        3        NaN
        4        NaN

        **on**

        Rolling sum with a window length of 2 days.

        >>> df = pd.DataFrame(
        ...     {
        ...         "A": [
        ...             pd.to_datetime("2020-01-01"),
        ...             pd.to_datetime("2020-01-01"),
        ...             pd.to_datetime("2020-01-02"),
        ...         ],
        ...         "B": [1, 2, 3],
        ...     },
        ...     index=pd.date_range("2020", periods=3),
        ... )

        >>> df
                            A  B
        2020-01-01 2020-01-01  1
        2020-01-02 2020-01-01  2
        2020-01-03 2020-01-02  3

        >>> df.rolling("2D", on="A").sum()
                            A    B
        2020-01-01 2020-01-01  1.0
        2020-01-02 2020-01-01  3.0
        2020-01-03 2020-01-02  6.0
        N)r  r  r  r  r  r  r  rr  )r   r   )	r   r  r  r  r  r  r  r  rr  s	            r   rollingzNDFrame.rolling.  sq    N '!
 
 
 
 #

 

 

 
	
r   Literal['single', 'table']r   c                &    t          | ||          S )a  
        Provide expanding window calculations.

        An expanding window yields the value of an aggregation statistic with all
        the data available up to that point in time.

        Parameters
        ----------
        min_periods : int, default 1
            Minimum number of observations in window required to have a value;
            otherwise, result is ``np.nan``.

        method : str {'single', 'table'}, default 'single'
            Execute the rolling operation per single column or row (``'single'``)
            or over the entire object (``'table'``).

            This argument is only implemented when specifying ``engine='numba'``
            in the method call.

        Returns
        -------
        pandas.api.typing.Expanding
            An instance of Expanding for further expanding window calculations,
            e.g. using the ``sum`` method.

        See Also
        --------
        rolling : Provides rolling window calculations.
        ewm : Provides exponential weighted functions.

        Notes
        -----
        See :ref:`Windowing Operations <window.expanding>` for further usage details
        and examples.

        Examples
        --------
        >>> df = pd.DataFrame({"B": [0, 1, 2, np.nan, 4]})
        >>> df
             B
        0  0.0
        1  1.0
        2  2.0
        3  NaN
        4  4.0

        **min_periods**

        Expanding sum with 1 vs 3 observations needed to calculate a value.

        >>> df.expanding(1).sum()
             B
        0  0.0
        1  1.0
        2  3.0
        3  3.0
        4  7.0
        >>> df.expanding(3).sum()
             B
        0  NaN
        1  NaN
        2  3.0
        3  3.0
        4  7.0
        )r  rr  )r   )r   r  rr  s      r   	expandingzNDFrame.expanding/  s    N ;vFFFFr   comspanhalflife(float | TimedeltaConvertibleTypes | Nonealphaadjust	ignore_natimes&np.ndarray | DataFrame | Series | Noner   c
                4    t          | |||||||||	
  
        S )N)	r  r  r  r  r  r  r  r  rr  )r   )
r   r  r  r  r  r  r  r  r  rr  s
             r   ewmzNDFrame.ewm0  s9     '#
 
 
 	
r   c                n     || |          }|                      |                    |                      | S )z<
        Wrap arithmetic method to operate inplace.
        )r  rq  )r   r  opri  s       r   _inplace_methodzNDFrame._inplace_method#0  s<    
 D% 	V0066777r   c                R    |                      |t          |           j                  S r   )r  r  __add__r  s     r   __iadd__zNDFrame.__iadd__/0  #     ##E4::+=>>>r   c                R    |                      |t          |           j                  S r   )r  r  __sub__r  s     r   __isub__zNDFrame.__isub__40  r  r   c                R    |                      |t          |           j                  S r   )r  r  __mul__r  s     r   __imul__zNDFrame.__imul__90  r  r   c                R    |                      |t          |           j                  S r   )r  r  __truediv__r  s     r   __itruediv__zNDFrame.__itruediv__>0  s+     ##JJ"
 
 	
r   c                R    |                      |t          |           j                  S r   )r  r  __floordiv__r  s     r   __ifloordiv__zNDFrame.__ifloordiv__F0  s+     ##JJ#
 
 	
r   c                R    |                      |t          |           j                  S r   )r  r  __mod__r  s     r   __imod__zNDFrame.__imod__N0  r  r   c                R    |                      |t          |           j                  S r   )r  r  __pow__r  s     r   __ipow__zNDFrame.__ipow__S0  r  r   c                R    |                      |t          |           j                  S r   )r  r  __and__r  s     r   __iand__zNDFrame.__iand__X0  r  r   c                R    |                      |t          |           j                  S r   )r  r  __or__r  s     r   __ior__zNDFrame.__ior__]0  s!    ##E4::+<===r   c                R    |                      |t          |           j                  S r   )r  r  __xor__r  s     r   __ixor__zNDFrame.__ixor__a0  r  r   c               x    |                                  j        }t          ||          }|dS | 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
        )r  is_validN)rl   r   r   r   )r   r  r  idxposs       r   _find_valid_indexzNDFrame._find_valid_indexi0  s=     ::<<&!cH===>4z&!!r   c                .    |                      d          S )aK  
        Return index for first non-missing value or None, if no value is found.

        See the :ref:`User Guide <missing_data>` for more information
        on which values are considered missing.

        Returns
        -------
        type of index
            Index of first non-missing value.

        See Also
        --------
        DataFrame.last_valid_index : Return index for last non-NA value or None, if
            no non-NA value is found.
        Series.last_valid_index : Return index for last non-NA value or None, if no
            non-NA value is found.
        DataFrame.isna : Detect missing values.

        Examples
        --------
        For Series:

        >>> s = pd.Series([None, 3, 4])
        >>> s.first_valid_index()
        1
        >>> s.last_valid_index()
        2

        >>> s = pd.Series([None, None])
        >>> print(s.first_valid_index())
        None
        >>> print(s.last_valid_index())
        None

        If all elements in Series are NA/null, returns None.

        >>> s = pd.Series()
        >>> print(s.first_valid_index())
        None
        >>> print(s.last_valid_index())
        None

        If Series is empty, returns None.

        For DataFrame:

        >>> df = pd.DataFrame({"A": [None, None, 2], "B": [None, 3, 4]})
        >>> df
             A      B
        0  NaN    NaN
        1  NaN    3.0
        2  2.0    4.0
        >>> df.first_valid_index()
        1
        >>> df.last_valid_index()
        2

        >>> df = pd.DataFrame({"A": [None, None, None], "B": [None, None, None]})
        >>> df
             A      B
        0  None   None
        1  None   None
        2  None   None
        >>> print(df.first_valid_index())
        None
        >>> print(df.last_valid_index())
        None

        If all elements in DataFrame are NA/null, returns None.

        >>> df = pd.DataFrame()
        >>> df
        Empty DataFrame
        Columns: []
        Index: []
        >>> print(df.first_valid_index())
        None
        >>> print(df.last_valid_index())
        None

        If DataFrame is empty, returns None.
        firstr  r  r   s    r   first_valid_indexzNDFrame.first_valid_index}0  s    j %%'%222r   c                .    |                      d          S )aM  
        Return index for last non-missing value or None, if no value is found.

        See the :ref:`User Guide <missing_data>` for more information
        on which values are considered missing.

        Returns
        -------
        type of index
            Index of last non-missing value.

        See Also
        --------
        DataFrame.first_valid_index : Return index for first non-NA value or None, if
            no non-NA value is found.
        Series.first_valid_index : Return index for first non-NA value or None, if no
            non-NA value is found.
        DataFrame.isna : Detect missing values.

        Examples
        --------
        For Series:

        >>> s = pd.Series([None, 3, 4])
        >>> s.first_valid_index()
        1
        >>> s.last_valid_index()
        2

        >>> s = pd.Series([None, None])
        >>> print(s.first_valid_index())
        None
        >>> print(s.last_valid_index())
        None

        If all elements in Series are NA/null, returns None.

        >>> s = pd.Series()
        >>> print(s.first_valid_index())
        None
        >>> print(s.last_valid_index())
        None

        If Series is empty, returns None.

        For DataFrame:

        >>> df = pd.DataFrame({"A": [None, None, 2], "B": [None, 3, 4]})
        >>> df
             A      B
        0  NaN    NaN
        1  NaN    3.0
        2  2.0    4.0
        >>> df.first_valid_index()
        1
        >>> df.last_valid_index()
        2

        >>> df = pd.DataFrame({"A": [None, None, None], "B": [None, None, None]})
        >>> df
             A      B
        0  None   None
        1  None   None
        2  None   None
        >>> print(df.first_valid_index())
        None
        >>> print(df.last_valid_index())
        None

        If all elements in DataFrame are NA/null, returns None.

        >>> df = pd.DataFrame()
        >>> df
        Empty DataFrame
        Columns: []
        Index: []
        >>> print(df.first_valid_index())
        None
        >>> print(df.last_valid_index())
        None

        If DataFrame is empty, returns None.
        r  r  r  r   s    r   last_valid_indexzNDFrame.last_valid_index0  s    j %%&%111r   )r   r/   r   r   )NF)
r   r/   r   r   r   r   r   r   r   r/   )r   r/   r   r   r   r   )r   r   )r   r   r   r   )r   rx   )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   r   r   rz   )r   r   r   r  )r   r*  )r   r4  )r   rz   )r   rA  )r   r   )r   r   )r   r   r   r   r   r   )r   r   r   rU  r   r   )r   r   r   rY  r   r   )r   r   r   r   r   r[  )r   r   rS  r`  r   r   )r   )r%  r)   r   r   r   r   )rf  r   r   rg  )r   rk  r   rl  ).)rv  rw  r   rw  r  rw  r   rk  r   rU  r%  rx  ru  r   r   r   )rv  rw  r   rw  r  rw  r   rk  r   rY  r%  rx  ru  r   r   r   )rv  rw  r   rw  r  rw  r   rk  r   r   r%  rx  ru  r   r   r[  )
rv  r  r   r   r   r   r   rU  r   r   )
rv  r  r   r   r   r   r   rY  r   r   )
rv  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   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   r$  r   r   r   r%  )r.  r/  rr  r   r0  r	   r   r	   )r   r4  )r   r   )r   r   )$rk  rl  r]  r   r^  r   r_  rm  r  rn  r`  ro  r   r   ra  rp  rb  r   rc  r   rd  rq  re  r   rf  r   rg  rr  rh  rs  ri  rt  rj  r   r   r   )r  r  rS  r  r  rm  r  r   r  r   r  r@   r  r  r  r   r  r   r   r   r  r  rh  rs  r  r  r   rm  )r  r  r$  r   r  r  r  r  r  r  r  r   r  r  r   r   r  r  r  r   r  r  ru  r2   r  r   r   r   )r#  r   r  rm  r  r  r   r   ra  rp  r  r  r   r  rr  r  r   r  )
r  r  r  r   r  r   rh  rs  r   r   )r  r   r  rm  r   r   ),r  r   r  rn  r`  r  r   r   r^  r   r  r  r_  r  r  r   r  r   r  r   r  rm  r  r   r  r   r  rm  r  r   r  r   r  rm  r  r   r  r  r  rm  r  rm  r   r   ),r  r  r  rn  r`  r  r   r   r^  r   r  r  r_  r  r  r   r  r   r  r   r  rm  r  r   r  r   r  rm  r  r   r  r   r  rm  r  r   r  r  r  rm  r  rm  r   r   ),r  r  r  rn  r`  r  r   r   r^  r   r  r  r_  r  r  r   r  r   r  r   r  rm  r  r   r  r   r  rm  r  r   r  r   r  rm  r  r   r  r  r  rm  r  rm  r   rm  )r	  r  r
  r  r  r  r  r  r  r  r  r   ),r  r   r  r   r^  r   r_  r1  r  rn  r`  r2  r   r   ra  rp  r  r   r  rm  r  r   r,  r  r-  r   r.  rm  r  r  r  rm  r/  r   r0  rm  r  r   ru  r2   rh  r9   r   r   ),r  r6  r  r   r^  r   r_  r1  r  rn  r`  r2  r   r   ra  rp  r  r   r  rm  r  r   r,  r  r-  r   r.  rm  r  r  r  rm  r/  r   r0  rm  r  r   ru  r2   rh  r9   r   r   ),r  r  r  r   r^  r   r_  r1  r  rn  r`  r2  r   r   ra  rp  r  r   r  rm  r  r   r,  r  r-  r   r.  rm  r  r  r  rm  r/  r   r0  rm  r  r   ru  r2   rh  rs  r   rm  )r   r   r   r   )r   NT)
r$  r)   r   r   r%  rp  rC  r   r   r   )r$  ro  r   r   )r[  ro  r   r   r   r   )r   r   r   r   )rr  rl  r   r   rm  r  r   r   )rS  rr  r   r   r   rr  r  rr  r%  rx  r   rY  ru  r'   r   r   )rS  rr  r   r   r   rr  r  rr  r%  rx  r   rU  ru  r'   r   r   )rS  rr  r   r   r   rr  r  rr  r%  rx  r   r   ru  r'   r   r[  )Nr  F)ru  r'   rz  r   r   r   )r!  r   r   rk  r   r   )r  r   r   rk  r   r   )r   r   r  r  r   rU  r   r8   r  r0   r  r   r$  rA   r   r   )r   r   r  r  r   rY  r   r8   r  r0   r  r   r$  rA   r   r   )r   r   r  r  r   r   r   r8   r  r0   r  r   r$  rA   r   r[  )r   r   r  r  r   r   r   r8   r  r0   r  r   r$  r  r   r[  )r   r   r%  r)   r  r  r   rY  r   r8   r  r0   r  r   r  r   r$  r(   r   r   )r   r   r%  r)   r  r  r   rU  r   r8   r  r0   r  r   r  r   r$  r(   r   r   )r   r   r%  r)   r  r  r   r   r   r8   r  r0   r  r   r  r   r$  r(   r   r[  )r   r   r%  rp  r  r  r   r   r   r8   r  r0   r  r   r  r   r$  r  r   r[  )r   rk  rr  r  r   r   r%  rx  r  r  rm  r  r   r   )r%  rx  rm  r  r  r  r   r   )r%  rx  r   r   )r}  r   r   r   )NNNN)r  rm  r  rm  r   rk  r   r   )r  )r  r   r   r   )NNFNNNF)r  r  r  r  r  r   r  r  r   rk  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	   r   r;   )rr  rm  r   r   )r#  r   )r#  r   r   r   )r   r   )r   r   )r   r   ru  r'   r   r   )T)r   r   r   r   )r   r   r   r   )TTTTTr1  )r/  r   r2  r   r3  r   r4  r   r5  r   r6  r    r   r   )
rr  r;  r   r<  r   r   rm  r=  r:  r>  )
r   rC  r   rk  r   r   rm  r  r   r   )
r   r<  r   r   rm  r=  r:  r>  r   r   )r   r   r  r   r   r   )rj  )rr  r*   r   r   rm  r  r   r   rk  rl  r:  r>  r   r   )F)r   r   )r   rk  r   r   r   r   )NNFN)rs  r&   rr  r  r  r  r  r   r  r  r   r   )FN)r  r   r   rk  r   r   )r  N)r  r+   r   rk  r   r   )NNr}  NNr  NF)r  r  r  r  r  r  r  rx  r%  rx  r  r  r  r  r  r   r   r   )r   r  Fr  TF)r   r   rr  r  r  r   r  r  r  r   r  r   r   r   )r   FFr  )
r  r   r  r   r  r   r  r   r  r:   )r  r1   rH  r   r   rk  r%  rx  r   r   r  r  r   r  )r  NNN)r  r   rH  r   r   rk  r   r  )r  r   rH  r   r   rk  r   r  )r   r   r   rk  r   r   )r   r   r   rk  r%  rx  r   r   )
r  r  r   r   r  r   r  rm  r   r  )r  r   r   r   r   r   )r   rk  r   r   r   r   )
r   r   r   r   r6  r<   r7  r>   r   r   r  )r   NN)r  r   rF  r   r   r   )r   FT)
r#  r   r   rk  rK  r   rL  r   r   rM  )r   rk  rK  r   rL  r   r   rM  )r   r   rK  r   rL  r   r   rM  )NT)r#  r   r   rk  rL  r   )r   T)r   r   rL  r   r   r   )r   Tr   F)r#  r   r   rk  rL  r   rv  r   r  r   r   rw  )
r   rk  rL  r   rv  r   r  r   r   rw  )r   TF)r#  r   r   rk  rL  r   r  r   )r   rk  rL  r   r  r   )r   rk  rL  r   r  r   r   rw  )r   TFr   )
r#  r   r   rk  rL  r   r  r   r  r   )r   rk  rL  r   r  r   r  r   )NFNNNNr  )r  r  r  r  r  r   r  rm  r  rm  r  r  r  r  rr  r   r   r  )r   r  )r  r   rr  r  r   r   )	NNNNr   TFNr  )r  r  r  r  r  r  r  r  r  r  r  r   r  r   r  r  rr  r  r   r   )r  r   r   r   )r   r   )r   
__module____qualname____doc__r   __annotations__r>  r   r   	frozensetr   r   r   r   classmethodr   r   propertyr   setterr   r   r  r   r   r   r   r
  r  r  r  r   r)  r3  r>  r@  rG  r   r  rO  rT  r   rR  rb  rd  rj  rp  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-  r3  r;  rA  rK  rP  rZ  r|  rV  r  r  pickleHIGHEST_PROTOCOLr  r  r  rO  r  r5  r>  r  rT  r\  rZ  rd  r  r  staticmethodr   rN   rL   rq  r  ry  r  r  r  r  r  rM  rx  rp  r  r  r  r  r  rU  r  rs   r  r8  r  r   r  r  r  r
  r  r  r   r  r;  r   r   r*  r-  r/  r8  rA  r@  rS  rW  r  rn  r  rk   r  rl   r  r  r  r  r  r  r  r  r  r  r  r  r  r  rL  r  r  r  r&  r,  r=  rE  rH  rX  r  r  rh  rj  rp  rs  ru  rz  r|  r  r  r  r  r  r  r  r  r  kurtosisr  r  rN  productr  r  rO   r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  __classcell__)r   s   @r   r   r      s7(        	 	" " "O     %(C$8$88888355J    $-IbMMM1111IMMMIII
V V V V
 
 "&    [ U:    [ U, # # # X#J \" " " \" % % % X U%N  &)^/3	D D D D D UDL    [ U$ ( ( ( X( 43334510M0MMMMM0000NNN
,0    U    [ U - - - [ U- @ @ @ U@
    [ U    U< Y Y Y UY 
 
 
 U
6 3 3 3 X U3 H H H XH > > > X>    X U, ( ( ( X U(8 %(^-C -C -C -C -C -C^    X XXX XXVVV XV
   U ) ) ) U) C4 C4 C4 C4 UC4J    p p p p Upj  "%
 !$"%"%!
 
 
 
 
 X
  "%
 !$"%!
 
 
 
 
 X
  "%
 !$"%!
 
 
 
 
 X
  "&F> !%"& "F> F> F> F> F> UF>P  .1	 %(^"%	 	 	 	 	 X	  .1	 %(^	 	 	 	 	 X	  .1	 %(^	 	 	 	 	 X	 .1^e n%(^e e e e e eN !$CF     X !$    X !$    X !"@7<@ @ @ @ @ U@J 
 
 
 U

 ^, ^, ^, U^,F 8 8 8 U8" 8 8 8 U8 ; ; ; U; 
 
 
 U
 D
 D
 D
 UD
L    U K K K K UK 
 
 
 
 U
< S S S S US2 
 
 
 
 U
0 )" )" )" )" U)"V @ @ @ @ U@D I I I I UIb % % % %2   >  $ $ $ $ & & & U& 9K 9K 9K X9K@ #"""" GK    : M M M UM 	
 	
 	
 U	
 !R !R !R U!RL1 1 1 1   U 
M 
M U
M 
 ##'-1,0)-;? /315/3 'k
 k
 k
 k
 k
 Uk
Z  PTF

 "& " "DH*1!!15"%!F
 F
 F
 F
 F
 UF
P
  ), $CG3748"9=!)!W
 W
 W
 W
 W
 UW
r  "IO)- $!%59@
 @
 @
 @
 @
 U@
D 
 +2/15[
 [
 [
 [
 [
 U[
z #tGF GF GF GF GF UGFR X7 X7 UX7t   .1-0,//2 #$'!$!"#&), #03"/     X4 
 .1-0,//2 #$'!$!"#&), #03"/     X4  37]
 .2-1,0/3 $ $(!%"##')- $04 #/]
 ]
 ]
 ]
 ]
 U]
~  H9 *.26+/157;%)H9 H9 H9 H9 H9 UH9T    .1-0#&),"*-!%( #"%!$!$*-/     X4 
 .1-0#&),"*-!%( #"%!$!$*-/     X4  PTQ
 .2-1#')-#*1"%) $"& !%!)15/Q
 Q
 Q
 Q
 Q
 UQ
l a
 a
 a
 a
 Ua
F  #'o o o o Uob( ( ( " " " U"      / / / U/D    U A A A UAF 	 	 \	 _^XDAAA
 RV%(^ {! {! {! {! U BA{!z  ),
 '*),!!
 
 
 
 
 X
  ),
 '*),!"%!
 
 
 
 
 X
  ),
 '*),!!
 
 
 
 
 X
 )-' '+)-"%' ' ' ' ' 'R 
 % S) S) S) S) US)j 
  
  
  U
  E& E& E& E& UE&N D& D& D& D& UD&L  +."%"% 
 
 
 
 
 X
  +."% 
 
 
 
 
 X
  +."% 
 
 
 
 
 X
 +/$"("#'e( e( e( e( e( e(N  +."%"      X  +."%"%"      X  +."%"      X" #'+/$"(#"#'6B 6B 6B 6B 6B 6Bt U/  '+%(^"$&F U/ U/ U/ U/ U/ U/n    U<	
 	
 	
 	
( ( (   	"
 "
 "
 "
 U"
L   nL nL nL nL nL` V$ V$ V$ V$ UV$p W% W% W% W% UW%r  !+/ "X X X X UXt    X    X eI eI eI UeIT 9 9 9 9 U9v 3 3 3 U3  '6 '6 '6 U'6R      U , , , U,
 
 
 U
 
) 
) 
) X U
) Y Y Y UY Y Y UY ( ( X( ( ( ( X( $W $W X$WL  &)^%	E" E" E" E" UE"N i
 i
 i
 i
 Ui
V % % % U% $ $ $ $ U$ 9< 9> 9> 9> 9> U9>v  ## $ $!%&6S? S? S? S? US?p 
 ! :>#> #> #> #> #> U#>J 
 ! l> l> l> l> l> Ul>\  ! :>c
 c
 c
 c
 c
 Uc
J  ! :>n
 n
 n
 n
 n
 Un
`  n[?
 [? [? [? [? [? U[?z  &.XC  IM:>XC XC XC XC XC UXCz p2 p2 p2 Up2jE< E< E< E<NE> E> E> E>NE> E> E> E>NE@ E@ E@ E@N     U$ I I UI@  q
 !q q q q q Uqf  (,.2&*z
 z
 z
 z
 Uz
x 9- 9- 9- 9- U9-v 
 )/ R- R- R- R- UR-h  37158?"2=37 z
 z
 z
 z
 Uz
x  EN"6<] ] ] ] U]D   !2j j j j jX  " "%(^&*e e e e UeN  " +' +' +' +' U+'Z  " <' <' <' <' U<'|  nj-
  j- j- j- j- j- Uj-X  nfQ
  "fQ fQ fQ fQ fQ UfQP  nm

  "m
 m
 m
 m
 m
 Um
b ()"~!T: T: T: T: T:l !9 !9 !9 U!9F   %(^s s s s Usj  %(^`> `> `> `> U`>D  %(^#*'.P? P? P? P? UP?j  	z0 z0 z0 z0 Uz0x   	Q: Q: Q: Q: UQ:f 
 -
 -
 -
 -
 U-
d 

 

 

 

 

 

 

 

 

 

 

 

 
 !)
 )
 )
 )
 U)
V
 
 
 
 


 
 
 
 

T T T T TV V V V V 
 "
 
 
 
 U
( "
 
 
 
 
 
  "
 
 
 
 
 
  "
 
 
 
 
 
 
 "
 
 
 
 U
* "
 
 
 
 
 
( "
 
 
 
 
 
( "

 

 

 

 

 

 "

 

 

 

 

 

 "

 

 

 

 

 

 "

 

 

 

 

 

 H

 "
 
 
 
 U
6 "
 
 
 
 
 
  "
 
 
 
 
 
& G
 #'#,0]
 ]
 ]
 ]
 U]
~  -5FG FG FG FG UFGP S	 !! !!=A""#8<-5
 
 
 
 "! U
8 	 	 	 U	 ? ? ? U? ? ? ? U? ? ? ? U? 
 
 
 U
 
 
 
 U
 ? ? ? U? ? ? ? U? ? ? ? U? > > > U> ? ? ? U? " " " U"& T3 T3 T3 UT3l T2 T2 T2 UT2 T2 T2 T2 T2r   r   a  
{desc}

Parameters
----------
axis : {axis_descr}
    Axis for the function to be applied on.
    For `Series` this parameter is unused and defaults to 0.

    For DataFrames, specifying ``axis=None`` will apply the aggregation
    across both axes.

    .. versionadded:: 2.0.0

skipna : bool, default True
    Exclude NA/null values when computing the result.
numeric_only : bool, default False
    Include only float, int, boolean columns.

{min_count}**kwargs
    Additional keyword arguments to be passed to the function.

Returns
-------
{name1} or scalar
    Value containing the calculation referenced in the description.{see_also}{examples}
a=  
{desc}

Parameters
----------
axis : {axis_descr}
    Axis for the function to be applied on.
    For `Series` this parameter is unused and defaults to 0.

    .. warning::

        The behavior of DataFrame.{name} with ``axis=None`` is deprecated,
        in a future version this will reduce over both axes and return a scalar
        To retain the old behavior, pass axis=0 (or do not pass axis).

    .. versionadded:: 2.0.0

skipna : bool, default True
    Exclude NA/null values when computing the result.
numeric_only : bool, default False
    Include only float, int, boolean columns. Not implemented for Series.

{min_count}**kwargs
    Additional keyword arguments to be passed to the function.

Returns
-------
{name1} or scalar
    Value containing the calculation referenced in the description.{see_also}{examples}
a  
{desc}

Parameters
----------
axis : {axis_descr}
    For `Series` this parameter is unused and defaults to 0.

    .. warning::

        The behavior of DataFrame.{name} with ``axis=None`` is deprecated,
        in a future version this will reduce over both axes and return a scalar
        To retain the old behavior, pass axis=0 (or do not pass axis).

skipna : bool, default True
    Exclude NA/null values. If an entire row/column is NA, the result
    will be NA.
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 False
    Include only float, int, boolean columns. Not implemented for Series.
**kwargs :
    Additional keywords have no effect but might be accepted
    for compatibility with NumPy.

Returns
-------
{name1} or {name2} (if level specified)
    {return_desc}

See Also
--------
{see_also}{notes}{examples}
av  scipy.stats.sem : Compute standard error of the mean.
{name2}.std : Return sample standard deviation over requested axis.
{name2}.var : Return unbiased variance over requested axis.
{name2}.mean : Return the mean of the values over the requested axis.
{name2}.median : Return the median of the values over the requested axis.
{name2}.mode : Return the mode(s) of the Series.z8Unbiased standard error of the mean over requested axis.a  numpy.std : Compute the standard deviation along the specified axis.
{name2}.var : Return unbiased variance over requested axis.
{name2}.sem : Return unbiased standard error of the mean over requested axis.
{name2}.mean : Return the mean of the values over the requested axis.
{name2}.median : Return the median of the values over the requested axis.
{name2}.mode : Return the mode(s) of the Series.z'Standard deviation over requested axis.zg

Notes
-----
To have the same behaviour as `numpy.std`, use `ddof=0` (instead of the
default `ddof=1`)ay  

Examples
--------
>>> df = pd.DataFrame({'person_id': [0, 1, 2, 3],
...                    'age': [21, 25, 62, 43],
...                    'height': [1.61, 1.87, 1.49, 2.01]}
...                   ).set_index('person_id')
>>> df
           age  height
person_id
0           21    1.61
1           25    1.87
2           62    1.49
3           43    2.01

The standard deviation of the columns can be found as follows:

>>> df.std()
age       18.786076
height     0.237417
dtype: float64

Alternatively, `ddof=0` can be set to normalize by N instead of N-1:

>>> df.std(ddof=0)
age       16.269219
height     0.205609
dtype: float64a?  

Examples
--------
>>> df = pd.DataFrame({'person_id': [0, 1, 2, 3],
...                    'age': [21, 25, 62, 43],
...                    'height': [1.61, 1.87, 1.49, 2.01]}
...                   ).set_index('person_id')
>>> df
           age  height
person_id
0           21    1.61
1           25    1.87
2           62    1.49
3           43    2.01

>>> df.var()
age       352.916667
height      0.056367
dtype: float64

Alternatively, ``ddof=0`` can be set to normalize by N instead of N-1:

>>> df.var(ddof=0)
age       264.687500
height      0.042275
dtype: float64ag  
{desc}

Parameters
----------
axis : {{0 or 'index', 1 or 'columns', None}}, default 0
    Indicate which axis or axes should be reduced. For `Series` this parameter
    is unused and defaults to 0.

    * 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 False
    Include only boolean columns. 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}, as for an empty row/column.
    If skipna is False, then NA are treated as True, because these are not
    equal to zero.
**kwargs : any, default None
    Additional keywords have no effect but might be accepted for
    compatibility with NumPy.

Returns
-------
{name2} or {name1}
    If axis=None, then a scalar boolean is returned.
    Otherwise a Series is returned with index matching the index argument.

{see_also}
{examples}zReturn 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([], dtype="float64").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 values in each column all return True.

>>> df.all()
col1     True
col2    False
dtype: bool

Specify ``axis='columns'`` to check if values in each row 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
zSee 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} over a DataFrame or Series axis.

Returns a DataFrame or Series of the same size containing the cumulative
{desc}.

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'.
    For `Series` this parameter is unused and defaults to 0.
skipna : bool, default True
    Exclude NA/null values. If an entire row/column is NA, the result
    will be NA.
numeric_only : bool, default False
    Include only float, int, boolean columns.
*args, **kwargs
    Additional keywords have no effect but might be accepted for
    compatibility with NumPy.

Returns
-------
{name1} or {name2}
    Return cumulative {desc} of {name1} or {name2}.

See Also
--------
core.window.expanding.Expanding.{accum_func_name} : Similar functionality
    but ignores ``NaN`` values.
{name2}.{accum_func_name} : Return the {desc} over
    {name2} axis.
{name2}.cummax : Return cumulative maximum over {name2} axis.
{name2}.cummin : Return cumulative minimum over {name2} axis.
{name2}.cumsum : Return cumulative sum over {name2} axis.
{name2}.cumprod : Return cumulative product over {name2} axis.

{examples}aZ  
Return cumulative {desc} over a DataFrame or Series axis.

Returns a DataFrame or Series of the same size containing the cumulative
{desc}.

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'.
    For `Series` this parameter is unused and defaults to 0.
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} or {name2}
    Return cumulative {desc} of {name1} or {name2}.

See Also
--------
core.window.expanding.Expanding.{accum_func_name} : Similar functionality
    but ignores ``NaN`` values.
{name2}.{accum_func_name} : Return the {desc} over
    {name2} axis.
{name2}.cummax : Return cumulative maximum over {name2} axis.
{name2}.cummin : Return cumulative minimum over {name2} axis.
{name2}.cumsum : Return cumulative sum over {name2} axis.
{name2}.cumprod : Return cumulative product over {name2} axis.

{examples}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.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
a2  See 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.
zReturn whether any element is True, potentially over an axis.

Returns False unless there is at least one element within a series or
along a Dataframe axis that is True or equivalent (e.g. non-zero or
non-empty).a\  Examples
--------
**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([], dtype="float64").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}stat_func_exampler  Sum         )	stat_funcverbdefault_outputlevel_output_0level_output_1a  

By default, the sum of an empty or all-NA Series is ``0``.

>>> pd.Series([], dtype="float64").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([], dtype="float64").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)
nanr  Max   r   _max_examplesr  Minr  _min_examplesz

See Also
--------
Series.skew : Return unbiased skew over requested axis.
Series.var : Return unbiased variance over requested axis.
Series.std : Return unbiased standard deviation over requested axis.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([], dtype="float64").prod()
1.0

This can be controlled with the ``min_count`` parameter

>>> pd.Series([], dtype="float64").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)
nanzmin_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.
r#  r  r   r   c                   |dk    rd}d}d}nd}d}d}| dk    r"t           }t          }t          }t          }dd	i}	nt| d
k    r"t           }t          }t
          }t          }ddi}	nL| dk    rt          }d}t          }t          }ddi}	n)| dk    rt          }d}t          }t          }ddi}	n| dk    r"t          }d}t          }t          }dt          i}	n| dk    r"t          }d}t          }t          }dt          i}	n| dk    rt          }d}t          }d}ddi}	n| dk    rt          }d}t          }d}ddi}	nz| dk    rt          }d}t           }d}ddi}	n\| dk    r7t          }d }t"          }t$                              |!          }dt(          d"}	n| d#k    r1t          }d$}d%}t*                              |!          }dt,          d"}	n| d&k    rt          }d'}t.          }d(}ddi}	n| d)k    rt          }d*}d}d+}ddi}	n| d,k    r%|dk    rt0          }nt2          }d}d}t4          }d-di}	n| d.k    r%|dk    rt0          }nt2          }d/}d}t6          }d-di}	n]| d0k    r%|dk    rt0          }nt2          }d1}d}t8          }d-di}	n2| d2k    r%|dk    rt0          }nt2          }d3}d}t:          }d-di}	nt<           |j        d5|| |||||d4|	}
|
S )6zB
    Generate the docstring for a Series/DataFrame reduction.
    r   scalarr   z{index (0)}r   z{index (0), columns (1)}r  empty_valueFalser  Truer  zReturn the minimum of the values over the requested axis.

If you want the *index* of the minimum, use ``idxmin``. This is the equivalent of the ``numpy.ndarray`` method ``argmin``.r  r  r  zReturn the maximum of the values over the requested axis.

If you want the *index* of the maximum, use ``idxmax``. This is the equivalent of the ``numpy.ndarray`` method ``argmax``.r  zfReturn the sum of the values over the requested axis.

This is equivalent to the method ``numpy.sum``.rN  z9Return the product of the values over the requested axis.r  z8Return the median of the values over the requested axis.a  

            Examples
            --------
            >>> s = pd.Series([1, 2, 3])
            >>> s.median()
            2.0

            With a DataFrame

            >>> df = pd.DataFrame({'a': [1, 2], 'b': [2, 3]}, index=['tiger', 'zebra'])
            >>> df
                   a   b
            tiger  1   2
            zebra  2   3
            >>> df.median()
            a   1.5
            b   2.5
            dtype: float64

            Using axis=1

            >>> df.median(axis=1)
            tiger   1.5
            zebra   2.5
            dtype: float64

            In this case, `numeric_only` should be set to `True`
            to avoid getting an error.

            >>> df = pd.DataFrame({'a': [1, 2], 'b': ['T', 'Z']},
            ...                   index=['tiger', 'zebra'])
            >>> df.median(numeric_only=True)
            a   1.5
            dtype: float64r  z6Return the mean of the values over the requested axis.aw  

            Examples
            --------
            >>> s = pd.Series([1, 2, 3])
            >>> s.mean()
            2.0

            With a DataFrame

            >>> df = pd.DataFrame({'a': [1, 2], 'b': [2, 3]}, index=['tiger', 'zebra'])
            >>> df
                   a   b
            tiger  1   2
            zebra  2   3
            >>> df.mean()
            a   1.5
            b   2.5
            dtype: float64

            Using axis=1

            >>> df.mean(axis=1)
            tiger   1.5
            zebra   2.5
            dtype: float64

            In this case, `numeric_only` should be set to `True` to avoid
            getting an error.

            >>> df = pd.DataFrame({'a': [1, 2], 'b': ['T', 'Z']},
            ...                   index=['tiger', 'zebra'])
            >>> df.mean(numeric_only=True)
            a   1.5
            dtype: float64r  zyReturn unbiased variance over requested axis.

Normalized by N-1 by default. This can be changed using the ddof argument.notesr  zReturn sample standard deviation over requested axis.

Normalized by N-1 by default. This can be changed using the ddof argument.)name2)r  return_descr|  zReturn unbiased standard error of the mean over requested axis.

Normalized by N-1 by default. This can be changed using the ddof argumenta  

            Examples
            --------
            >>> s = pd.Series([1, 2, 3])
            >>> round(s.sem(), 6)
            0.57735

            With a DataFrame

            >>> df = pd.DataFrame({'a': [1, 2], 'b': [2, 3]}, index=['tiger', 'zebra'])
            >>> df
                   a   b
            tiger  1   2
            zebra  2   3
            >>> df.sem()
            a   0.5
            b   0.5
            dtype: float64

            Using axis=1

            >>> df.sem(axis=1)
            tiger   0.5
            zebra   0.5
            dtype: float64

            In this case, `numeric_only` should be set to `True`
            to avoid getting an error.

            >>> df = pd.DataFrame({'a': [1, 2], 'b': ['T', 'Z']},
            ...                   index=['tiger', 'zebra'])
            >>> df.sem(numeric_only=True)
            a   0.5
            dtype: float64r  z=Return unbiased skew over requested axis.

Normalized by N-1.a-  

            Examples
            --------
            >>> s = pd.Series([1, 2, 3])
            >>> s.skew()
            0.0

            With a DataFrame

            >>> df = pd.DataFrame({'a': [1, 2, 3], 'b': [2, 3, 4], 'c': [1, 3, 5]},
            ...                   index=['tiger', 'zebra', 'cow'])
            >>> df
                    a   b   c
            tiger   1   2   1
            zebra   2   3   3
            cow     3   4   5
            >>> df.skew()
            a   0.0
            b   0.0
            c   0.0
            dtype: float64

            Using axis=1

            >>> df.skew(axis=1)
            tiger   1.732051
            zebra  -1.732051
            cow     0.000000
            dtype: float64

            In this case, `numeric_only` should be set to `True` to avoid
            getting an error.

            >>> df = pd.DataFrame({'a': [1, 2, 3], 'b': ['T', 'Z', 'X']},
            ...                   index=['tiger', 'zebra', 'cow'])
            >>> df.skew(numeric_only=True)
            a   0.0
            dtype: float64r  zReturn unbiased kurtosis over requested axis.

Kurtosis obtained using Fisher's definition of
kurtosis (kurtosis of normal == 0.0). Normalized by N-1.a7  

            Examples
            --------
            >>> s = pd.Series([1, 2, 2, 3], index=['cat', 'dog', 'dog', 'mouse'])
            >>> s
            cat    1
            dog    2
            dog    2
            mouse  3
            dtype: int64
            >>> s.kurt()
            1.5

            With a DataFrame

            >>> df = pd.DataFrame({'a': [1, 2, 2, 3], 'b': [3, 4, 4, 4]},
            ...                   index=['cat', 'dog', 'dog', 'mouse'])
            >>> df
                   a   b
              cat  1   3
              dog  2   4
              dog  2   4
            mouse  3   4
            >>> df.kurt()
            a   1.5
            b   4.0
            dtype: float64

            With axis=None

            >>> df.kurt(axis=None)
            -0.9886927196984727

            Using axis=1

            >>> df = pd.DataFrame({'a': [1, 2], 'b': [3, 4], 'c': [3, 4], 'd': [1, 2]},
            ...                   index=['cat', 'dog'])
            >>> df.kurt(axis=1)
            cat   -6.0
            dog   -6.0
            dtype: float64rs  accum_func_nameru  r  rp  rq  rj  rk  )descr#  name1r  
axis_descrsee_alsoexamplesr  )	_bool_doc	_any_desc_any_see_also_any_examples	_all_desc_all_see_also_all_examples_num_doc_stat_func_see_alsor  r  _sum_prod_doc_sum_examples_min_count_stub_prod_examples_num_ddof_doc_var_examples_std_examples_std_see_alsor  _std_return_desc_sem_see_also_sem_return_desc_skew_see_also_cnum_series_doc_cnum_pd_doc_cumsum_examples_cumprod_examples_cummin_examples_cummax_examplesr   )r#  r  r  r  r  base_docr  r  r  r   docstrs              r   make_docr4  [4  s    qyy"

/
u}}  )	  (	I 	
 ' r"	I 	
 ' r"	 > 	 ' /	 J&!/			I&"F r"	G&"F r"	 K 	 !2	  	
 ! ''e'44.>??	 & 	
"F !''e'44.>??	P!&N r"	 	 )T r"			199'HH#H##U+			199'HH#H$#V,			199'HH#H##U+			199'HH#H##U+ "!X_ 		 	 	 	F Mr   )r#  r   r  r   r   r   )
__future__r   rW  r   r   datetimer?  	functoolsr   r  r   r  r  r  rF  typingr   r	   r
   r   r   r   r   r   r   r   r  numpyrM  pandas._configr   pandas._libsr   pandas._libs.libr   pandas._libs.tslibsr   r   r   pandas._typingr   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   pandas.compatrE   pandas.compat._constantsrF   pandas.compat._optionalrG   pandas.compat.numpyrH   r?  pandas.errorsrI   rJ   rK   rL   pandas.errors.cowrM   pandas.util._decoratorsrN   rO   pandas.util._exceptionsrP   pandas.util._validatorsrQ   rR   rS   rT   pandas.core.dtypes.astyperU   pandas.core.dtypes.castrV   pandas.core.dtypes.commonrW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   pandas.core.dtypes.dtypesrd   re   rf   pandas.core.dtypes.genericrg   rh   pandas.core.dtypes.inferenceri   rj   pandas.core.dtypes.missingrk   rl   pandas.corerm   rI  rn   ro   rp   rq   rr   rs   pandas.core.array_algos.replacert   pandas.core.arraysru   pandas.core.baserv   pandas.core.constructionrw   pandas.core.flagsrx   pandas.core.indexes.apiry   rz   r{   r|   r}   r~   pandas.core.internalsr   pandas.core.methods.describer   pandas.core.missingr   r   r   pandas.core.reshape.concatr   pandas.core.shared_docsr   pandas.core.sortingr   pandas.core.windowr   r   r   r   pandas.io.formats.formatr   r   pandas.io.formats.printingr   collections.abcr   r   r   r   r   r   r   r  r   r   r   r   pandas.core.indexers.objectsr   r  r   _shared_doc_kwargsIndexingMixinr   r  r   r$  r)  r*  r'  r(  
_std_notesr&  r%  r  r  r  r  r-  r,  r0  r.  r/  r1  r  r  r  r  r!  r  r  r  r+  r  r#  r"  r4  r  r   r   <module>rd     s
   " " " " " " "                             				 



                             ! ! ! ! ! !       - - - - - -         
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .^ 3 2 2 2 2 2      ? > > > > > . . . . . .            = < < < < <        5 4 4 4 4 4            5 4 4 4 4 4 4 4 4 4 4 4                                      
                     
                  = < < < < < - - - - - - ) ) ) ) ) ) 2 2 2 2 2 2 # # # # # #                / . . . . . 9 9 9 9 9 9         
 . - - - - - 0 0 0 0 0 0 3 3 3 3 3 3                   4 3 3 3 3 3 /              /.....                  988888......
  ,`00
 
 EA2 EA2 EA2 EA2 EA2lH2 EA2 EA2 EA2PB@!F$L4< 4+ 
<8!	F	,\$L" H? B? B? B? B	DL%  !( 0188%1UV 9     , ""56==%!TU >       ""56==%!TU >      HO .n n n n n nr   