
    Pi7                      U d dl mZ d dlZd dlmZmZmZmZmZm	Z	m
Z
mZ d dlZd dlZd dlmZ d dlmZmZmZmZmZmZmZ d dlmZ d dlmZmZ d dlmZ d d	l m!Z! d d
l"m#Z#m$Z$ d dl%m&Z&m'Z' d dl(m)c m*Z+ d dl,m-Z- d dl.m/Z/ d dl0m1Z1m2Z2 d dl3m4Z4 d dl5m6Z6m7Z7m8Z8 d dl9m:Z: d dl;m<Z< d dl=m>Z> d dl?m@Z@ d dlAmBZBmCZC d dlDmEZEmFZF d dlGmHZHmIZI d dlJmKZK d dlLmMZMmNZN d dlOmPZPmQZQ er6d dlRmSZSmTZT d dlmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZambZb d dlcmdZdmeZe d dl3m4Z4 i Zfdegd<    ed            G d! d"e6e1                      Zh G d# d$e1e2          Zi G d% d&eh          Zj ed            G d' d(eiej                      Zk G d) d*ej          Zl ed            G d+ d,eiel                      Zm G d- d.ej          Zn ed            G d/ d0eien                      Zodod4Zpehjq        ep_q        	 	 	 	 dpdqd9Zr ed            G d: d;e:                      ZsedrdA            ZtedsdC            ZtdtdEZt	 	 	 dudvdVZu	 	 	 dudwdYZvdxdbZw	 	 	 	 dydzdfZx	 	 	 	 d{d|dkZyd}dnZzdS )~    )annotationsN)TYPE_CHECKINGConcatenateLiteralSelfcastfinalno_type_checkoverload)lib)
BaseOffsetIncompatibleFrequencyNaTPeriod	Timedelta	Timestamp	to_offset)NDFrameT)AbstractMethodErrorPandas4Warning)
set_module)find_stack_level)
ArrowDtypePeriodDtype)ABCDataFrame	ABCSeries)ResamplerWindowApply)ArrowExtensionArray)PandasObjectSelectionMixin)NDFrame)BaseGroupByGroupByget_groupby)Grouper)
BinGrouper)
MultiIndex)Index)DatetimeIndex
date_range)PeriodIndexperiod_range)TimedeltaIndextimedelta_range)concat)is_subperiodis_superperiod)DayTick)CallableHashable)AnyAnyArrayLikeAxis
FreqIndexT	Frequency
IndexLabelInterpolateOptionsPTTimedeltaConvertibleTypesTimeGrouperOriginTimestampConvertibleTypesTimeUnitnpt)	DataFrameSerieszdict[str, str]_shared_docs_kwargszpandas.api.typingc                      e Zd ZU dZded<   ded<   ded<    e            Zded	<    eh d
          Zg dZ	dddddfdZ
edgd            Zedhd            Zeedid                        Zdjd Zd! Zed"             Zedkd*            Zedld-            Zedm fd/            Zednd0            ZeZeZed1             Zd2 Zdodpd5Zdndqd8Zd9 Zedrd<            Zd= Zedndpd>            Zedndpd?            Z edndpd@            Z!e	 dsdBddCddDdtdK            Z"edndL            Z#e	 	 dudvdO            Z$e	 	 dudvdP            Z%e	 	 dudvdQ            Z&e	 	 dudvdR            Z'e	 	 	 dwdxdU            Z(e	 	 	 dwdxdV            Z)edydzdW            Z*e	 dydzdX            Z+e	 	 d{d|d[            Z,e	 	 d{d|d\            Z-e	 	 d{d|d]            Z.ed^             Z/ed_             Z0ed`             Z1eda             Z2ed}d~de            Z3 xZ4S )	Resamplera  
    Class for resampling datetimelike data, a groupby-like operation.
    See aggregate, transform, and apply functions on this object.

    It's easiest to use obj.resample(...) to use Resampler.

    Parameters
    ----------
    obj : Series or DataFrame
    groupby : TimeGrouper

    Returns
    -------
    a Resampler of the appropriate type

    Notes
    -----
    After resampling, see aggregate, apply, and transform functions.
    r&   _grouperTimeGrouper_timegrouperz,DatetimeIndex | TimedeltaIndex | PeriodIndexbinnerzfrozenset[Hashable]
exclusions>   axobj_indexer)freqclosedlabel
conventionoriginoffsetFN)
group_keys	selectioninclude_groupsrO   r!   timegrouper	gpr_indexr(   rW   boolrY   returnNonec                  |rt          d          || _        d | _        d| _        || _        d| _        | j                            |                     |          d|          \  | _        | _	        | _
        |                                 \  | _        | _        || _        | j        j        !t!          | j        j        g          | _        d S t!                      | _        d S )Nz)include_groups=True is no longer allowed.T)sortr[   )
ValueErrorrK   keysr`   rW   as_index_set_grouper_convert_objrO   rN   rP   _get_binnerrL   rI   
_selectionkey	frozensetrM   )selfrO   rZ   r[   rW   rX   rY   s          h/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/pandas/core/resample.py__init__zResampler.__init__   s      	JHIII'		$+/+<+I+Ic"" ,J ,
 ,
($'4= &*%5%5%7%7"T]# ,'):)>(?@@DOOO'kkDOOO    strc                      fd j         D             }t                     j         dd                    |           dS )z@
        Provide a nice str repr of our rolling object.
        c              3  x   K   | ]4}t          j        |d           | dt          j        |           V  5d S )N=)getattrrK   ).0krj   s     rk   	<genexpr>z$Resampler.__str__.<locals>.<genexpr>   s_       
 
t(!T22> 2274,a0022>>>>
 
rm   z [z, ])_attributestype__name__join)rj   attrss   ` rk   __str__zResampler.__str__   s\    

 
 
 
%
 
 

 t**%<<5)9)9<<<<rm   attrc                    || j         v rt                              | |          S || j        v rt	          | j        |          S || j        v r| |         S t                              | |          S N)_internal_names_setobject__getattribute__rw   rr   rK   rO   )rj   r}   s     rk   __getattr__zResampler.__getattr__   st    4+++**46664###4,d33348:&&tT222rm   c                L    | j         duo| j         j        dup| j         j        duS )zP
        Is the resampling from a DataFrame column or MultiIndex level.
        N)rK   rh   levelrj   s    rk   _from_selectionzResampler._from_selection   s8      , 
!-T1B1HPT1T	
rm   r   c                *    |                                 S )z
        Provide any conversions for the object in order to correctly handle.

        Parameters
        ----------
        obj : Series or DataFrame

        Returns
        -------
        Series or DataFrame
        )_consolidate)rj   rO   s     rk   re   zResampler._convert_obj   s     !!!rm   c                     t          |           r   r   r   s    rk   _get_binner_for_timezResampler._get_binner_for_time       !$'''rm   c                   |                                  \  }}}t          |          t          |          k    sJ | j        j        |                    | j        j                  }t          ||| j                  }||fS )zk
        Create the BinGrouper, assume that self.set_grouper(obj)
        has already been called.
        N)indexer)r   lenrK   _arrow_dtypeastyper&   rP   )rj   rL   bins	binlabelsbin_groupers        rk   rf   zResampler._get_binner   s     #'";";"="=i4yyC	NN****)5!(():)GHHI y$-HHH{""rm   func!Callable[Concatenate[Self, P], T]argsP.argskwargsP.kwargsr>   c                    d S r    rj   r   r   r   s       rk   pipezResampler.pipe   	     Crm   tuple[Callable[..., T], str]r6   c                    d S r   r   r   s       rk   r   zResampler.pipe  r   rm   @Callable[Concatenate[Self, P], T] | tuple[Callable[..., T], str]c                >     t                      j        |g|R i |S )aN	  
        Apply a ``func`` with arguments to this Resampler object and return its result.

        Use `.pipe` when you want to improve readability by chaining together
        functions that expect Series, DataFrames, GroupBy or Resampler objects.
        Instead of writing

        >>> h = lambda x, arg2, arg3: x + 1 - arg2 * arg3
        >>> g = lambda x, arg1: x * 5 / arg1
        >>> f = lambda x: x**4
        >>> df = pd.DataFrame([["a", 4], ["b", 5]], columns=["group", "value"])
        >>> h(g(f(df.groupby("group")), arg1=1), arg2=2, arg3=3)  # doctest: +SKIP

        You can write

        >>> (
        ...     df.groupby("group").pipe(f).pipe(g, arg1=1).pipe(h, arg2=2, arg3=3)
        ... )  # doctest: +SKIP

        which is much more readable.

        Parameters
        ----------
        func : callable or tuple of (callable, str)
            Function to apply to this Resampler object or, alternatively,
            a `(callable, data_keyword)` tuple where `data_keyword` is a
            string indicating the keyword of `callable` that expects the
            Resampler object.
        *args : iterable, optional
            Positional arguments passed into `func`.
        **kwargs : dict, optional
                A dictionary of keyword arguments passed into `func`.

        Returns
        -------
        any
            The result of applying ``func`` to the Resampler object.

        See Also
        --------
        Series.pipe : Apply a function with arguments to a series.
        DataFrame.pipe: Apply a function with arguments to a dataframe.
        apply : Apply function to each group instead of to the
            full Resampler object.

        Notes
        -----
        See more `here
        <https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#piping-function-calls>`_

        Examples
        --------
        >>> df = pd.DataFrame(
        ...     {"A": [1, 2, 3, 4]}, index=pd.date_range("2012-08-02", periods=4)
        ... )
        >>> df
                    A
        2012-08-02  1
        2012-08-03  2
        2012-08-04  3
        2012-08-05  4

        To get the difference between each 2-day period's maximum and minimum
        value in one pass, you can do

        >>> df.resample("2D").pipe(lambda x: x.max() - x.min())
                    A
        2012-08-02  1
        2012-08-04  1
        )superr   )rj   r   r   r   	__class__s       rk   r   zResampler.pipe
  s,    Z uww|D242226222rm   c                z    t          | |||                                          }||} | j        |g|R i |}|S )a  
        Aggregate using one or more operations over the specified axis.

        Parameters
        ----------
        func : function, str, list or dict
            Function to use for aggregating the data. If a function, must either
            work when passed a DataFrame or when passed to DataFrame.apply.

            Accepted combinations are:

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

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

            The return can be:

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

        See Also
        --------
        DataFrame.groupby.aggregate : Aggregate using callable, string, dict,
            or list of string/callables.
        DataFrame.resample.transform : Transforms the Series on each group
            based on the given function.
        DataFrame.aggregate: Aggregate using one or more
            operations over the specified axis.

        Notes
        -----
        The aggregation operations are always performed over an axis, either the
        index (default) or the column axis. This behavior is different from
        `numpy` aggregation functions (`mean`, `median`, `prod`, `sum`, `std`,
        `var`), where the default is to compute the aggregation of the flattened
        array, e.g., ``numpy.mean(arr_2d)`` as opposed to
        ``numpy.mean(arr_2d, axis=0)``.

        `agg` is an alias for `aggregate`. Use the alias.

        Functions that mutate the passed object can produce unexpected
        behavior or errors and are not supported. See :ref:`gotchas.udf-mutation`
        for more details.

        A passed user-defined-function will be passed a Series for evaluation.

        If ``func`` defines an index relabeling, ``axis`` must be ``0`` or ``index``.

        Examples
        --------
        >>> s = pd.Series(
        ...     [1, 2, 3, 4, 5], index=pd.date_range("20130101", periods=5, freq="s")
        ... )
        >>> s
        2013-01-01 00:00:00    1
        2013-01-01 00:00:01    2
        2013-01-01 00:00:02    3
        2013-01-01 00:00:03    4
        2013-01-01 00:00:04    5
        Freq: s, dtype: int64

        >>> r = s.resample("2s")

        >>> r.agg("sum")
        2013-01-01 00:00:00    3
        2013-01-01 00:00:02    7
        2013-01-01 00:00:04    5
        Freq: 2s, dtype: int64

        >>> r.agg(["sum", "mean", "max"])
                            sum  mean  max
        2013-01-01 00:00:00    3   1.5    2
        2013-01-01 00:00:02    7   3.5    4
        2013-01-01 00:00:04    5   5.0    5

        >>> r.agg({"result": lambda x: x.mean() / x.std(), "total": "sum"})
                            result  total
        2013-01-01 00:00:00  2.121320      3
        2013-01-01 00:00:02  4.949747      7
        2013-01-01 00:00:04       NaN      5

        >>> r.agg(average="mean", total="sum")
                                average  total
        2013-01-01 00:00:00      1.5      3
        2013-01-01 00:00:02      3.5      7
        2013-01-01 00:00:04      5.0      5
        )r   r   )r   agg_groupby_and_aggregate)rj   r   r   r   resulthows         rk   	aggregatezResampler.aggregateY  sX    F &dDtFKKKOOQQ>C0T0FtFFFvFFFrm   c                ^     | j                             | j                  j        |g|R i |S )a  
        Call function producing a like-indexed Series on each group.

        Return a Series with the transformed values.

        Parameters
        ----------
        arg : function
            To apply to each group. Should return a Series with the same index.
        *args, **kwargs
            Additional arguments and keywords.

        Returns
        -------
        Series
            A Series with the transformed values, maintaining the same index as
            the original object.

        See Also
        --------
        core.resample.Resampler.apply : Apply a function along each group.
        core.resample.Resampler.aggregate : Aggregate using one or more operations
            over the specified axis.

        Examples
        --------
        >>> s = pd.Series([1, 2], index=pd.date_range("20180101", periods=2, freq="1h"))
        >>> s
        2018-01-01 00:00:00    1
        2018-01-01 01:00:00    2
        Freq: h, dtype: int64

        >>> resampled = s.resample("15min")
        >>> resampled.transform(lambda x: (x - x.mean()) / x.std())
        2018-01-01 00:00:00   NaN
        2018-01-01 01:00:00   NaN
        Freq: h, dtype: float64
        )_selected_objgroupbyrK   	transform)rj   argr   r   s       rk   r   zResampler.transform  sN    P Gt!))$*;<<F

 
 
 
 
 	
rm   c                     t          |           r   r   )rj   r   r   s      rk   _downsamplezResampler._downsample  r   rm   limit
int | Nonec                     t          |           r   r   )rj   fr   
fill_values       rk   	_upsamplezResampler._upsample  r   rm   ndimintc                    | j         }|| j        }|	||         }n|j        dk    sJ |dk    r|j        dk    sJ t          |d|| j                  }|S )  
        Sub-classes to define. Return a sliced object.

        Parameters
        ----------
        key : string / list of selections
        ndim : {1, 2}
            requested ndim of result
        subset : object, default None
            subset to act on
        N   bygrouperrW   )rI   rO   r   r$   rW   )rj   rh   r   subsetr   groupeds         rk   _gotitemzResampler._gotitem  s~     ->XF {a''''199;!####tW
 
 
 rm   c                   | j         }| j        }t          |d|| j                  }	 t	                    rfd}|                    |          }n |j        gR i }n^# t          t          f$ r  |j        gR i }Y n:t          $ r.}	dt          |	          v rn  |j        gR i }Y d}	~	nd}	~	ww xY w|                     |          S )zA
        Re-evaluate the obj with a groupby aggregation.
        Nr   c                     | gR i S r   r   )xr   r   r   s    rk   <lambda>z2Resampler._groupby_and_aggregate.<locals>.<lambda>#  s!    Q!8!8!8!8!8!8 rm   zMust produce aggregated value)rI   _obj_with_exclusionsr$   rW   callabler   AttributeErrorKeyErrorapplyra   rn   _wrap_result)
