HOME


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

���h���@s:UddlZddlmZddlmZddlmZmZmZm	Z	ddl
Zddlm
Z
ddlmZmZmZmZmZmZddlmZmZddlmZdd	lmZdd
lmZmZm Z ddl!m"Z"m#Z#ddl$j%j&Z'ddl(m)Z)m*Z*dd
l+m,Z,m-Z-ddl.m/Z/ddl0m1Z1ddl2m3Z3m4Z4m5Z5m6Z6ddl7m8Z8ddl9m:Z:ddl;m<Z<ddl=m>Z>m?Z?ddl@mAZAmBZBddlCmDZDmEZEddlFmGZGmHZHddlImJZJmKZKmLZLmMZMeN�ZOeePePfOGdd�de4e*�ZQx6dPD].ZReRdfdd�ZSeTe3eR�jUeS_UeVeQeReS��q�Wx4dQD],ZReRfd'd(�ZWeTe3eR�jUeW_UeVeQeReW��q�Wx4dRD],ZReRfd*d+�ZXeTe1eR�jUeX_UeVeQeReX��q*WGd,d-�d-e/�ZYGd.d/�d/eQ�ZZGd0d1�d1eYeZ�Z[Gd2d3�d3eZ�Z\Gd4d5�d5eYe\�Z]Gd6d7�d7eZ�Z^Gd8d9�d9eYe^�Z_dSd:d;�Z`eQjUe`_UdTd<d=�ZaGd>d?�d?e8�ZbdUd@dA�ZcdVdDdE�ZddWdFdG�ZedXdIdJ�ZfdYdLdM�ZgdNdO�ZhdS)Z�N)�	timedelta)�dedent)�Dict�Optional�Union�
no_type_check)�lib)�IncompatibleFrequency�NaT�Period�	Timedelta�	Timestamp�	to_offset)�TimedeltaConvertibleTypes�TimestampConvertibleTypes)�function)�AbstractMethodError)�Appender�Substitution�doc)�ABCDataFrame�	ABCSeries)�	DataError�ShallowMixin)�NDFrame�_shared_docs)�GroupByMixin)�
SeriesGroupBy)�GroupBy�_GroupBy�_pipe_template�get_groupby)�Grouper)�
BinGrouper)�Index)�
DatetimeIndex�
date_range)�PeriodIndex�period_range)�TimedeltaIndex�timedelta_range)�is_subperiod�is_superperiod)�
DateOffset�Day�Nano�Tickc	s�eZdZdZdddddddd	d
g	Zdbd
d�Zed�dd�Zed�dd�Z�fdd�Z	e
dd��Ze
dd��Ze
ed�dd��Z
e
ed�dd��Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zedd)d*d+�ee��fd,d-���Zed.�Zed/�Zeed0eed1d2d1d3�d4d5��ZeZeZ d6d7�Z!d8d9�Z"dcd:d;�Z#dde$d<�d=d>�Z%ded?d@�Z&dAdB�Z'dCdD�Z(dEdF�Z)dfdGdH�Z*e*Z+dgdIdJ�Z,dhdKdL�Z-e-Z.didMdN�Z/ee0j1fe2�djdRdS��Z1dkdTdU�Z3dldWdX�Z4dmdYdZ�Z5ee6j7�d[d\��Z7ee6j8�d]d^��Z8dnd`da�Z9�Z:S)o�	Resamplera2
    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 : pandas object
    groupby : a TimeGrouper object
    axis : int, default 0
    kind : str or None
        'period', 'timestamp' to override default index treatment

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

    Notes
    -----
    After resampling, see aggregate, apply, and transform functions.
    �freq�axis�closed�label�
convention�loffset�kind�origin�offsetNrcKsh||_d|_d|_||_||_d|_d|_d|_t�|_	d|_
d|_|jdk	rd|jj|j
|�dd�dS)NTF)�sort)�groupby�keysr;r3r8ZsqueezeZ
group_keysZas_index�setZ
exclusions�binner�grouper�_set_grouper�_convert_obj)�self�objr<r3r8�kwargs�rF�6/tmp/pip-build-5_djhm0z/pandas/pandas/core/resample.py�__init__Ps
zResampler.__init__)�returncs0�fdd��jD�}t��j�ddj|��d�S)z@
        Provide a nice str repr of our rolling object.
        c3s6|].}t�j|d�dk	r|�dt�j|���VqdS)N�=)�getattrr<)�.0�k)rCrFrG�	<genexpr>esz$Resampler.__str__.<locals>.<genexpr>z [z, �])�_attributes�type�__name__�join)rC�attrsrF)rCrG�__str__`s

zResampler.__str__)�attrcCsJ||jkrtj||�S||jkr,t|j|�S||jkr>||Stj||�S)N)Z_internal_names_set�object�__getattribute__rPrKr<rD)rCrVrFrFrG�__getattr__ks


zResampler.__getattr__cs|j�t�j�S)z�
        Resampler iterator.

        Returns
        -------
        Generator yielding sequence of (name, subsetted object)
        for each group.

        See Also
        --------
        GroupBy.__iter__
        )�_set_binner�super�__iter__)rC)�	__class__rFrGr\us
zResampler.__iter__cCs|jjS)N)r<rD)rCrFrFrGrD�sz
Resampler.objcCs|jjS)N)r<�ax)rCrFrFrGr^�szResampler.axcCst|jt�rdSdS)zC
        Masquerade for compat as a Series or a DataFrame.
        ZseriesZ	dataframe)�
isinstance�
_selected_objr)rCrFrFrG�_typ�szResampler._typcCs"|jdk	o |jjdk	p |jjdk	S)zP
        Is the resampling from a DataFrame column or MultiIndex level.
        N)r<�key�level)rCrFrFrG�_from_selection�s
zResampler._from_selectioncCs|j�}|S)z�
        Provide any conversions for the object in order to correctly handle.

        Parameters
        ----------
        obj : the object to be resampled

        Returns
        -------
        obj : converted object
        )Z_consolidate)rCrDrFrFrGrB�szResampler._convert_objcCst|��dS)N)r)rCrFrFrG�_get_binner_for_time�szResampler._get_binner_for_timecCs|jdkr|j�\|_|_dS)zW
        Setup our binners.

        Cache these as we are an immutable object
        N)r?�_get_binnerr@)rCrFrFrGrZ�s
zResampler._set_binnercCs<|j�\}}}t|�t|�ks"t�t|||jjd�}||fS)zk
        Create the BinGrouper, assume that self.set_grouper(obj)
        has already been called.
        )�indexer)re�len�AssertionErrorr#r<rg)rCr?�bins�	binlabelsZbin_grouperrFrFrGrf�szResampler._get_binnercCs|j�dS)zF
        Make sure that we are creating our binner & grouper.
        N)rZ)rCrFrFrG�_assure_grouper�szResampler._assure_grouperz.. versionadded:: 0.23.0a�
    >>> 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)�klass�versionadded�examplescst�j|f|�|�S)N)r[�pipe)rC�func�argsrE)r]rFrGrp�szResampler.pipezx
    See Also
    --------
    DataFrame.groupby.aggregate
    DataFrame.resample.transform
    DataFrame.aggregate
    a"
    Examples
    --------
    >>> s = pd.Series([1,2,3,4,5],
                      index=pd.date_range('20130101', periods=5,freq='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')
    DatetimeIndexResampler [freq=<2 * Seconds>, axis=0, closed=left,
                            label=left, convention=start]

    >>> r.agg(np.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' : np.sum})
                         total    result
    2013-01-01 00:00:00      3  2.121320
    2013-01-01 00:00:02      7  4.949747
    2013-01-01 00:00:04      5       NaN
    �	aggregate��	DataFrame)Zsee_alsorornrmr3cOsP|j�|j|f|�|�\}}|dkrB|}d}|j||f|�|�}|j|�}|S)N)rZZ
_aggregate�_groupby_and_aggregate�_apply_loffset)rCrqrrrE�result�howr@rFrFrGrss

zResampler.aggregatecOs|jj|j�j|f|�|�S)a�
        Call function producing a like-indexed Series on each group and return
        a Series with the transformed values.

        Parameters
        ----------
        arg : function
            To apply to each group. Should return a Series with the same index.

        Returns
        -------
        transformed : Series

        Examples
        --------
        >>> resampled.transform(lambda x: (x - x.mean()) / x.std())
        )r`r<�	transform)rC�argrrrErFrFrGrz,szResampler.transformcCst|��dS)N)r)rC�frFrFrG�_downsample@szResampler._downsamplecCst|��dS)N)r)rCr|�limit�
fill_valuerFrFrG�	_upsampleCszResampler._upsample)�ndimcCsP|j�|j}|dkr|j}t|d||jd�}y||Stk
rJ|SXdS)a
        Sub-classes to define. Return a sliced object.

        Parameters
        ----------
        key : string / list of selections
        ndim : {1, 2}
            requested ndim of result
        subset : object, default None
            subset to act on
        N)�byr@r3)rZr@rDr!r3�KeyError)rCrbr�Zsubsetr@�groupedrFrFrG�_gotitemFszResampler._gotitemc	Os