rj   r   r   r   r   rO   r   r   r   errs
    ```      rk   r   z Resampler._groupby_and_aggregate  sK    - 'cdGXXX	9}} A 988888 **400**3@@@@@@) 	9 	9 	9 #W]3888888FFF 
	9 
	9 
	9.#c((::  #W]3888888FFFFFF
	9   (((s   =A) )"C	C$B??Cr   r#   c                2    |                      |||           S )zG
        Return the correct class for resampling with groupby.
        )r   rh   parent)_resampler_for_grouping)rj   r   rh   s      rk   _get_resampler_for_groupingz%Resampler._get_resampler_for_grouping?  s*     ++ , 
 
 	
rm   c                   t          |t                    r| j        | j        |_        t          |t                    rL|j        rE| j        }t          |j        dd         | j                  |_        t          |dd          |_        | j
        j        D|j                            | j
        j                  |_        | j        j        j        |j        _        |S )z/
        Potentially wrap any results.
        Nr   rQ   name)
isinstancer   rg   r   emptyrO   _asfreq_compatindexrQ   rr   rK   r   r   )rj   r   rO   s      rk   r   zResampler._wrap_resultN  s     fi(( 	*T_-H/FKfi(( 	5V\ 	5(C)#)BQB-diHHHFL!#vt44FK)5!<..t/@/MNNFL $ 3FLrm   c                0    |                      d|          S )aQ  
        Forward fill the values.

        This method fills missing values by propagating the last valid
        observation forward, up to the next valid observation. It is commonly
        used in time series analysis when resampling data to a higher frequency
        (upsampling) and filling gaps in the resampled output.

        Parameters
        ----------
        limit : int, optional
            Limit of how many values to fill.

        Returns
        -------
        Series
            The resampled data with missing values filled forward.

        See Also
        --------
        Series.fillna: Fill NA/NaN values using the specified method.
        DataFrame.fillna: Fill NA/NaN values using the specified method.

        Examples
        --------
        Here we only create a ``Series``.

        >>> ser = pd.Series(
        ...     [1, 2, 3, 4],
        ...     index=pd.DatetimeIndex(
        ...         ["2023-01-01", "2023-01-15", "2023-02-01", "2023-02-15"]
        ...     ),
        ... )
        >>> ser
        2023-01-01    1
        2023-01-15    2
        2023-02-01    3
        2023-02-15    4
        dtype: int64

        Example for ``ffill`` with downsampling (we have fewer dates after resampling):

        >>> ser.resample("MS").ffill()
        2023-01-01    1
        2023-02-01    3
        Freq: MS, dtype: int64

        Example for ``ffill`` with upsampling (fill the new dates with
        the previous value):

        >>> ser.resample("W").ffill()
        2023-01-01    1
        2023-01-08    1
        2023-01-15    2
        2023-01-22    2
        2023-01-29    2
        2023-02-05    3
        2023-02-12    3
        2023-02-19    4
        Freq: W-SUN, dtype: int64

        With upsampling and limiting (only fill the first new date with the
        previous value):

        >>> ser.resample("W").ffill(limit=1)
        2023-01-01    1.0
        2023-01-08    1.0
        2023-01-15    2.0
        2023-01-22    2.0
        2023-01-29    NaN
        2023-02-05    3.0
        2023-02-12    NaN
        2023-02-19    4.0
        Freq: W-SUN, dtype: float64
        ffillr   r   rj   r   s     rk   r   zResampler.ffilla  s    Z ~~gU~333rm   c                0    |                      d|          S )a&  
        Resample by using the nearest value.

        When resampling data, missing values may appear (e.g., when the
        resampling frequency is higher than the original frequency).
        The `nearest` method will replace ``NaN`` values that appeared in
        the resampled data with the value from the nearest member of the
        sequence, based on the index value.
        Missing values that existed in the original data will not be modified.
        If `limit` is given, fill only this many values in each direction for
        each of the original values.

        Parameters
        ----------
        limit : int, optional
            Limit of how many values to fill.

        Returns
        -------
        Series or DataFrame
            An upsampled Series or DataFrame with ``NaN`` values filled with
            their nearest value.

        See Also
        --------
        bfill : Backward fill the new missing values in the resampled data.
        ffill : Forward fill ``NaN`` values.

        Examples
        --------
        >>> s = pd.Series([1, 2], index=pd.date_range("20180101", periods=2, freq="1h"))
        >>> s
        2018-01-01 00:00:00    1
        2018-01-01 01:00:00    2
        Freq: h, dtype: int64

        >>> s.resample("15min").nearest()
        2018-01-01 00:00:00    1
        2018-01-01 00:15:00    1
        2018-01-01 00:30:00    2
        2018-01-01 00:45:00    2
        2018-01-01 01:00:00    2
        Freq: 15min, dtype: int64

        Limit the number of upsampled values imputed by the nearest:

        >>> s.resample("15min").nearest(limit=1)
        2018-01-01 00:00:00    1.0
        2018-01-01 00:15:00    1.0
        2018-01-01 00:30:00    NaN
        2018-01-01 00:45:00    2.0
        2018-01-01 01:00:00    2.0
        Freq: 15min, dtype: float64
        nearestr   r   r   s     rk   r   zResampler.nearest  s    p ~~iu~555rm   c                0    |                      d|          S )a  
        Backward fill the new missing values in the resampled data.

        In statistics, imputation is the process of replacing missing data with
        substituted values [1]_. When resampling data, missing values may
        appear (e.g., when the resampling frequency is higher than the original
        frequency). The backward fill will replace NaN values that appeared in
        the resampled data with the next value in the original sequence.
        Missing values that existed in the original data will not be modified.

        Parameters
        ----------
        limit : int, optional
            Limit of how many values to fill.

        Returns
        -------
        Series, DataFrame
            An upsampled Series or DataFrame with backward filled NaN values.

        See Also
        --------
        nearest : Fill NaN values with nearest neighbor starting from center.
        ffill : Forward fill NaN values.
        Series.fillna : Fill NaN values in the Series using the
            specified method, which can be 'backfill'.
        DataFrame.fillna : Fill NaN values in the DataFrame using the
            specified method, which can be 'backfill'.

        References
        ----------
        .. [1] https://en.wikipedia.org/wiki/Imputation_%28statistics%29

        Examples
        --------
        Resampling a Series:

        >>> s = pd.Series(
        ...     [1, 2, 3], index=pd.date_range("20180101", periods=3, freq="h")
        ... )
        >>> s
        2018-01-01 00:00:00    1
        2018-01-01 01:00:00    2
        2018-01-01 02:00:00    3
        Freq: h, dtype: int64

        >>> s.resample("30min").bfill()
        2018-01-01 00:00:00    1
        2018-01-01 00:30:00    2
        2018-01-01 01:00:00    2
        2018-01-01 01:30:00    3
        2018-01-01 02:00:00    3
        Freq: 30min, dtype: int64

        >>> s.resample("15min").bfill(limit=2)
        2018-01-01 00:00:00    1.0
        2018-01-01 00:15:00    NaN
        2018-01-01 00:30:00    2.0
        2018-01-01 00:45:00    2.0
        2018-01-01 01:00:00    2.0
        2018-01-01 01:15:00    NaN
        2018-01-01 01:30:00    3.0
        2018-01-01 01:45:00    3.0
        2018-01-01 02:00:00    3.0
        Freq: 15min, dtype: float64

        Resampling a DataFrame that has missing values:

        >>> df = pd.DataFrame(
        ...     {"a": [2, np.nan, 6], "b": [1, 3, 5]},
        ...     index=pd.date_range("20180101", periods=3, freq="h"),
        ... )
        >>> df
                               a  b
        2018-01-01 00:00:00  2.0  1
        2018-01-01 01:00:00  NaN  3
        2018-01-01 02:00:00  6.0  5

        >>> df.resample("30min").bfill()
                               a  b
        2018-01-01 00:00:00  2.0  1
        2018-01-01 00:30:00  NaN  3
        2018-01-01 01:00:00  NaN  3
        2018-01-01 01:30:00  6.0  5
        2018-01-01 02:00:00  6.0  5

        >>> df.resample("15min").bfill(limit=2)
                               a    b
        2018-01-01 00:00:00  2.0  1.0
        2018-01-01 00:15:00  NaN  NaN
        2018-01-01 00:30:00  NaN  3.0
        2018-01-01 00:45:00  NaN  3.0
        2018-01-01 01:00:00  NaN  3.0
        2018-01-01 01:15:00  NaN  NaN
        2018-01-01 01:30:00  6.0  5.0
        2018-01-01 01:45:00  6.0  5.0
        2018-01-01 02:00:00  6.0  5.0
        bfillr   r   r   s     rk   r   zResampler.bfill  s    H ~~gU~333rm   linearr   forward)axisr   limit_direction
limit_areamethodr<   r   r8   r   &Literal['forward', 'backward', 'both']c          
        d|v rdt          j        dt          |           j         dt          t                                 |                    d          }|rt          d          |                     d          }| j	        }	t          |	j        t                    }
|
s|j        }t          |t                    rt          d          |	j                            |          }t!          |          dk    r.t#          ||	j        |         g                                          } |j        d|||d	||d
|}|
r|S |j        |         }||_        |S )a  
        Interpolate values between target timestamps according to different methods.

        The original index is first reindexed to target timestamps
        (see :meth:`core.resample.Resampler.asfreq`),
        then the interpolation of ``NaN`` values via :meth:`DataFrame.interpolate`
        happens.

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

            * 'linear': Ignore the index and treat the values as equally
              spaced. This is the only method supported on MultiIndexes.
            * 'time': Works on daily and higher resolution data to interpolate
              given length of interval.
            * 'index', 'values': use the actual numerical values of the index.
            * 'pad': Fill in NaNs using existing values.
            * 'nearest', 'zero', 'slinear', 'quadratic', 'cubic',
              '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.
        limit_direction : {{'forward', 'backward', 'both'}}, Optional
            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
        -------
        DataFrame or Series
            Interpolated values at the specified freq.

        See Also
        --------
        core.resample.Resampler.asfreq: Return the values at the new freq,
            essentially a reindex.
        DataFrame.interpolate: Fill NaN values using an interpolation method.
        DataFrame.bfill : Backward fill NaN values in the resampled data.
        DataFrame.ffill : Forward fill NaN values.

        Notes
        -----
        For high-frequent or non-equidistant time-series with timestamps
        the reindexing followed by interpolation may lead to information loss
        as shown in the last example.

        Examples
        --------

        >>> start = "2023-03-01T07:00:00"
        >>> timesteps = pd.date_range(start, periods=5, freq="s")
        >>> series = pd.Series(data=[1, -1, 2, 1, 3], index=timesteps)
        >>> series
        2023-03-01 07:00:00    1
        2023-03-01 07:00:01   -1
        2023-03-01 07:00:02    2
        2023-03-01 07:00:03    1
        2023-03-01 07:00:04    3
        Freq: s, dtype: int64

        Downsample the dataframe to 0.5Hz by providing the period time of 2s.

        >>> series.resample("2s").interpolate("linear")
        2023-03-01 07:00:00    1
        2023-03-01 07:00:02    2
        2023-03-01 07:00:04    3
        Freq: 2s, dtype: int64

        Upsample the dataframe to 2Hz by providing the period time of 500ms.

        >>> series.resample("500ms").interpolate("linear")
        2023-03-01 07:00:00.000    1.0
        2023-03-01 07:00:00.500    0.0
        2023-03-01 07:00:01.000   -1.0
        2023-03-01 07:00:01.500    0.5
        2023-03-01 07:00:02.000    2.0
        2023-03-01 07:00:02.500    1.5
        2023-03-01 07:00:03.000    1.0
        2023-03-01 07:00:03.500    2.0
        2023-03-01 07:00:04.000    3.0
        Freq: 500ms, dtype: float64

        Internal reindexing with ``asfreq()`` prior to interpolation leads to
        an interpolated timeseries on the basis of the reindexed timestamps
        (anchors). It is assured that all available datapoints from original
        series become anchors, so it also works for resampling-cases that lead
        to non-aligned timestamps, as in the following example:

        >>> series.resample("400ms").interpolate("linear")
        2023-03-01 07:00:00.000    1.000000
        2023-03-01 07:00:00.400    0.333333
        2023-03-01 07:00:00.800   -0.333333
        2023-03-01 07:00:01.200    0.000000
        2023-03-01 07:00:01.600    1.000000
        2023-03-01 07:00:02.000    2.000000
        2023-03-01 07:00:02.400    1.666667
        2023-03-01 07:00:02.800    1.333333
        2023-03-01 07:00:03.200    1.666667
        2023-03-01 07:00:03.600    2.333333
        2023-03-01 07:00:04.000    3.000000
        Freq: 400ms, dtype: float64

        Note that the series correctly decreases between two anchors
        ``07:00:00`` and ``07:00:02``.
        inplacezThe 'inplace' keyword in zo.interpolate is deprecated and will be removed in a future version. resample(...).interpolate is never inplace.
stacklevelz1Cannot interpolate inplace on a resampled object.asfreqa-  Direct interpolation of MultiIndex data frames is not supported. If you tried to resample and interpolate on a grouped data frame, please use:
`df.groupby(...).apply(lambda x: x.resample(...).interpolate(...))`
instead, as resampling and interpolation has to be performed for each group independently.r   F)r   r   r   r   r   r   r   )warningswarnrx   ry   r   r   popra   r   r   r   r   r+   r'   NotImplementedError
differencer   r/   loc
sort_indexinterpolate)rj   r   r   r   r   r   r   r   r   rO   is_period_indexfinal_indexmissing_data_points_indexresult_interpolateds                 rk   r   zResampler.interpolateP  s   ` M>DJJ,? > > > +--    jj++G V !TUUU))  $SY<<  	 ,K+z22 	)>   ),	(<(<[(I(I%,--11SW%>?@ *,,  1f0 
+!
 
 
 
  	'&& 25kB %0!""rm   c                0    |                      d|          S )a'  
        Return the values at the new freq, essentially a reindex.

        Parameters
        ----------
        fill_value : scalar, optional
            Value to use for missing values, applied during upsampling (note
            this does not fill NaNs that already were present).

        Returns
        -------
        DataFrame or Series
            Values at the specified freq.

        See Also
        --------
        Series.asfreq: Convert TimeSeries to specified frequency.
        DataFrame.asfreq: Convert TimeSeries to specified frequency.

        Examples
        --------

        >>> ser = pd.Series(
        ...     [1, 2, 3, 4],
        ...     index=pd.DatetimeIndex(
        ...         ["2023-01-01", "2023-01-31", "2023-02-01", "2023-02-28"]
        ...     ),
        ... )
        >>> ser
        2023-01-01    1
        2023-01-31    2
        2023-02-01    3
        2023-02-28    4
        dtype: int64
        >>> ser.resample("MS").asfreq()
        2023-01-01    1
        2023-02-01    3
        Freq: MS, dtype: int64
        r   )r   r   )rj   r   s     rk   r   zResampler.asfreq   s    R ~~h:~>>>rm   numeric_only	min_countc                2    |                      d||          S )aq  
        Compute sum of group values.

        This method provides a simple way to compute the sum of values within each
        resampled group, particularly useful for aggregating time-based data into
        daily, monthly, or yearly sums.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns.

            .. versionchanged:: 2.0.0

                numeric_only no longer accepts ``None``.

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

        Returns
        -------
        Series or DataFrame
            Computed sum of values within each group.

        See Also
        --------
        core.resample.Resampler.mean : Compute mean of groups, excluding missing values.
        core.resample.Resampler.count : Compute count of group, excluding missing
            values.
        DataFrame.resample : Resample time-series data.
        Series.sum : Return the sum of the values over the requested axis.

        Examples
        --------
        >>> ser = pd.Series(
        ...     [1, 2, 3, 4],
        ...     index=pd.DatetimeIndex(
        ...         ["2023-01-01", "2023-01-15", "2023-02-01", "2023-02-15"]
        ...     ),
        ... )
        >>> ser
        2023-01-01    1
        2023-01-15    2
        2023-02-01    3
        2023-02-15    4
        dtype: int64
        >>> ser.resample("MS").sum()
        2023-01-01    3
        2023-02-01    7
        Freq: MS, dtype: int64
        sumr   r   r   rj   r   r   s      rk   r   zResampler.sumK  s     t LIVVVrm   c                2    |                      d||          S )a}  
        Compute prod of group values.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns.

            .. versionchanged:: 2.0.0

                numeric_only no longer accepts ``None``.

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

        Returns
        -------
        Series or DataFrame
            Computed prod of values within each group.

        See Also
        --------
        core.resample.Resampler.sum : Compute sum of groups, excluding missing values.
        core.resample.Resampler.mean : Compute mean of groups, excluding missing values.
        core.resample.Resampler.median : Compute median of groups, excluding missing
            values.

        Examples
        --------
        >>> ser = pd.Series(
        ...     [1, 2, 3, 4],
        ...     index=pd.DatetimeIndex(
        ...         ["2023-01-01", "2023-01-15", "2023-02-01", "2023-02-15"]
        ...     ),
        ... )
        >>> ser
        2023-01-01    1
        2023-01-15    2
        2023-02-01    3
        2023-02-15    4
        dtype: int64
        >>> ser.resample("MS").prod()
        2023-01-01    2
        2023-02-01   12
        Freq: MS, dtype: int64
        prodr  r  r  s      rk   r  zResampler.prod  s     j \YWWWrm   c                2    |                      d||          S )av  
        Compute min value of group.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns.

            .. versionchanged:: 2.0.0

                numeric_only no longer accepts ``None``.

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

        Returns
        -------
        Series or DataFrame
            Compute the minimum value in the given Series or DataFrame.

        See Also
        --------
        core.resample.Resampler.max : Compute max value of group.
        core.resample.Resampler.mean : Compute mean of groups, excluding missing values.
        core.resample.Resampler.median : Compute median of groups, excluding missing
            values.

        Examples
        --------
        >>> ser = pd.Series(
        ...     [1, 2, 3, 4],
        ...     index=pd.DatetimeIndex(
        ...         ["2023-01-01", "2023-01-15", "2023-02-01", "2023-02-15"]
        ...     ),
        ... )
        >>> ser
        2023-01-01    1
        2023-01-15    2
        2023-02-01    3
        2023-02-15    4
        dtype: int64
        >>> ser.resample("MS").min()
        2023-01-01    1
        2023-02-01    3
        Freq: MS, dtype: int64
        minr  r  r  s      rk   r  zResampler.min       j LIVVVrm   c                2    |                      d||          S )aw  
        Compute max value of group.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns.

            .. versionchanged:: 2.0.0

                numeric_only no longer accepts ``None``.

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

        Returns
        -------
        Series or DataFrame
            Computes the maximum value in the given Series or Dataframe.

        See Also
        --------
        core.resample.Resampler.min : Compute min value of group.
        core.resample.Resampler.mean : Compute mean of groups, excluding missing values.
        core.resample.Resampler.median : Compute median of groups, excluding missing
            values.

        Examples
        --------
        >>> ser = pd.Series(
        ...     [1, 2, 3, 4],
        ...     index=pd.DatetimeIndex(
        ...         ["2023-01-01", "2023-01-15", "2023-02-01", "2023-02-15"]
        ...     ),
        ... )
        >>> ser
        2023-01-01    1
        2023-01-15    2
        2023-02-01    3
        2023-02-15    4
        dtype: int64
        >>> ser.resample("MS").max()
        2023-01-01    2
        2023-02-01    4
        Freq: MS, dtype: int64
        maxr  r  r  s      rk   r
  zResampler.max  r  rm   Tskipnac                4    |                      d|||          S )a-  
        Compute the first non-null entry of each column.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns.
        min_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.
        skipna : bool, default True
            Exclude NA/null values. If an entire group is NA, the result will be NA.

        Returns
        -------
        Series or DataFrame
            First values within each group.

        See Also
        --------
        core.resample.Resampler.last : Compute the last non-null value in each group.
        core.resample.Resampler.mean : Compute mean of groups, excluding missing values.

        Examples
        --------
        >>> s = pd.Series(
        ...     [1, 2, 3, 4],
        ...     index=pd.DatetimeIndex(
        ...         ["2023-01-01", "2023-01-15", "2023-02-01", "2023-02-15"]
        ...     ),
        ... )
        >>> s
        2023-01-01    1
        2023-01-15    2
        2023-02-01    3
        2023-02-15    4
        dtype: int64
        >>> s.resample("MS").first()
        2023-01-01    1
        2023-02-01    3
        Freq: MS, dtype: int64
        firstr   r   r  r  rj   r   r   r  s       rk   r  zResampler.first,  s+    b ,)F   
 
 	