|dkr|j�|j}|j}t|d||jd�}y<t|t�rVt|�rV|j|f|�|�}n|j	|f|�|�}Wn�t
ttfk
r�|j
|f|�|�}Yn`tk
r�}zDdt|�kr�ndt|�kr�ndt|�kr�n�|j
|f|�|�}WYdd}~XnX|j|�}|j|�S)zA
        Re-evaluate the obj with a groupby aggregation.
        N)r�r@r3zMust produce aggregated valuezlen(index) != len(labels)zNo objects to concatenate)rZr@r`r!r3r_r�callableZ_aggregate_item_by_itemrsr�AttributeErrorr��apply�
ValueError�strrw�_wrap_result)	rCryr@rrrErDr�rx�errrFrFrGrv^s,$
z Resampler._groupby_and_aggregatecCsJt|jtttjf�o,t|jt�o,t|j�dk}|r@|j|j|_d|_|S)a
        If loffset is set, offset the result index.

        This is NOT an idempotent routine, it will be applied
        exactly once to the result.

        Parameters
        ----------
        result : Series or DataFrame
            the result of resample
        rN)	r_r7r-r�npZtimedelta64�indexr%rh)rCrxZneeds_offsetrFrFrGrw�s
zResampler._apply_loffsetcKs|j|fd|i|��S)zG
        Return the correct class for resampling with groupby.
        r<)�_resampler_for_grouping)rCr<rErFrFrG�_get_resampler_for_grouping�sz%Resampler._get_resampler_for_groupingcCsVt|t�r|jdk	r|j|_t|t�rR|jrR|j}t|j|jd�|_t	|dd�|_|S)z/
        Potentially wrap any results.
        N)r2�name)
r_rZ
_selectionr��emptyrD�_asfreq_compatr�r2rK)rCrxrDrFrFrGr��szResampler._wrap_resultcCs|jd|d�S)a-
        Forward fill the values.

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

        Returns
        -------
        An upsampled Series.

        See Also
        --------
        Series.fillna
        DataFrame.fillna
        �pad)r~)r�)rCr~rFrFrGr��sz
Resampler.padcCs|jd|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
        --------
        backfill : Backward fill the new missing values in the resampled data.
        pad : 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: 15T, 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: 15T, dtype: float64
        �nearest)r~)r�)rCr~rFrFrGr��s:zResampler.nearestcCs|jd|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
        --------
        bfill : Alias of backfill.
        fillna : Fill NaN values using the specified method, which can be
            'backfill'.
        nearest : Fill NaN values with nearest neighbor starting from center.
        pad : 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_(statistics)

        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').backfill()
        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: 30T, dtype: int64

        >>> s.resample('15min').backfill(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: 15T, 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').backfill()
                               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').backfill(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
        �backfill)r~)r�)rCr~rFrFrGr�sdzResampler.backfillcCs|j||d�S)a

        Fill missing values introduced by upsampling.

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

        Missing values that existed in the original data will
        not be modified.

        Parameters
        ----------
        method : {'pad', 'backfill', 'ffill', 'bfill', 'nearest'}
            Method to use for filling holes in resampled data

            * 'pad' or 'ffill': use previous valid observation to fill gap
              (forward fill).
            * 'backfill' or 'bfill': use next valid observation to fill gap.
            * 'nearest': use nearest valid observation to fill gap.

        limit : int, optional
            Limit of how many consecutive missing values to fill.

        Returns
        -------
        Series or DataFrame
            An upsampled Series or DataFrame with missing values filled.

        See Also
        --------
        backfill : Backward fill NaN values in the resampled data.
        pad : Forward fill NaN values in the resampled data.
        nearest : Fill NaN values in the resampled data
            with nearest neighbor starting from center.
        interpolate : Fill NaN values using interpolation.
        Series.fillna : Fill NaN values in the Series using the
            specified method, which can be 'bfill' and 'ffill'.
        DataFrame.fillna : Fill NaN values in the DataFrame using the
            specified method, which can be 'bfill' and 'ffill'.

        References
        ----------
        .. [1] https://en.wikipedia.org/wiki/Imputation_(statistics)

        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

        Without filling the missing values you get:

        >>> s.resample("30min").asfreq()
        2018-01-01 00:00:00    1.0
        2018-01-01 00:30:00    NaN
        2018-01-01 01:00:00    2.0
        2018-01-01 01:30:00    NaN
        2018-01-01 02:00:00    3.0
        Freq: 30T, dtype: float64

        >>> s.resample('30min').fillna("backfill")
        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: 30T, dtype: int64

        >>> s.resample('15min').fillna("backfill", 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: 15T, dtype: float64

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

        >>> s.resample('30min').fillna("nearest")
        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: 30T, dtype: int64

        Missing values present before the upsampling are not affected.

        >>> sm = pd.Series([1, None, 3],
        ...               index=pd.date_range('20180101', periods=3, freq='h'))
        >>> sm
        2018-01-01 00:00:00    1.0
        2018-01-01 01:00:00    NaN
        2018-01-01 02:00:00    3.0
        Freq: H, dtype: float64

        >>> sm.resample('30min').fillna('backfill')
        2018-01-01 00:00:00    1.0
        2018-01-01 00:30:00    NaN
        2018-01-01 01:00:00    NaN
        2018-01-01 01:30:00    3.0
        2018-01-01 02:00:00    3.0
        Freq: 30T, dtype: float64

        >>> sm.resample('30min').fillna('pad')
        2018-01-01 00:00:00    1.0
        2018-01-01 00:30:00    1.0
        2018-01-01 01:00:00    NaN
        2018-01-01 01:30:00    NaN
        2018-01-01 02:00:00    3.0
        Freq: 30T, dtype: float64

        >>> sm.resample('30min').fillna('nearest')
        2018-01-01 00:00:00    1.0
        2018-01-01 00:30:00    NaN
        2018-01-01 01:00:00    NaN
        2018-01-01 01:30:00    3.0
        2018-01-01 02:00:00    3.0
        Freq: 30T, dtype: float64

        DataFrame resampling is done column-wise. All the same options are
        available.

        >>> 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').fillna("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
        )r~)r�)rC�methodr~rFrFrG�fillnapszResampler.fillna�linearF�forwardc

Ks*|jd�}	|	jf|||||||d�|��S)zD
        Interpolate values according to different methods.
        N)r�r3r~�inplace�limit_direction�
limit_area�downcast)r��interpolate)
rCr�r3r~r�r�r�r�rErxrFrFrGr�s
zResampler.interpolatecCs|jd|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
        DataFrame.asfreq
        �asfreq)r)r�)rCrrFrFrGr�+szResampler.asfreq�cOstjd||�|jd|d�S)a/
        Compute standard deviation of groups, excluding missing values.

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

        Returns
        -------
        DataFrame or Series
            Standard deviation of values within each group.
        �std)�ddof)�nv�validate_resampler_funcr})rCr�rrrErFrFrGr�Asz
Resampler.stdcOstjd||�|jd|d�S)a
        Compute variance of groups, excluding missing values.

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

        Returns
        -------
        DataFrame or Series
            Variance of values within each group.
        �var)r�)r�r�r})rCr�rrrErFrFrGr�Rsz
Resampler.varcCsP|jd�}t|j�sLddlm}|jjdkr6|jj}nd}|g|jd|d�}|S)N�sizer)�Seriesr��int64)r��dtyper�)	r}rhr^�pandasr�r`r�r�r�)rCrxr�r�rFrFrGr�cs


zResampler.sizecCsb|jd�}t|j�s^|jjdkr>t|j�g|jd|jjd�}n ddlm	}|g|j|j
dd�}|S)N�countr�r�)r�r�r�r)ru)r��columnsr�)r}rhr^r`r�rQr�r�r�rur�)rCrxrurFrFrGr�ps

zResampler.count��?cKs|jdd|i|��S)a�
        Return value at the given quantile.

        .. versionadded:: 0.24.0

        Parameters
        ----------
        q : float or array-like, default 0.5 (50% quantile)

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

        See Also
        --------
        Series.quantile
        DataFrame.quantile
        DataFrameGroupBy.quantile
        �quantile�q)r�)r})rCr�rErFrFrGr��szResampler.quantile)NrN)NN)N)N)N)N)N)N)r�rNFr�NN)N)r�)r�)r�);rR�
__module__�__qualname__�__doc__rPrHr�rUrYr\�propertyrDr^ra�boolrdrBrerZrfrlrrr rprZ_agg_see_also_docZ_agg_examples_docrrrsZaggr�rzr}r��intr�rvrwr�r�r�Zffillr�r�Zbfillr�rr��_shared_docs_kwargsr�r�r�rr�r�r��
__classcell__rFrF)r]rGr1+s�


	
#

,

<
f
!



r1�sum�prodcOstj|||�|j||d�S)N)�	min_count)r�r�r})rC�_methodr�rrrErFrFrGr|�sr|�min�max�first�last�mean�sem�median�ohlccOstj|||�|j|�S)N)r�r�r})rCr�rrrErFrFrG�g�sr��nuniquecCs
|j|�S)N)r})rCr�rFrFrG�h�sr�cs:eZdZdZ�fdd�Zeddd��ZeZeZeZ	�Z
S)�
_GroupByMixinz)
    Provide the groupby facilities.
    c	s�|jdd�}|jdd�}|dkr$|}x(|jD]}t|||j|t||���q,Wt�jd�||_d|j_d|jj	_t