rm   c                4    |                      d|||          S )a/  
        Compute the last non-null entry of each column.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns.
        min_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.
        skipna : bool, default True
            Exclude NA/null values. If an entire group is NA, the result will be NA.

        Returns
        -------
        Series or DataFrame
            Last of values within each group.

        See Also
        --------
        core.resample.Resampler.first : Compute the first non-null value in each group.
        core.resample.Resampler.mean : Compute mean of groups, excluding missing values.

        Examples
        --------
        >>> s = pd.Series(
        ...     [1, 2, 3, 4],
        ...     index=pd.DatetimeIndex(
        ...         ["2023-01-01", "2023-01-15", "2023-02-01", "2023-02-15"]
        ...     ),
        ... )
        >>> s
        2023-01-01    1
        2023-01-15    2
        2023-02-01    3
        2023-02-15    4
        dtype: int64
        >>> s.resample("MS").last()
        2023-01-01    2
        2023-02-01    4
        Freq: MS, dtype: int64
        lastr  r  r  s       rk   r  zResampler.lasta  s+    b 6   
 
 	
rm   c                0    |                      d|          S )a  
        Compute median of groups, excluding missing values.

        For multiple groupings, the result index will be a MultiIndex

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns.

            .. versionchanged:: 2.0.0

                numeric_only no longer accepts ``None`` and defaults to False.

        Returns
        -------
        Series or DataFrame
            Median of values within each group.

        See Also
        --------
        Series.groupby : Apply a function groupby to a Series.
        DataFrame.groupby : Apply a function groupby to each row or column of a
            DataFrame.

        Examples
        --------

        >>> ser = pd.Series(
        ...     [1, 2, 3, 3, 4, 5],
        ...     index=pd.DatetimeIndex(
        ...         [
        ...             "2023-01-01",
        ...             "2023-01-10",
        ...             "2023-01-15",
        ...             "2023-02-01",
        ...             "2023-02-10",
        ...             "2023-02-15",
        ...         ]
        ...     ),
        ... )
        >>> ser.resample("MS").median()
        2023-01-01    2.0
        2023-02-01    4.0
        Freq: MS, dtype: float64
        medianr   r  rj   r   s     rk   r  zResampler.median  s    ` |DDDrm   c                0    |                      d|          S )aM  
        Compute mean of groups, excluding missing values.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only `float`, `int` or `boolean` data.

            .. versionchanged:: 2.0.0

                numeric_only now defaults to ``False``.

        Returns
        -------
        DataFrame or Series
            Mean of values within each group.

        See Also
        --------
        core.resample.Resampler.median : Compute median of groups, excluding missing
            values.
        core.resample.Resampler.sum : Compute sum of groups, excluding missing values.
        core.resample.Resampler.std : Compute standard deviation of groups, excluding
            missing values.
        core.resample.Resampler.var : Compute variance of groups, excluding missing
            values.

        Examples
        --------

        >>> ser = pd.Series(
        ...     [1, 2, 3, 4],
        ...     index=pd.DatetimeIndex(
        ...         ["2023-01-01", "2023-01-15", "2023-02-01", "2023-02-15"]
        ...     ),
        ... )
        >>> ser
        2023-01-01    1
        2023-01-15    2
        2023-02-01    3
        2023-02-15    4
        dtype: int64
        >>> ser.resample("MS").mean()
        2023-01-01    1.5
        2023-02-01    3.5
        Freq: MS, dtype: float64
        meanr  r  r  s     rk   r  zResampler.mean  s    h \BBBrm   r   ddofc                2    |                      d||          S )a  
        Compute standard deviation of groups, excluding missing values.

        Parameters
        ----------
        ddof : int, default 1
            Degrees of freedom.
        numeric_only : bool, default False
            Include only `float`, `int` or `boolean` data.

            .. versionchanged:: 2.0.0

                numeric_only now defaults to ``False``.

        Returns
        -------
        DataFrame or Series
            Standard deviation of values within each group.

        See Also
        --------
        core.resample.Resampler.mean : Compute mean of groups, excluding missing values.
        core.resample.Resampler.median : Compute median of groups, excluding missing
            values.
        core.resample.Resampler.var : Compute variance of groups, excluding missing
            values.

        Examples
        --------

        >>> ser = pd.Series(
        ...     [1, 3, 2, 4, 3, 8],
        ...     index=pd.DatetimeIndex(
        ...         [
        ...             "2023-01-01",
        ...             "2023-01-10",
        ...             "2023-01-15",
        ...             "2023-02-01",
        ...             "2023-02-10",
        ...             "2023-02-15",
        ...         ]
        ...     ),
        ... )
        >>> ser.resample("MS").std()
        2023-01-01    1.000000
        2023-02-01    2.645751
        Freq: MS, dtype: float64
        stdr  r   r  rj   r  r   s      rk   r  zResampler.std       l D|LLLrm   c                2    |                      d||          S )a  
        Compute variance of groups, excluding missing values.

        Parameters
        ----------
        ddof : int, default 1
            Degrees of freedom.

        numeric_only : bool, default False
            Include only `float`, `int` or `boolean` data.

            .. versionchanged:: 2.0.0

                numeric_only now defaults to ``False``.

        Returns
        -------
        DataFrame or Series
            Variance of values within each group.

        See Also
        --------
        core.resample.Resampler.std : Compute standard deviation of groups, excluding
            missing values.
        core.resample.Resampler.mean : Compute mean of groups, excluding missing values.
        core.resample.Resampler.median : Compute median of groups, excluding missing
            values.

        Examples
        --------

        >>> ser = pd.Series(
        ...     [1, 3, 2, 4, 3, 8],
        ...     index=pd.DatetimeIndex(
        ...         [
        ...             "2023-01-01",
        ...             "2023-01-10",
        ...             "2023-01-15",
        ...             "2023-02-01",
        ...             "2023-02-10",
        ...             "2023-02-15",
        ...         ]
        ...     ),
        ... )
        >>> ser.resample("MS").var()
        2023-01-01    1.0
        2023-02-01    7.0
        Freq: MS, dtype: float64

        >>> ser.resample("MS").var(ddof=0)
        2023-01-01    0.666667
        2023-02-01    4.666667
        Freq: MS, dtype: float64
        varr  r  r  s      rk   r  zResampler.var6  s     x D|LLLrm   c                2    |                      d||          S )a`  
        Compute standard error of the mean of groups, excluding missing values.

        For multiple groupings, the result index will be a MultiIndex.

        Parameters
        ----------
        ddof : int, default 1
            Degrees of freedom.

        numeric_only : bool, default False
            Include only `float`, `int` or `boolean` data.

            .. versionchanged:: 2.0.0

                numeric_only now defaults to ``False``.

        Returns
        -------
        Series or DataFrame
            Standard error of the mean of values within each group.

        See Also
        --------
        DataFrame.sem : Return unbiased standard error of the mean over requested axis.
        Series.sem : Return unbiased standard error of the mean over requested axis.

        Examples
        --------

        >>> ser = pd.Series(
        ...     [1, 3, 2, 4, 3, 8],
        ...     index=pd.DatetimeIndex(
        ...         [
        ...             "2023-01-01",
        ...             "2023-01-10",
        ...             "2023-01-15",
        ...             "2023-02-01",
        ...             "2023-02-10",
        ...             "2023-02-15",
        ...         ]
        ...     ),
        ... )
        >>> ser.resample("MS").sem()
        2023-01-01    0.577350
        2023-02-01    1.527525
        Freq: MS, dtype: float64
        semr  r  r  s      rk   r!  zResampler.semt  r  rm   c                   | j         }| j        }t          |          dk    r|                                }t	          |j        | j                  |_        |j        dk    r.|                                }|	                    g dd          }n4t          j        |j        g dg          }|	                    |d          }|S |                     d          S )a@  
        Compute open, high, low and close values of a group, excluding missing values.

        Returns
        -------
        DataFrame
            Open, high, low and close values within each group.

        See Also
        --------
        DataFrame.agg : Aggregate using one or more operations over the specified axis.
        DataFrame.resample : Resample time-series data.
        DataFrame.groupby : Group DataFrame using a mapper or by a Series of columns.

        Examples
        --------
        >>> ser = pd.Series(
        ...     [1, 3, 2, 4, 3, 5],
        ...     index=pd.DatetimeIndex(
        ...         [
        ...             "2023-01-01",
        ...             "2023-01-10",
        ...             "2023-01-15",
        ...             "2023-02-01",
        ...             "2023-02-10",
        ...             "2023-02-15",
        ...         ]
        ...     ),
        ... )
        >>> ser.resample("MS").ohlc()
                    open  high  low  close
        2023-01-01     1     3    1      2
        2023-02-01     4     5    3      5
        r   r   )openhighlowclose)r   ohlc)rN   r   r   copyr   r   rQ   r   to_framereindexr'   from_productcolumnsr   )rj   rN   rO   mis       rk   r'  zResampler.ohlc  s    H W'r77a<<((**C&sy$)<<CIx1}}llnnkk"B"B"BkKK,["B"B"BC  kk"1k--J'''rm   c                ,    |                      d          S )a
  
        Return number of unique elements in the group.

        Returns
        -------
        Series
            Number of unique values within each group.

        See Also
        --------
        core.groupby.SeriesGroupBy.nunique : Method nunique for SeriesGroupBy.

        Examples
        --------
        >>> ser = pd.Series(
        ...     [1, 2, 3, 3],
        ...     index=pd.DatetimeIndex(
        ...         ["2023-01-01", "2023-01-15", "2023-02-01", "2023-02-15"]
        ...     ),
        ... )
        >>> ser
        2023-01-01    1
        2023-01-15    2
        2023-02-01    3
        2023-02-15    3
        dtype: int64
        >>> ser.resample("MS").nunique()
        2023-01-01    2
        2023-02-01    1
        Freq: MS, dtype: int64
        nuniquer  r   s    rk   r/  zResampler.nunique  s    B 	***rm   c                *   |                      d          }t          |t                    r|j        s|                                }t          | j                  s9ddlm} | j	        j
        dk    r| j	        j        }nd} |g |j        d|          }|S )a  
        Compute group sizes.

        Returns
        -------
        Series
            Number of rows in each group.

        See Also
        --------
        Series.groupby : Apply a function groupby to a Series.
        DataFrame.groupby : Apply a function groupby to each row
            or column of a DataFrame.

        Examples
        --------
        >>> ser = pd.Series(
        ...     [1, 2, 3],
        ...     index=pd.DatetimeIndex(["2023-01-01", "2023-01-15", "2023-02-01"]),
        ... )
        >>> ser
        2023-01-01    1
        2023-01-15    2
        2023-02-01    3
        dtype: int64
        >>> ser.resample("MS").size()
        2023-01-01    2
        2023-02-01    1
        Freq: MS, dtype: int64
        sizer   )rE   r   Nint64r   dtyper   )r   r   r   r   stackr   rN   pandasrE   r   r   r   r   )rj   r   rE   r   s       rk   r1  zResampler.size  s    @ !!&)) fl++ 	$FL 	$\\^^F47|| 	N%%%%%%!&!++).VBfl'MMMFrm   c                   |                      d          }t          | j                  s`| j        j        dk    r1 t          | j                  g |j        d| j        j                  }nddlm	}  |g |j        |j
        d          }|S )ag  
        Compute count of group, excluding missing values.

        Returns
        -------
        Series or DataFrame
            Count of values within each group.

        See Also
        --------
        Series.groupby : Apply a function groupby to a Series.
        DataFrame.groupby : Apply a function groupby to each row
            or column of a DataFrame.

        Examples
        --------
        >>> ser = pd.Series(
        ...     [1, 2, 3, 4],
        ...     index=pd.DatetimeIndex(
        ...         ["2023-01-01", "2023-01-15", "2023-02-01", "2023-02-15"]
        ...     ),
        ... )
        >>> ser
        2023-01-01    1
        2023-01-15    2
        2023-02-01    3
        2023-02-15    4
        dtype: int64
        >>> ser.resample("MS").count()
        2023-01-01    2
        2023-02-01    2
        Freq: MS, dtype: int64
        countr   r2  r3  r   )rD   )r   r,  r4  )r   r   rN   r   r   rx   r   r   r6  rD   r,  )rj   r   rD   s      rk   r8  zResampler.count6  s    F !!'**47|| 
	!&!++1d011fl'@R@W   -,,,,,"flFN'   rm         ?q"float | list[float] | AnyArrayLikec                      | j         dd|i|S )ac  
        Return value at the given quantile.

        Computes the quantile of values within each resampled group.

        Parameters
        ----------
        q : float or array-like, default 0.5 (50% quantile)
            Value between 0 <= q <= 1, the quantile(s) to compute.
        **kwargs
            Additional keyword arguments to be passed to the function.

        Returns
        -------
        DataFrame or Series
            Quantile of values within each group.

        See Also
        --------
        Series.quantile
            Return a series, where the index is q and the values are the quantiles.
        DataFrame.quantile
            Return a DataFrame, where the columns are the columns of self,
            and the values are the quantiles.
        DataFrameGroupBy.quantile
            Return a DataFrame, where the columns are groupby columns,
            and the values are its quantiles.

        Examples
        --------

        >>> ser = pd.Series(
        ...     [1, 3, 2, 4, 3, 8],
        ...     index=pd.DatetimeIndex(
        ...         [
        ...             "2023-01-01",
        ...             "2023-01-10",
        ...             "2023-01-15",
        ...             "2023-02-01",
        ...             "2023-02-10",
        ...             "2023-02-15",
        ...         ]
        ...     ),
        ... )
        >>> ser.resample("MS").quantile()
        2023-01-01    2.0
        2023-02-01    4.0
        Freq: MS, dtype: float64

        >>> ser.resample("MS").quantile(0.25)
        2023-01-01    1.5
        2023-02-01    3.5
        Freq: MS, dtype: float64
        quantiler:  )r=  r  )rj   r:  r   s      rk   r=  zResampler.quantileh  s#    p  t::a:6:::rm   )rO   r!   rZ   rJ   r[   r(   rW   r\   rY   r\   r]   r^   )r]   rn   )r}   rn   )r]   r\   rO   r   r]   r   )r   r   r   r   r   r   r]   r>   )r   r   r   r6   r   r6   r]   r>   )r   r   r   r6   r   r6   r]   r>   r   NNr   r   )r   r   )r   r#   )r   )r   r<   r   r8   r   r   r   r   )Fr   )r   r\   r   r   )Fr   T)r   r\   r   r   r  r\   F)r   r\   )r   F)r  r   r   r\   )r9  )r:  r;  )5ry   