j
|j�|_dS)N�parentr<T)�poprP�setattr�getrKr[rH�_groupbyZmutatedr@�copyr<)rCrDrrrEr�r<rV)r]rFrGrH�s
z_GroupByMixin.__init__Ncs(����fdd�}�jj|�}�j|�S)z�
        Dispatch to _upsample; we are stripping all of the _upsample kwargs and
        performing the original function call on the grouped object.
        cs<�j|�jd�}t�t�r*t|��f��S|j�f����S)N)r<)Z
_shallow_copyr<r_r�rKr�)�x)rrr|rErCrFrGrq�s
z"_GroupByMixin._apply.<locals>.func)r�r�r�)rCr|r@rrrErqrxrF)rrr|rErCrG�_apply�sz_GroupByMixin._apply)N)rRr�r�r�rHrr�r�r}rvr�rFrF)r]rGr��sr�csJeZdZedd��Zdd�Zdd�Zdd�Zdd
d�Z�fdd
�Z	�Z
S)�DatetimeIndexResamplercCstS)N)�DatetimeIndexResamplerGroupby)rCrFrFrGr��sz.DatetimeIndexResampler._resampler_for_groupingcCs&|jdkr|jj|j�S|jj|j�S)N�period)r8r<�_get_time_period_binsr^�_get_time_bins)rCrFrFrGre�s
z+DatetimeIndexResampler._get_binner_for_timecKs�|j�|j|�p|}|j}|j}t|�sf|j�}|jj|j�|_|jj|jksbt	|jj|jf��|S|jdk	sz|j
dk	r�t|jj�t|�kr�|dkr�|j
�S|j|j|jd�j|f|�}|j|�}|j|�S)z�
        Downsample the cython defined function.

        Parameters
        ----------
        how : string / cython mapped function
        **kwargs : kw args passed to how function
        N)r3)rZ�_get_cython_funcr^r`rhr�r�Z
_with_freqr2ri�
inferred_freqr@rkr�r<r3rsrwr�)rCryrEr^rDrxrFrFrGr}�s	 
z"DatetimeIndexResampler._downsamplecCs(|jdkr|dd�}n|dd�}|S)z|
        Adjust our binner when upsampling.

        The range of a new index should not be outside specified range
        �rightr�N���)r4)rCr?rFrFrG�_adjust_binner_for_upsamples
z2DatetimeIndexResampler._adjust_binner_for_upsampleNc	Cs�|j�|jrtd��|jr$td��|j}|j}|j}|j|�}|dkrht	|j
�|jkrh|j�}||_
n|j||||d�}|j|�}|j|�S)az
        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

        See Also
        --------
        .fillna

        zaxis must be 0zvUpsampling from level= or on= selection is not supported, use .set_index(...) to explicitly set index to datetime-likeN)r�r~r)rZr3rirdr�r^r`r?r�rr�r2r�r��reindexrwr�)	rCr�r~rr^rDr?Z	res_indexrxrFrFrGr�$s"

z DatetimeIndexResampler._upsamplecs8t�j|�}|jdkr4t|jt�r4|jj|j�|_|S)Nr�)r[r�r8r_r�r'�	to_periodr2)rCrx)r]rFrGr�Osz#DatetimeIndexResampler._wrap_result)NN)rRr�r�r�r�rer}r�r�r�r�rFrF)r]rGr��s$
+r�c@seZdZdZedd��ZdS)r�z9
    Provides a resample of a groupby implementation
    cCstS)N)r�)rCrFrFrG�_constructor^sz*DatetimeIndexResamplerGroupby._constructorN)rRr�r�r�r�r�rFrFrFrGr�Ysr�csNeZdZedd��Z�fdd�Z�fdd�Z�fdd�Zd�fd
d�	Z�Z	S)
�PeriodIndexResamplercCstS)N)�PeriodIndexResamplerGroupby)rCrFrFrGr�dsz,PeriodIndexResampler._resampler_for_groupingcs"|jdkrt�j�S|jj|j�S)N�	timestamp)r8r[rer<�_get_period_binsr^)rC)r]rFrGrehs

z)PeriodIndexResampler._get_binner_for_timecsJt�j|�}|jrd}t|��|jdk	r.d|_|jdkrF|j|jd�}|S)Nz�Resampling from level= or on= selection with a PeriodIndex is not currently supported, use .set_index(...) to explicitly set indexr�)ry)r[rBrd�NotImplementedErrorr7r8�to_timestampr6)rCrD�msg)r]rFrGrBms