__module____qualname____doc____annotations__ri   rM   setr   rw   rl   r	   r|   r   propertyr   re   r   rf   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/  r1  r8  r=  __classcell__r   s   @rk   rH   rH   w   s;         ( 8888&/ikkJ1111#77788  K !$* * * * * *8 	= 	= 	= U	= 3 3 3 U3 
 
 
 X U
" " " "( ( ( 
# 
# U
#    X    X L3 L3 L3 L3 L3 UL3\ g g g UgR CE
)
 )
 U)
V( ( (( ( ( ( (    8)) )) ))V 
 
 
 U
  & L4 L4 L4 L4 UL4\ 76 76 76 76 U76r c4 c4 c4 c4 Uc4J  &.M#  BKM# M# M# M# M# UM#^ (? (? (? U(?T  #9W 9W 9W 9W U9Wv  #4X 4X 4X 4X U4Xl  #4W 4W 4W 4W U4Wl  #4W 4W 4W 4W U4Wl  #	2
 2
 2
 2
 U2
h  #	2
 2
 2
 2
 U2
h /E /E /E /E U/Eb  #3C 3C 3C 3C U3Cj  "5M 5M 5M 5M U5Mn  ";M ;M ;M ;M U;Mz  "5M 5M 5M 5M U5Mn 3( 3( U3(j  +  + U +D . . U.` / / U/b 7; 7; 7; 7; U7; 7; 7; 7; 7;rm   rH   c                      e Zd ZU dZded<   dZded<   ded<   d	ed
<   dddddZed             ZeZ	eZ
eZedd            ZdS )_GroupByMixinz)
    Provide the groupby facilities.
    z	list[str]rw   NIndexLabel | Nonerg   r#   _groupbyrJ   rK   )rh   rX   r   rH   r   rX   r]   r^   c          	        t          |t                    sJ t          |                      t          |t                    sJ t          |                      | j        D ]!}t          | |t          ||                     "|| _        |j        | _        || _	        || _
        t          j        |j                  | _        |j        | _        |j        | _        d S r   )r   r#   rx   rH   rw   setattrrr   rg   rL   rh   rM  r(  rK   rN   rO   )rj   r   r   rh   rX   r}   s         rk   rl   z_GroupByMixin.__init__  s     '7++::T']]::+ &),,::d6ll::, $ 	7 	7DD$ 5 56666#m If&9::):rm   c                v     fd} j                             |          }t          |t                    rjt	          |          dk    rWt          |j        t                    s=|                    t           j	        j        dd          j
                  d          }                     |          S )z
        Dispatch to _upsample; we are stripping all of the _upsample kwargs and
        performing the original function call on the grouped object.
        c                                         | j        j                  } t          t                    r t          |           di S  | j        gR i S )N)rZ   r[   r   )_resampler_clsrK   rN   r   rn   rr   r   )r   r   r   r   rj   s    rk   r   z"_GroupByMixin._apply.<locals>.func  sv    ##A43DPTPW#XXA!S!! /$wq!}}..v...171.t...v...rm   r   Nr   T)append)rM  r   r   r   r   r   r+   	set_indexr   rO   rQ   r   )rj   r   r   r   r   r   s   ````  rk   _applyz_GroupByMixin._apply  s    	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ $$T** v|,,	Fq  v|[99 ! %%tx~bqb1	BBB4 &  F   (((rm   c                   || j         }|	||         }n|j        dk    sJ 	 t          |t                    r*| j        |vr!| j        |                    | j                   | j        |         }n# t          $ r
 | j        }Y nw xY w|                     ||          } t          |           |t          t          |           |          }|S )r   Nr   )r   r   rX   )rO   r   r   listrh   rS  rM  
IndexError_infer_selectionrx   r   rH   )rj   rh   r   r   r   rX   new_rss          rk   r   z_GroupByMixin._gotitem  s     >XF {a''''	$#t$$ %)<)<AU

48$$$mC(GG 	$ 	$ 	$mGGG	$ ))#v66	d	4((
 
 

 s   AA0 0BB)r   rH   r   r#   rX   rL  r]   r^   r   )ry   rB  rC  rD  rE  rg   rl   r
   rU  r   r   r   r	   r   r   rm   rk   rK  rK    s           $(J(((( '+     < ) ) ])8 IK#
$ $ $ U$ $ $rm   rK  c                  ^     e Zd ZU ded<   edd            Zd Zd Zd ZdddZ	 fdZ
 xZS )DatetimeIndexResamplerr)   rN   r]   #type[DatetimeIndexResamplerGroupby]c                    t           S r   )DatetimeIndexResamplerGroupbyr   s    rk   r   z.DatetimeIndexResampler._resampler_for_grouping  s    ,,rm   c                @    | j                             | j                  S r   )rK   _get_time_binsrN   r   s    rk   r   z+DatetimeIndexResampler._get_binner_for_time  s     //888rm   c                   | j         }| j        }t          |          sj|                                }|j                            | j                  |_        |j        j        | j        k    sJ |j        j        | j        f            |S  |                    | j                  j	        |fi |}| 
                    |          S )
        Downsample the cython defined function.

        Parameters
        ----------
        how : string / cython mapped function
        **kwargs : kw args passed to how function
        )rN   r   r   r(  r   
_with_freqrQ   r   rI   r   r   )rj   r   r   rN   rO   r   s         rk   r   z"DatetimeIndexResampler._downsample  s     W '2ww 	((**C	,,TY77CI9>TY...0K...J 6T]++5cDDVDD  (((rm   c                F    | j         dk    r|dd         }n
|dd         }|S )z|
        Adjust our binner when upsampling.

        The range of a new index should not be outside specified range
        rightr   N)rR   rj   rL   s     rk   _adjust_binner_for_upsamplez2DatetimeIndexResampler._adjust_binner_for_upsample9  s2     ;'!!ABBZFFCRC[Frm   Nr   r   c                   | j         rt          d          | j        }| j        }| j        }|                     |          }|st          |j                  | j        k    rVt          |          t          |          k    r6|j
                            |          r|                                }||_
        n!|dk    rd}|                    ||||          }|                     |          S )aF  
        Parameters
        ----------
        method : string {'backfill', 'bfill', 'pad',
            'ffill', 'asfreq'} method for upsampling
        limit : int, default None
            Maximum size gap to fill when reindexing
        fill_value : scalar, default None
            Value to use for missing values
        zvUpsampling from level= or on= selection is not supported, use .set_index(...) to explicitly set index to datetime-likeNr   )r   r   r   )r   ra   rN   r   rL   ri  r   inferred_freqrQ   r   r   equalsr(  r*  r   )	rj   r   r   r   rN   rO   rL   	res_indexr   s	            rk   r   z DatetimeIndexResampler._upsampleE  s      	;   W 44V<<	 M"*++ty88CC	NN**	  ++ + XXZZF$FLL!![[&* !  F   (((rm   c                   t                                          |          }t          | j        t                    rt          |j        t                    st          |j        t                    rqt          |j        j        d         t                    sK|j        j        d                             | j	                  }|j        
                    |d          |_        n$|j                            | j	                  |_        |S )Nrg  )r   )r   r   r   rN   r+   r   r'   levels	to_periodrQ   
set_levels)rj   r   	new_levelr   s      rk   r   z#DatetimeIndexResampler._wrap_resultn  s    %%f-- dg{++ 		AJL+5
 5
 		A &,
33 A!&,"5b"9;GG P & 3B 7 A A$) L LI#)<#:#:9B#:#O#OFL%|55di@@rm   )r]   r]  r?  r@  )ry   rB  rC  rE  rG  r   r   r   ri  r   r   rH  rI  s   @rk   r\  r\    s         - - - X-9 9 9) ) )4
 
 
') ') ') ') ')R        rm   r\  c                  (    e Zd ZdZed             ZdS )r_  z9
    Provides a resample of a groupby implementation
    c                    t           S r   )r\  r   s    rk   rR  z,DatetimeIndexResamplerGroupby._resampler_cls  s    %%rm   Nry   rB  rC  rD  rG  rR  r   rm   rk   r_  r_    s9          & & X& & &rm   r_  c                  X     e Zd ZU ded<   ed             Zd Zd fdZd	 ZdddZ	 xZ
S )PeriodIndexResamplerr+   rN   c                    t           S r   )PeriodIndexResamplerGroupbyr   s    rk   r   z,PeriodIndexResampler._resampler_for_grouping  s    **rm   c                @    | j                             | j                  S r   )rK   _get_period_binsrN   r   s    rk   r   z)PeriodIndexResampler._get_binner_for_time  s     11$':::rm   rO   r   r]   c                z    t                                          |          }| j        rd}t          |          |S )NzResampling from level= or on= selection with a PeriodIndex is not currently supported, use .set_index(...) to explicitly set index)r   re   r   r   )rj   rO   msgr   s      rk   re   z!PeriodIndexResampler._convert_obj  sD    gg""3'' 	+> 
 &c***
rm   c                z   | j         }t          |j        | j                  r | j        |fi |S t	          |j        | j                  r/|dk    r|                     |          S |                                 S |j        | j        k    r|                                 S t          d|j         d| j         d          )rc  r'  z
Frequency z cannot be resampled to z&, as they are not sub or super periods)rN   r0   rQ   r   r1   r   r   )rj   r   r   rN   s       rk   r   z PeriodIndexResampler._downsample  s     W++ 	!.4.s==f===BGTY// 
	!f}} 223777;;== W	!!;;== #3 3 3$) 3 3 3
 
 	
rm   Nr   r   c                    | j         }| j        }| j        }|                    | j        | j                  }|dk    rd}|                    |||          }t          |||          }	|                     |	          S )a8  
        Parameters
        ----------
        method : {'backfill', 'bfill', 'pad', 'ffill'}
            Method for upsampling.
        limit : int, default None
            Maximum size gap to fill when reindexing.
        fill_value : scalar, default None
            Value to use for missing values.
        r   r   N)r   r   )	rN   rO   rL   r   rQ   rT   get_indexer_take_new_indexr   )
rj   r   r   r   rN   rO   	new_indexmembr   new_objs
             rk   r   zPeriodIndexResampler._upsample  s     WhK	 yyy88 XF""9V5"II!
 

   )))rm   r>  r?  r@  )ry   rB  rC  rE  rG  r   r   re   r   r   rH  rI  s   @rk   rw  rw    s          OOO+ + X+; ; ;     
 
 
>* * * * * * * * *rm   rw  c                  (    e Zd ZdZed             ZdS )ry  :
    Provides a resample of a groupby implementation.
    c                    t           S r   )rw  r   s    rk   rR  z*PeriodIndexResamplerGroupby._resampler_cls  s    ##rm   Nru  r   rm   rk   ry  ry    s9          $ $ X$ $ $rm   ry  c                  <    e Zd ZU ded<   ed             Zd Zd ZdS )TimedeltaIndexResamplerr-   rN   c                    t           S r   )TimedeltaIndexResamplerGroupbyr   s    rk   r   z/TimedeltaIndexResampler._resampler_for_grouping  s    --rm   c                @    | j                             | j                  S r   )rK   _get_time_delta_binsrN   r   s    rk   r   z,TimedeltaIndexResampler._get_binner_for_time  s     55dg>>>rm   c                    |S )z
        Adjust our binner when upsampling.

        The range of a new index is allowed to be greater than original range
        so we don't need to change the length of a binner, GH 13022
        r   rh  s     rk   ri  z3TimedeltaIndexResampler._adjust_binner_for_upsample	  s	     rm   N)ry   rB  rC  rE  rG  r   r   ri  r   rm   rk   r  r    s[          . . X.? ? ?    rm   r  c                  (    e Zd ZdZed             ZdS )r  r  c                    t           S r   )r  r   s    rk   rR  z-TimedeltaIndexResamplerGroupby._resampler_cls	  s    &&rm   Nru  r   rm   rk   r  r  	  s9          ' ' X' ' 'rm   r  rO   Series | DataFramer]   c                F    t          | fi |}|                    |           S )z8
    Create a TimeGrouper and return our resampler.
    )rJ   _get_resampler)rO   kwdstgs      rk   get_resamplerr  	  s-     
S	!	!D	!	!BS!!!rm   r   r#   r   r   c                    t          d||d|}|                    | j                  }|                    | |j                  S )zA
    Return our appropriate resampler when grouping as well.
    rQ   rh   )r   rh   r   )rJ   r  rO   r   rh   )	r   ruler   fill_methodr   onr   r  	resamplers	            rk   get_resampler_for_groupingr  %	  sN     
	1$B	1	1&	1	1B!!'+..I00bf0MMMrm   c                       e Zd ZU dZg ej        ddddddR Zded<   	 	 	 	 	 	 	 	 	 	 	 	 d<d= fdZd>d"Z	 d?d@d(Z	dAd+Z
dBd0ZdCd2ZdAd3ZdDd5Z	 dEd	d6dF fd;Z xZS )GrJ   ah  
    Custom groupby class for time-interval grouping.

    Parameters
    ----------
    freq : pandas date offset or offset alias for identifying bin edges
    closed : closed end of interval; 'left' or 'right'
    label : interval boundary to use for labeling; 'left' or 'right'
    convention : {'start', 'end', 'e', 's'}
        If axis is PeriodIndex
    rR   rS   r   rT   rU   rV   r@   NMinr  	start_dayFrO   Grouper | NonerQ   r:   rh   
str | NoneLiteral['left', 'right'] | Nonern   r   r   (Literal['start', 'end', 'e', 's'] | NoneTLiteral['epoch', 'start', 'start_day', 'end', 'end_day'] | TimestampConvertibleTypes TimedeltaConvertibleTypes | NonerW   r\   r]   r^   c                   |dvrt          d| d          |dvrt          d| d          |	dvrt          d|	 d          ||t          |j        t                    s|/|-t	          ||         dd           dk    rt          |d	
          }nt          |          }t          |t                    sX|(t          j        dt          t                                 |
dk    r(t          j        dt          t                                 h d}|j        }||v s#d|v r(|d |                    d                   |v r	|d}|d}n|
dv r	|d}|d}n|d}|d}|| _        || _        |	|	nd| _        || _        || _        || _        || _        d | _        |
dv r|
| _        nC	 t-          |
          | _        n-# t           t.          f$ r}t          d|
 d          |d }~ww xY w	 |t1          |          nd | _        n-# t           t.          f$ r}t          d| d          |d }~ww xY wd	|d<    t5                      j        d||d| d S )N>   Nleftrf  zUnsupported value z for `label`z for `closed`>   Nesendstartz for `convention`r4  periodT)	is_periodzsThe 'offset' keyword does not take effect when resampling with a 'freq' that is not Tick-like (h, m, s, ms, us, ns)r   r  zsThe 'origin' keyword does not take effect when resampling with a 'freq' that is not Tick-like (h, m, s, ms, us, ns)>   WMEQEYEBMEBQEBYE-rf  r  end_dayr  r  )epochr  r  r  r  z|'origin' should be equal to 'epoch', 'start', 'start_day', 'end', 'end_day' or should be a Timestamp convertible type. Got 'z
' instead.z6'offset' should be a Timedelta convertible type. Got 'r`   r  r   )ra   r   r   r+   rr   r   r3   r   r   RuntimeWarningr   	rule_codefindrR   rS   rT   r   r  r   rW   r   rU   r   	TypeErrorr   rV   r   rl   )rj   rO   rQ   rh   rR   rS   r   r  r   rT   rU   rV   rW   r   	end_typesr  r   r   s                    rk   rl   zTimeGrouper.__init__Q	  sO   * ///E%EEEFFF000G&GGGHHH===O*OOOPPPKCO
39k0R0ROOC'400H<<TT222DDT??D$%% 	!P"/11	    $$P"/11	    A@@	~96F		#6F1G91T1T~ } )))~ }~}
(2(>**C&
$/3FFF !DKK'//	*    WDJW W W  		/5/A)F+++tDKKI& 	 	 	++ + +  	 v6d66v66666s0   +G   G*G%%G*.H H1H,,H1r!   rH   c                   |                      |d          \  }}}t          |t                    rt          || | j        |          S t          |t
                    rt          || | j        |          S t          |t                    rt          || | j        |          S t          dt          |          j         d          )a  
        Return my resampler or raise if we have an invalid axis.

        Parameters
        ----------
        obj : Series or DataFrame

        Returns
        -------
        Resampler

        Raises
        ------
        TypeError if incompatible axis

        Nr[   )rZ   rW   r[   zVOnly valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of '')rd   r   r)   r\  rW   r+   rw  r-   r  r  rx   ry   )rj   rO   _rN   s       rk   r  zTimeGrouper._get_resampler	  s    " $$SD$992qb-(( 	) ?	    K(( 	' ?	    N++ 	* ?	    <'+Bxx'8< < <
 
 	
rm   Tr   validateobservedtuple[BinGrouper, NDFrameT]c                n    |                      |          }|j        t          t          |j                  fS )a  
        Parameters
        ----------
        obj : Series or DataFrame
            Object being grouped.
        validate : bool, default True
            Unused. Only for compatibility with ``Grouper._get_grouper``.
        observed : bool, default True
            Unused. Only for compatibility with ``Grouper._get_grouper``.

        Returns
        -------
        A tuple of grouper, obj (possibly sorted)
        )r  rI   r   r   rO   )rj   rO   r  r  rs        rk   _get_grouperzTimeGrouper._get_grouper	  s0    $ $$z4!%0000rm   rN   r)   c           
        t          |t                    s$t          dt          |          j                   t          |          dk    r)t          g | j        |j        |j                  x}}|g |fS t          |
                                |                                | j        |j        | j        | j        | j                  \  }}t!          | j        |||j        |j        dd|j                  x}}|j        }|                     ||          \  }}t)          j        ||| j        |j                  }| j        d	k    r|}| j        d	k    r
|d
d          }n| j        d	k    r
|d
d          }|j        r6|                    dt2                    }|                    dt2                    }t          |          t          |          k     r|d t          |                   }|||fS )N5axis must be a DatetimeIndex, but got an instance of r   datarQ   r   r4  unitrR   rU   rV   Tshift_forward)rQ   r  r  tzr   	ambiguousnonexistentr  )hasnansrf  r   )r   r)   r  rx   ry   r   rQ   r   r4  _get_timestamp_range_edgesr  r
  r  rR   rU   rV   r*   r  asi8_adjust_bin_edgesr   generate_bins_dt64r  rS   insertr   )	rj   rN   rL   labelsr  r  	ax_values	bin_edgesr   s	            rk   ra  zTimeGrouper._get_time_bins
  s   "m,, 	6"&r(("36 6  
 r77a<<+dibgRX   FV 2v%%0FFHHFFHHI;;;
 
 
t  %u'	
 	
 	
 		
 G	 2269EE	 %y$+rz
 
 
 ;'!!FzW$$Z7""ABBZF: 	+]]1c**F]]1c**F
 t99s6{{""Kc$iiK(FtV##rm   rL   r  npt.NDArray[np.int64]+tuple[DatetimeIndex, npt.NDArray[np.int64]]c                *   | j         j        dv s'| j         j                            d          d         dv r| j        dk    r|                    d           }|t          d                              |j                  z   t          d|j                                      |j                  z
  }|                    |j                  j	        }n|j	        }|d	         |
                                k    r|d d
         }|d d
         }n|j	        }||fS )N)r  r  r  r  r   )r  r  r  r  r  rf  r   )daysr  rg  )rQ   r   splitrR   tz_localizer   as_unitr  r  r  r
  )rj   rL   r  	edges_dtir  s        rk   r  zTimeGrouper._adjust_bin_edgesK
  s   
 9>///49>3G3G3L3LQ3O T
 4
 4
 {g%%"..t44	Q'''//	??@	777??	OOP 
 &11&)<<A		"K	 }y}}..%crcN	Iy  rm   r-   c                   t          |t                    s$t          dt          |          j                   t          | j        t          t          f          st          d| j                   t          |          s#t          g | j        |j
                  x}}|g |fS |                                |                                }}| j        dk    r