z!PeriodIndexResampler._convert_objcs�|jdkrt�j|f|�S|j|�p&|}|j}t|j|j�rT|j|fd|ji|��St	|j|j�r�|dkrz|j||jd�S|j
�S|j|jkr�|j
�Std|j�d|j�d���dS)	z�
        Downsample the cython defined function.

        Parameters
        ----------
        how : string / cython mapped function
        **kwargs : kw args passed to how function
        r�r@r�)r@z
Frequency z cannot be resampled to z&, as they are not sub or super periodsN)r8r[r}r�r^r+r2rvr@r,r�r	)rCryrEr^)r]rFrGr}�s

z PeriodIndexResampler._downsampleNc	sp|jdkrt�j|||d�S|j�|j}|j}|j}|j|j|j	d�}|j
|||d�}|jt||||j
d��S)as
        Parameters
        ----------
        method : string {'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.

        See Also
        --------
        .fillna

        r�)r~r)ry)r�r~)r3)r8r[r�rZr^rDr?r�r2r6Zget_indexerr��_take_new_indexr3)	rCr�r~rr^rD�	new_index�membrg)r]rFrGr��s
zPeriodIndexResampler._upsample)NN)
rRr�r�r�r�rerBr}r�r�rFrF)r]rGr�cs
$r�c@seZdZdZedd��ZdS)r�z:
    Provides a resample of a groupby implementation.
    cCstS)N)r�)rCrFrFrGr��sz(PeriodIndexResamplerGroupby._constructorN)rRr�r�r�r�r�rFrFrFrGr��sr�c@s(eZdZedd��Zdd�Zdd�ZdS)�TimedeltaIndexResamplercCstS)N)�TimedeltaIndexResamplerGroupby)rCrFrFrGr��sz/TimedeltaIndexResampler._resampler_for_groupingcCs|jj|j�S)N)r<�_get_time_delta_binsr^)rCrFrFrGre�sz,TimedeltaIndexResampler._get_binner_for_timecCs|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
        rF)rCr?rFrFrGr��sz3TimedeltaIndexResampler._adjust_binner_for_upsampleN)rRr�r�r�r�rer�rFrFrFrGr��sr�c@seZdZdZedd��ZdS)r�z:
    Provides a resample of a groupby implementation.
    cCstS)N)r�)rCrFrFrGr��sz+TimedeltaIndexResamplerGroupby._constructorN)rRr�r�r�r�r�rFrFrFrGr��sr�cKstf|�}|j||d�S)z8
    Create a TimeGrouper and return our resampler.
    )r8)�TimeGrouper�_get_resampler)rDr8�kwds�tgrFrFrG�
get_resampler�s
r�c	Ks>|jdd�|d<tfd|i|��}|j|j|d�}|j|d�S)zA
    Return our appropriate resampler when grouping as well.
    �onNrbr2)r8)r<)r�r�r�rDr�)	r<�rulery�fill_methodr~r8rEr�Z	resamplerrFrFrG�get_resampler_for_grouping�sr�c
s�eZdZdZejd#Zd$eeeeeeeeeee	ee
feed��fdd�
Zd%dd�Z
d&ed�dd�Zdd�Zdd�Zdd�Zed�dd �Zed�d!d"�Z�ZS)'r�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
    r4r5ryr7r8r6r9r:�MinNr�r�	start_day)r4r5r8r6�baser9r:c!s(|dkrtd|�d���|dkr0td|�d���|
dkrHtd|
�d
���t|�}ddd
ddddh}|j}||ks�d|kr�|d|jd��|kr�|dkr�d}|dkr�d}n|dkr�d}|dkr�d}||_||_|	|_|
p�d|_|jj�|_||_	||_
||_|d k�r||_nFyt
|�|_Wn6tk
�rP}ztd|�d��|�WYdd}~XnXy|
dk	�rft|
�nd|_Wn6tk
�r�}ztd|
�d��|�WYdd}~XnXd|d<|dk	�r�|
dk	�r�td��|�r�t|t��r�t||j|j�|_t|t��rt|�}||_t�jf||d�|��dS)!N�leftr�zUnsupported value z for `label`z
 for `closed`�start�end�e�sz for `convention`�M�A�QZBMZBAZBQ�W�-�E�epochr�zj'origin' should be equal to 'epoch', 'start', 'start_day' or should be a Timestamp convertible type. Got 'z
' instead.z6'offset' should be a Timedelta convertible type. Got 'Tr;z6'offset' and 'base' cannot be present at the same time)r2r3>Nr�r�>Nr�r�>r�r�Nr�r�)rr�r�)r�rZ	rule_code�findr4r5r8r6�lowerryr�r~r9r
�	Exceptionrr:r_r0�nanos�nr�r7r[rH)rCr2r4r5ryr3r�r~r7r8r6r�r9r:rEZ	end_typesr�r�)r]rFrGrH"sb&