|| j        z  }t          ||| j        |j
                  x}}|}| j        dk    r
|| j        z  }|                    || j                  }| j        r
|| j        z  }|||fS )Nz6axis must be a TimedeltaIndex, but got an instance of zWResampling on a TimedeltaIndex requires fixed-duration `freq`, e.g. '24h' or '3D', not r  rQ   r   rf  r  r  rQ   r   r  side)r   r-   r  rx   ry   rQ   r3   r2   ra   r   r   r  r
  rR   r.   searchsortedrV   )rj   rN   rL   r  r  r  
end_stampsr   s           rk   r  z TimeGrouper._get_time_delta_binso
  so   "n-- 	6"&r(("36 6  
 $)dC[11 	7+/97 7  
 2ww 	&,"4927SSSSFV2v%%VVXXrvvxxs;'!!49C)Styrw
 
 
 	
 
;&  $)#Jz<<; 	"dk!FtV##rm   c                   t          |t                    s$t          dt          |          j                   | j        }t          |          dk    r$t          g ||j        |j	                  x}}|g |fS t          |d         |d         ||j                  x}}||z                       |d                                          }|j        r|                    |j                  }|                    |d          }|||fS )	Nr  r   r  rg  r  r  r  r  )r   r)   r  rx   ry   rQ   r   r+   r   r4  r,   r   to_timestampr  r  r  )rj   rN   rQ   rL   r  r  r   s          rk   _get_time_period_binsz!TimeGrouper._get_time_period_bins
  s   "m,, 	6"&r(("36 6  
 yr77a<<)d   FV 2v%%&RU2TPRPWXXXXtm++D#66CCEE
5 	7#//66Jz77tV##rm   r+   c                   t          |t                    s$t          dt          |          j                   |                    | j        | j                  }d}|j        r't          j
        |j                  }||j                  }t          |          syt          j        g t          j                  }t          g | j        |j                  x}}t          |          dk    r#t!          |||t          |                    \  }}}|||fS | j        j        }|                                                    | j        | j                  }|                                                    | j        d          }	d}