zTimeGrouper.__init__cCs�|j|�|j}t|t�r,t||||jd�St|t�s>|dkrPt||||jd�St|t�rjt	|||jd�St
dt|�j�d���dS)a_
        Return my resampler or raise if we have an invalid axis.

        Parameters
        ----------
        obj : input object
        kind : string, optional
            'period','timestamp','timedelta' are valid

        Returns
        -------
        a Resampler

        Raises
        ------
        TypeError if incompatible axis

        )r<r8r3r�)r<r3zVOnly valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of '�'N)
rAr^r_r%r�r3r'r�r)r��	TypeErrorrQrR)rCrDr8r^rFrFrGr�~s


zTimeGrouper._get_resamplerT)�validatecCs"|j|�}|j�|j|j|jfS)N)r�rZr?r@rD)rCrDr
�rrFrFrG�_get_grouper�s
zTimeGrouper._get_grouperc		CsFt|t�stdt|�j����t|�dkrJtg|j|jd�}}|g|fSt|j	�|j
�|j|j|j|j
d�\}}t|j|||j|jddd�}}|j}|j||�\}}tj|||j|jd�}|jd	kr�|}|jd	kr�|d
d�}n|jd	kr�|d
d�}|j�r|jdt�}|jdt�}t|�t|�k�r<|dt|��}|||fS)Nz5axis must be a DatetimeIndex, but got an instance of r)�datar2r�)r4r9r:TZ
shift_forward)r2r�r��tzr�Z	ambiguousZnonexistent)�hasnansr�r�)r_r%r	rQrRrhr2r��_get_timestamp_range_edgesr�r�r4r9r:r&r�asi8�_adjust_bin_edgesrZgenerate_bins_dt64rr5�insertr
)	rCr^r?�labelsr�r��	ax_values�	bin_edgesrjrFrFrGr��sJ

	


zTimeGrouper._get_time_binscCs�|jdkr~t|jd�r~|jdkrN|jd�}|td�td�}|j|j�j}n|j}|d|j�kr�|dd�}|dd�}n|j}||fS)N�Dr�r�����r�r�)	r2r,r4�tz_localizerr/rrr�)rCr?rrrFrFrGr�s

zTimeGrouper._adjust_bin_edgescCs�t|t�stdt|�j����t|�sFtg|j|jd�}}|g|fS|j�|j	�}}t
|||j|jd�}}||j}|j|dd�}|jr�||j7}|j
r�||j
7}|||fS)Nz6axis must be a TimedeltaIndex, but got an instance of )r
r2r�)r�r�r2r�r�)�side)r_r)r	rQrRrhr2r�r�r�r*�searchsortedr:r7)rCr^r?rr�r��
end_stampsrjrFrFrGr��s 




z TimeGrouper._get_time_delta_bins)r^cCs�t|t�stdt|�j����|j}t|�sJtg||jd�}}|g|fSt	|d|d	||jd�}}||j
|d�j�}|jr�|j
|j�}|j|dd�}|||fS)
Nz5axis must be a DatetimeIndex, but got an instance of )r
r2r�rr�)r�r�r2r�r�r�)rr�)r_r%r	rQrRr2rhr'r�r(r�r�rrr)rCr^r2r?rrrjrFrFrGr�s

z!TimeGrouper._get_time_period_binscCs�t|t�stdt|�j����|j|j|jd�}d}|jrRt	j
|j�}||j}t|�sztg|j|j
d�}}|g|fS|jj}|j�j|j|jd�}|j�j|jdd�}d}	t|jt��rt|||j|j|j|jd�\}
}t||j�t|
|j�}|j|}	|
}t|||j|j
d�}}|j}t|�|}
|
|d|d}t	j|d|d
||�}||7}||	8}t|j�||jd	�}|j|d
d�}|dk�r�||7}t	j|d|�}|jdt�}|jdt�}|||fS)Nz3axis must be a PeriodIndex, but got an instance of )ryr)r
r2r�r�)r4r9r:)r�r�r2r�r�)r�r�)rr�r�)r_r'r	rQrRr�r2r6rr�r�Z_isnanrhr�rr�r�r0�_get_period_range_edgesr4r9r:rr(rZarange�_datar�rrr
)rCr^r�Z	nat_countr?rZ	freq_multr�r�Z	bin_shiftZp_startZstart_offset�i8Zexpected_bins_countZ	i8_extend�rngZprngrjrFrFrGr�,sT