t          | j        t(                    rct+          ||	| j        | j        | j        | j                  \  }}	t3          || j                  t3          || j                  z
  }|j        |z  }
|}t5          ||	| j        |j                  x}}|j        }t          |          |z  }||d	         |d         z
  z
  }t          j        |d         |d	         |z   |          }||z  }||
z  } t          |j                  ||j                  }|                    |d
          }|dk    rt!          ||||          \  }}}|||fS )Nz3axis must be a PeriodIndex, but got an instance of r  r   )r4  r  r  )rR   rU   rV   r  rg  r  r  ) r   r+   r  rx   ry   r   rQ   rT   r  npr   _isnanr   arrayr2  r   _insert_nat_binnr  r
  r3   _get_period_range_edgesrR   rU   rV   r   r,   r  arange_datar4  r  )rj   rN   r  	nat_countr   rL   r  	freq_multr  r  	bin_shiftp_startstart_offseti8expected_bins_count	i8_extendrngprngs                     rk   r{  zTimeGrouper._get_period_bins
  s   "k** 	6"&r(("36 6  
 yyy88 	< 	& t{++I%D4yy 	(8Bbh///D)r	PPPPFV2ww{{'6vtVSQSWW'U'U$f4''IK		t??ffhhoodiUo33	di&& 	
 3	{{{  LGS "%33fWdi6P6PPL$2IE&Styrw
 
 
 	
 Y "&kkI5'2b6BqE>:	i1r"v	19==yy  tDJ4:666  F 33q==#264#S#S FD&tV##rm   r  r`   r[   Index | None3tuple[NDFrameT, Index, npt.NDArray[np.intp] | None]c               8   t                                          |||          \  }}}t          |j        t                    rS|j        j        dv rE|j        | _        t          t          t          |j
                                                            }|||fS )Nr  Mm)r   rd   r   r4  r   kindr   r(   r   r   r  _maybe_convert_datelike_array)rj   rO   r`   r[   rN   r   r   s         rk   rd   zTimeGrouper._set_grouper
  s     !77//TY/OORbh
++ 	0E0E "D("(33QQSS B Brm   )Nr  NNNr  NNNr  NF)rO   r  rQ   r:   rh   r  rR   r  rS   r  r   rn   r   r   rT   r  rU   r  rV   r  rW   r\   r]   r^   )rO   r!   r]   rH   )TT)rO   r   r  r\   r  r\   r]   r  )rN   r)   )rL   r)   r  r  r]   r  )rN   r-   )rN   r+   rA  )rO   r   r`   r\   r[   r  r]   r  )ry   rB  rC  rD  r%   rw   rE  rl   r  r  ra  r  r  r  r{  rd   rH  rI  s   @rk   rJ   rJ   7	  s        
 
		 	 		
 	 	 	 K  #2615 ?C 37 !r7 r7 r7 r7 r7 r7 r7h,
 ,
 ,
 ,
^ FJ1 1 1 1 1*A$ A$ A$ A$F"! "! "! "!H%$ %$ %$ %$N$ $ $ $0I$ I$ I$ I$X +0	 NR	  	  	  	  	  	  	  	  	  	  	  	 rm   rJ   rD   r   npt.NDArray[np.intp]r  r(   c                    d S r   r   rO   r   r  s      rk   r  r    s	     rm   rE   c                    d S r   r   r  s      rk   r  r    s	     Srm   DataFrame | Seriesc                T   t          | t                    r7t          j        | j        |          }|                     ||| j                  S t          | t                    r9| j        	                    ||d          }| 
                    ||j                  S t          d          )N)r   r   r   )new_axisr   r   )axesz.'obj' should be either a Series or a DataFrame)r   r   algostake_nd_values_constructorr   r   _mgrreindex_indexer_constructor_from_mgrr  ra   )rO   r   r  