zTimeGrouper._get_period_bins)r4r5ryr7r8r6r9r:)
r�NNr�rNNNNNNr�N)N)T)rRr�r�r�r"rPrr�r�rrrrHr�r�rr�rr�r%r�r'r�r�rFrF)r]rGr�
s<@N
#?r�cCsht|t�r*tj|j|�}|j|||jd�St|t�r\|dkrDtd��|j|j	j
||dd��Std��dS)N)r�r�r�zaxis 1 is not supported)Znew_axisrgr3z.'obj' should be either a Series or a DataFrame)r_r�algosZtake_1dZ_valuesr�r�rr�Z_mgrZreindex_indexerr�)rDrgr�r3Z
new_valuesrFrFrGr�vs

r�r�r�cCs�t|t�r�|j}t|t�r6|jdk|dkkr6td��n|dkrJtd|d�}t|t�r||jd�}|jd�}t|t�r||jd�}t||||||d�\}}t|t�r�|j|�}|j|�}n@|j�}|j�}|dkr�t|j	|��}nt||�}t||�}||fS)aU
    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 None
        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.rz
1970-01-01)r)r4r9r:r�)
r_r0rr
r�r.r�_adjust_dates_anchored�	normalize�rollback)r�r�r2r4r9r:Zindex_tzrFrFrGr�s.#








rcCs�tdd�||gD��std��|j�}|j�}|j|�}|j|�}t||||||d�\}}|t|�|j|�}|t|�|j|�}||fS)aj
    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 None
        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.
    css|]}t|t�VqdS)N)r_r)rLrDrFrFrGrN�sz*_get_period_range_edges.<locals>.<genexpr>z3'first' and 'last' must be instances of type Period)r4r9r:)�allr	r�Zis_on_offsetrr�r�)r�r�r2r4r9r:Zadjust_firstZadjust_lastrFrFrGr�s!
rr�c
Csrd}|dkr|j�j}n |dkr(|j}nt|t�r8|j}||rD|jnd7}|j}|j}|dk	rh|jd�}|dk	rz|jd�}|j||j}	|j||j}
|dkr�|	dkr�|j|	}n|j|j}|
dkr�|j|j|
}n|j}nB|	dkr�|j|	}n|j}|
dk�r|j|j|
}n|j|j}t|�}t|�}|dk	�rP|jd�j|�}|dk	�rj|jd�j|�}||fS)Nrr�r��UTCr�)r$�valuer_r
�tzinfoZ
tz_convertrr)
r�r�r2r4r9r:Zorigin_nanosZfirst_tzinfoZlast_tzinfoZfoffsetr7ZfresultZlresultrFrFrGr#sH





r#FcCs�t|jt�rD|dk	rtd��|dkr(d}|j�}|jj||d�|_njt|j�dkrj|j�}t|j|�|_nDt|jd|jd	|d�}|jj	|_	|j
|||d�}|r�|jj�|_|S)
zC
    Utility frequency conversion method for Series/DataFrame.
    Nz"'method' argument is not supportedr)ryrr�)r2)r�rr�)r_r�r'r�r�r�rhr�r&r�r�r$)rDr2r�ryr$rZnew_objZdtirFrFrGr�As 
r�cCsDt|�dkrtd��t|t�r,|j|d�}ntg|j||jd�}|S)z�
    Helper to mimic asfreq on (empty) DatetimeIndex and TimedeltaIndex.

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

    Returns
    -------
    same type as index
    rzECan only set arbitrary freq for empty DatetimeIndex or TimedeltaIndex)r2)r�r2r�)rhr�r_r'r�r$r�r�)r�r2r�rFrFrGr�]s

r�)r�r�)r�r�r�r�r�r�r�r�)r�)N)NNNN)r)r�r�N)r�r�N)r�r�N)NNFN)ir��datetimer�textwraprZtypingrrrrZnumpyr�Zpandas._libsrZpandas._libs.tslibsr	r
rrr
rZpandas._typingrrZpandas.compat.numpyrr�Z
pandas.errorsrZpandas.util._decoratorsrrrZpandas.core.dtypes.genericrrZpandas.core.algorithms�coreZ
algorithmsr"Zpandas.core.baserrZpandas.core.genericrrZpandas.core.groupby.baserZpandas.core.groupby.genericrZpandas.core.groupby.groupbyrrr r!Zpandas.core.groupby.grouperr"Zpandas.core.groupby.opsr#Zpandas.core.indexes.apir$Zpandas.core.indexes.datetimesr%r&Zpandas.core.indexes.periodr'r(Zpandas.core.indexes.timedeltasr)r*Zpandas.tseries.frequenciesr+r,Zpandas.tseries.offsetsr-r.r/r0�dictr�r�r1r�r|rKr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rrr#r�r�rFrFrFrG�<module>s� u


/q
h




n

I
3
?