new_valuesnew_mgrs        rk   r  r    s    
 #y!! K]3;88

)#(KKK	C	&	& K(**IwUV*WW((w|(DDDIJJJrm   r  r  r  r   r  rQ   r   r  rB   rR   Literal['right', 'left']rU   r@   rV   Timedelta | Nonetuple[Timestamp, Timestamp]c           	        t          |t                    rk| j        }t          |t                    r|j        du |du k    rt	          d          |dk    rt          d|          }t          | ||||||          \  } }nu|                                 } |                                }|dk    r#t          |                    |                     } nt          | |z
            } t          ||z             }| |fS )aW  
    Adjust the `first` Timestamp to the preceding Timestamp that resides on
    the provided offset. Adjust the `last` Timestamp to the following
    Timestamp that resides on the provided offset. Input Timestamps that
    already reside on the offset will be adjusted depending on the type of
    offset and the `closed` parameter.

    Parameters
    ----------
    first : pd.Timestamp
        The beginning Timestamp of the range to be adjusted.
    last : pd.Timestamp
        The ending Timestamp of the range to be adjusted.
    freq : pd.DateOffset
        The dateoffset to which the Timestamps will be adjusted.
    closed : {'right', 'left'}, default "left"
        Which side of bin interval is closed.
    origin : {'epoch', 'start', 'start_day'} or Timestamp, default 'start_day'
        The timestamp on which to adjust the grouping. The timezone of origin must
        match the timezone of the index.
        If a timestamp is not used, these values are also supported:

        - 'epoch': `origin` is 1970-01-01
        - 'start': `origin` is the first value of the timeseries
        - 'start_day': `origin` is the first day at midnight of the timeseries
    offset : pd.Timedelta, default is None
        An offset timedelta added to the origin.

    Returns
    -------
    A tuple of length 2, containing the adjusted pd.Timestamp objects.
    Nz4The origin must have the same timezone as the index.r  z
1970-01-01)r  )rR   rU   rV   r  r  )r   r3   r  r   ra   _adjust_dates_anchored	normalizerollback)r  r  rQ   r  rR   rU   rV   index_tzs           rk   r  r     s   R $ &8fi(( 	Ufi4.?XQUEU-V-VSTTTW |999F,
 
 
tt !!~~VdmmE2233EEedl++E%%$;rm   r   tuple[Period, Period]c           	        t          d | |fD                       st          d          |                                 }|                                }|                    |           }|                    |          }	t	          |||d|||          \  }}|t          |          |z  z                       |          } |t          |	          |z  z
                      |          }| |fS )al  
    Adjust the provided `first` and `last` Periods to the respective Period of
    the given offset that encompasses them.

    Parameters
    ----------
    first : pd.Period
        The beginning Period of the range to be adjusted.
    last : pd.Period
        The ending Period of the range to be adjusted.
    freq : pd.DateOffset
        The freq to which the Periods will be adjusted.
    closed : {'right', 'left'}, default "left"
        Which side of bin interval is closed.
    origin : {'epoch', 'start', 'start_day'}, Timestamp, default 'start_day'
        The timestamp on which to adjust the grouping. The timezone of origin must
        match the timezone of the index.

        If a timestamp is not used, these values are also supported:

        - 'epoch': `origin` is 1970-01-01
        - 'start': `origin` is the first value of the timeseries
        - 'start_day': `origin` is the first day at midnight of the timeseries
    offset : pd.Timedelta, default is None
        An offset timedelta added to the origin.

    Returns
    -------
    A tuple of length 2, containing the adjusted pd.Period objects.
    c              3  @   K   | ]}t          |t                    V  d S r   )r   r   )rs   rO   s     rk   ru   z*_get_period_range_edges.<locals>.<genexpr>  s,      @@3z#v&&@@@@@@rm   z3'first' and 'last' must be instances of type Periodnsr  )allr  r  is_on_offsetr  r   rp  )
r  r  rQ   rR   rU   rV   first_tslast_tsadjust_firstadjust_lasts
             rk   r  r  i  s   L @@5$-@@@@@ OMNNN !!##H!!G((222L##G,,K2'4d6&QW  Hg L))D00;;DAAEc+&&--88>>D$;rm   rL   r+   r   
np.ndarrayr  r  r   +tuple[PeriodIndex, np.ndarray, PeriodIndex]c                    |dk    sJ ||z  }t          j        |d|          }|                     dt                    } |                    dt                    }| ||fS )Nr   )r  r  r   )rL   r   r  r  s       rk   r  r    se    
 q====ID9T1i((D ]]1c""F ]]1c""F4rm   rf  r&  r3   c                   |                      |          } |                     |          }||                     |          }t          |                               |          j        }d}|dk    r|                                 j        }n|dk    r| j        }n}t	          |t
                    r|                     |          j        }nM|dv rI|dk    r|n|                    d          }	|	j        | j        z
  |z  }
|dk    r|
dz  }
|	|
|z  z
  } | j        }||r|j        ndz  }| j        }|j        }||                     d	          } ||                    d	          }| j        |z
  |z  }|j        |z
  |z  }|d
k    r7|dk    r| j        |z
  }n
| j        |z
  }|dk    r|j        ||z
  z   }n>|j        }n6|dk    r| j        |z
  }n| j        }|dk    r|j        ||z
  z   }n
|j        |z   }t          ||          }t          ||          }|(|	                    d	                              |          }|(|	                    d	                              |          }||fS )Nr   r  r  r  r  Dr  r   UTCrf  r  )
r  r   _valuer   r   r   ceiltzinfo
tz_convertr  )r  r  rQ   rR   rU   rV   r  
freq_valueorigin_timestamporigin_lastsub_freq_timesfirst_tzinfolast_tzinfofoffsetloffsetfresult_intlresult_intfresultlresults                      rk   r  r    s    MM$E<<D%%4((..5J ??,,3	7		 <	FI	&	& (!>>$//6	%	%	%$oodd499S>>%,u|;
JVaNnt33 <6Q6
 <L+K  ''u%%|..*<G{--;GQ;;,0KK,3KQ;;+g)=>KK +KKQ;;,0KK  ,KQ;;+g)=>KK+
2K$///G$///G%%e,,77EE%%e,,77DDGrm   Fr   r   r\   c                4   t          | j        t                    r|t          d          |d}t          |t                    r$t          |d          rt          |          j        }|                                 }| j        	                    ||          |_        nt          | j                  dk    r/|                                 }t          | j        |          |_        nd}t          | j        t                    r| j        j        }t          | j                                        | j                                        ||          }| j        j        |_        |                     |||	          }|r|j                                        |_        |S )
z
    Utility frequency conversion method for Series/DataFrame.

    See :meth:`pandas.NDFrame.asfreq` for full documentation.
    Nz"'method' argument is not supportedE_period_dtype_coder  r   r&  )rQ   r  )r   r   )r   r   r+   r   r   hasattrr   _freqstrr(  r   r   r   r)   r  r*   r  r
  r   r*  r   )	rO   rQ   r   r   r   r   r  r  dtis	            rk   r   r     s\    #)[)) 6%&JKKK;CdJ'' 	2t122 2"4((1((**	((3(77	SY1		((**&sy$77ci// 	"9>D#)--//4PPP9>++c&Z+HH 	6#M3355GMNrm   r   r9   c                   t          |           dk    rt          d          t          | t                    r|                     |          }nt          | t
                    rt          g | j        || j                  }nOt          | t                    rt          g | j        || j                  }nt          t          |                     |S )z
    Helper to mimic asfreq on (empty) DatetimeIndex and TimedeltaIndex.

    Parameters
    ----------
    index : PeriodIndex, DatetimeIndex, or TimedeltaIndex
    freq : DateOffset

    Returns
    -------
    same type as index
    r   zECan only set arbitrary freq for empty DatetimeIndex or TimedeltaIndexr   )r4  rQ   r   )r   ra   r   r+   r   r)   r4  r   r-   r  rx   )r   rQ   r  s      rk   r   r   4  s     5zzQS
 
 	
 %%% %LLdL++			E=	)	) %!"EKdTTT			E>	*	* %"2U[t%*UUU		U$$$rm   )rO   r  r]   rH   )NNNN)r   r#   r   r   r]   rH   )rO   rD   r   r
  r  r(   r]   rD   )rO   rE   r   r
  r  r(   r]   rE   )rO   r  r   r
  r  r(   r]   r  )r  r  N)r  r   r  r   rQ   r   r  rB   rR   r  rU   r@   rV   r  r]   r  )r  r   r  r   rQ   r   rR   r  rU   r@   rV   r  r]   r#  )
rL   r+   r   r-  r  r+   r  r   r]   r.  )rf  r  Nr&  )r  r   r  r   rQ   r3   rR   r  rU   r@   rV   r  r  rB   r]   r  )NNFN)rO   r   r   r\   r]   r   )r   r9   r]   r9   ){
__future__r   r(  typingr   r   r   r   r   r	   r
   r   r   numpyr  pandas._libsr   pandas._libs.tslibsr   r   r   r   r   r   r   pandas._typingr   pandas.errorsr   r   pandas.util._decoratorsr   pandas.util._exceptionsr   pandas.core.dtypes.dtypesr   r   pandas.core.dtypes.genericr   r   pandas.core.algorithmscore
algorithmsr  pandas.core.applyr   pandas.core.arraysr   pandas.core.baser   r    pandas.core.genericr!   pandas.core.groupby.groupbyr"   r#   r$   pandas.core.groupby.grouperr%   pandas.core.groupby.opsr&   pandas.core.indexes.apir'   pandas.core.indexes.baser(   pandas.core.indexes.datetimesr)   r*   pandas.core.indexes.periodr+   r,   pandas.core.indexes.timedeltasr-   r.   pandas.core.reshape.concatr/   pandas.tseries.frequenciesr0   r1   pandas.tseries.offsetsr2   r3   collections.abcr4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   r6  rD   rE   rF   rE  rH   rK  r\  r_  rw  ry  r  r  r  rD  r  rJ   r  r  r  r  r  r   r   r   rm   rk   <module>rh     sg   " " " " " " " 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	                             $ # # # # #        / . . . . . 4 4 4 4 4 4              
 ' & & & & & & & & 2 2 2 2 2 2 2 2 2 2 2 2                     
 0 / / / / / . . . . . . . . . . . . * * * * * *                      . - - - - -              
  ,       
                               "        ,+++++&(  ( ( ( (   h; h; h; h; h;\ h; h; ! h;V9n n n n nL. n n nbi i i i iY i i iX   	& 	& 	& 	& 	&)	& 	& ! 	&T* T* T* T* T*1 T* T* T*n   	$ 	$ 	$ 	$ 	$'	$ 	$ ! 	$    4   ,   	' 	' 	' 	' 	'*	' 	' ! 	'" " " " ")  	N N N N N$   J  J  J  J  J ' J  J  ! J Z 
   

 
   

K K K K( (. +#F F F F FZ (. +#5 5 5 5 5p       , (/ +#Q Q Q Q Qn * * * * *Z     rm   