U
    Mf                    @  sZ  d Z ddlmZ ddlmZ ddlZddlmZmZ ddl	Z	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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! ddl"m#  m$Z% dd
l&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z. ddl/m0Z1 ddl2m3Z3 ddl4m5Z5m6Z6m7Z7m8Z8 ddl9m:Z: ddl;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZD ddlEmFZFmGZG ddlHmIZI ddlJmKZK ddlLmM  mNZN ddlOmPZPmQZQmRZRmSZS ddlTmUZUmVZVmWZW ddlXmM  mYZZ ddl[m\Z\ ddl]m^Z^ ddl_m`Z`maZambZb ddlcmdZdmeZe ddlfmgZgmhZhmiZi ddljmkZk ddllmM  mmZm ddlnmoZo ddlpmqZq ddlrmsZsmtZt dZudd d!d"Zvd#Zwd$Zxd%Zyd&ZzeG d'd( d(eVZ{eeee eegef eeegef  eeef f Z|G d)d* d*eVeWe) edZ}ed+e^d,Z~G d-d. d.e}e) Ze8edDd1d2d3d4d5d5d5d5d5d5d5d.d6d7d8Zd9d:d;d<d=d>Zd?d@dAdBdCZdS )Ea  
Provide the groupby split-apply-combine paradigm. Define the GroupBy
class providing the base-class of operations.

The SeriesGroupBy and DataFrameGroupBy sub-class
(defined in pandas.core.groupby.generic)
expose these user-facing objects to provide specific functionality.
    )annotations)contextmanagerN)partialwraps)dedent)CallableHashableIterableIteratorListLiteralMappingSequenceTypeVarUnioncastfinal)option_context)	Timestamplib)	ArrayLike
IndexLabelNDFrameTPositionalIndexerRandomStateScalarTnpt)functionAbstractMethodError)AppenderSubstitutioncache_readonlydoc)find_stack_level)	is_bool_dtypeis_datetime64_dtypeis_float_dtype
is_integeris_integer_dtypeis_numeric_dtypeis_object_dtype	is_scalaris_timedelta64_dtype)isnanotna)nanops)executor)BaseMaskedArrayBooleanArrayCategoricalExtensionArray)	DataErrorPandasObjectSelectionMixin)	DataFrame)NDFrame)basenumba_ops)GroupByIndexingMixinGroupByNthSelector)CategoricalIndexIndex
MultiIndex)ensure_block_shape)Series)get_group_index_sorter)NUMBA_FUNC_CACHEmaybe_use_numbaz
        See Also
        --------
        Series.%(name)s : Apply a function %(name)s to a Series.
        DataFrame.%(name)s : Apply a function %(name)s
            to each row or column of a DataFrame.
a]  
    Apply function ``func`` group-wise and combine the results together.

    The function passed to ``apply`` must take a {input} as its first
    argument and return a DataFrame, Series or scalar. ``apply`` will
    then take care of combining the results back together into a single
    dataframe or series. ``apply`` is therefore a highly flexible
    grouping method.

    While ``apply`` is a very flexible method, its downside is that
    using it can be quite a bit slower than using more specific methods
    like ``agg`` or ``transform``. Pandas offers a wide range of method that will
    be much faster than using ``apply`` for their specific purposes, so try to
    use them before reaching for ``apply``.

    Parameters
    ----------
    func : callable
        A callable that takes a {input} as its first argument, and
        returns a dataframe, a series or a scalar. In addition the
        callable may take positional and keyword arguments.
    args, kwargs : tuple and dict
        Optional positional and keyword arguments to pass to ``func``.

    Returns
    -------
    applied : Series or DataFrame

    See Also
    --------
    pipe : Apply function to the full GroupBy object instead of to each
        group.
    aggregate : Apply aggregate function to the GroupBy object.
    transform : Apply function column-by-column to the GroupBy object.
    Series.apply : Apply a function to a Series.
    DataFrame.apply : Apply a function to each row or column of a DataFrame.

    Notes
    -----

    .. versionchanged:: 1.3.0

        The resulting dtype will reflect the return value of the passed ``func``,
        see the examples below.

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

    Examples
    --------
    {examples}
    aY  
    >>> df = pd.DataFrame({'A': 'a a b'.split(),
    ...                    'B': [1,2,3],
    ...                    'C': [4,6,5]})
    >>> g = df.groupby('A')

    Notice that ``g`` has two groups, ``a`` and ``b``.
    Calling `apply` in various ways, we can get different grouping results:

    Example 1: below the function passed to `apply` takes a DataFrame as
    its argument and returns a DataFrame. `apply` combines the result for
    each group together into a new DataFrame:

    >>> g[['B', 'C']].apply(lambda x: x / x.sum())
              B    C
    0  0.333333  0.4
    1  0.666667  0.6
    2  1.000000  1.0

    Example 2: The function passed to `apply` takes a DataFrame as
    its argument and returns a Series.  `apply` combines the result for
    each group together into a new DataFrame.

    .. versionchanged:: 1.3.0

        The resulting dtype will reflect the return value of the passed ``func``.

    >>> g[['B', 'C']].apply(lambda x: x.astype(float).max() - x.min())
         B    C
    A
    a  1.0  2.0
    b  0.0  0.0

    Example 3: The function passed to `apply` takes a DataFrame as
    its argument and returns a scalar. `apply` combines the result for
    each group together into a Series, including setting the index as
    appropriate:

    >>> g.apply(lambda x: x.C.max() - x.B.min())
    A
    a    5
    b    2
    dtype: int64a  
    >>> s = pd.Series([0, 1, 2], index='a a b'.split())
    >>> g = s.groupby(s.index)

    From ``s`` above we can see that ``g`` has two groups, ``a`` and ``b``.
    Calling `apply` in various ways, we can get different grouping results:

    Example 1: The function passed to `apply` takes a Series as
    its argument and returns a Series.  `apply` combines the result for
    each group together into a new Series.

    .. versionchanged:: 1.3.0

        The resulting dtype will reflect the return value of the passed ``func``.

    >>> g.apply(lambda x: x*2 if x.name == 'a' else x/2)
    a    0.0
    a    2.0
    b    1.0
    dtype: float64

    Example 2: The function passed to `apply` takes a Series as
    its argument and returns a scalar. `apply` combines the result for
    each group together into a Series, including setting the index as
    appropriate:

    >>> g.apply(lambda x: x.max() - x.min())
    a    1
    b    0
    dtype: int64)templatedataframe_examplesZseries_examplesa  
Compute {fname} of group values.

Parameters
----------
numeric_only : bool, default {no}
    Include only float, int, boolean columns. If None, will attempt to use
    everything, then use only numeric data.
min_count : int, default {mc}
    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 {fname} of values within each group.
aa  
Apply a function `func` with arguments to this %(klass)s object and return
the function's 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(g(f(df.groupby('group')), arg1=a), arg2=b, arg3=c)  # doctest: +SKIP

You can write

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

which is much more readable.

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

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

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 %(klass)s object.

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

Examples
--------
%(examples)s
a  
Call function producing a like-indexed %(klass)s on each group and
return a %(klass)s having the same indexes as the original object
filled with the transformed values.

Parameters
----------
f : function
    Function to apply to each group.

    Can also accept a Numba JIT function with
    ``engine='numba'`` specified.

    If the ``'numba'`` engine is chosen, the function must be
    a user defined function with ``values`` and ``index`` as the
    first and second arguments respectively in the function signature.
    Each group's index will be passed to the user defined function
    and optionally available for use.

    .. versionchanged:: 1.1.0
*args
    Positional arguments to pass to func.
engine : str, default None
    * ``'cython'`` : Runs the function through C-extensions from cython.
    * ``'numba'`` : Runs the function through JIT compiled code from numba.
    * ``None`` : Defaults to ``'cython'`` or the global setting ``compute.use_numba``

    .. versionadded:: 1.1.0
engine_kwargs : dict, default None
    * For ``'cython'`` engine, there are no accepted ``engine_kwargs``
    * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil``
      and ``parallel`` dictionary keys. The values must either be ``True`` or
      ``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is
      ``{'nopython': True, 'nogil': False, 'parallel': False}`` and will be
      applied to the function

    .. versionadded:: 1.1.0
**kwargs
    Keyword arguments to be passed into func.

Returns
-------
%(klass)s

See Also
--------
%(klass)s.groupby.apply : Apply function ``func`` group-wise and combine
    the results together.
%(klass)s.groupby.aggregate : Aggregate using one or more
    operations over the specified axis.
%(klass)s.transform : Call ``func`` on self producing a %(klass)s with the
    same axis shape as self.

Notes
-----
Each group is endowed the attribute 'name' in case you need to know
which group you are working on.

The current implementation imposes three requirements on f:

* f must return a value that either has the same shape as the input
  subframe or can be broadcast to the shape of the input subframe.
  For example, if `f` returns a scalar it will be broadcast to have the
  same shape as the input subframe.
* if this is a DataFrame, f must support application column-by-column
  in the subframe. If f also supports application to the entire subframe,
  then a fast path is used starting from the second chunk.
* f must not mutate groups. Mutation is not supported and may
  produce unexpected results. See :ref:`gotchas.udf-mutation` for more details.

When using ``engine='numba'``, there will be no "fall back" behavior internally.
The group data and group index will be passed as numpy arrays to the JITed
user defined function, and no alternative execution attempts will be tried.

.. versionchanged:: 1.3.0

    The resulting dtype will reflect the return value of the passed ``func``,
    see the examples below.

Examples
--------

>>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
...                           'foo', 'bar'],
...                    'B' : ['one', 'one', 'two', 'three',
...                           'two', 'two'],
...                    'C' : [1, 5, 5, 2, 5, 5],
...                    'D' : [2.0, 5., 8., 1., 2., 9.]})
>>> grouped = df.groupby('A')
>>> grouped.transform(lambda x: (x - x.mean()) / x.std())
          C         D
0 -1.154701 -0.577350
1  0.577350  0.000000
2  0.577350  1.154701
3 -1.154701 -1.000000
4  0.577350 -0.577350
5  0.577350  1.000000

Broadcast result of the transformation

>>> grouped.transform(lambda x: x.max() - x.min())
   C    D
0  4  6.0
1  3  8.0
2  4  6.0
3  3  8.0
4  4  6.0
5  3  8.0

.. versionchanged:: 1.3.0

    The resulting dtype will reflect the return value of the passed ``func``,
    for example:

>>> grouped[['C', 'D']].transform(lambda x: x.astype(int).max())
   C  D
0  5  8
1  5  9
2  5  8
3  5  9
4  5  8
5  5  9
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 {klass} or when passed to {klass}.apply.

    Accepted combinations are:

    - function
    - string function name
    - list of functions and/or function names, e.g. ``[np.sum, 'mean']``
    - dict of axis labels -> functions, function names or list of such.

    Can also accept a Numba JIT function with
    ``engine='numba'`` specified. Only passing a single function is supported
    with this engine.

    If the ``'numba'`` engine is chosen, the function must be
    a user defined function with ``values`` and ``index`` as the
    first and second arguments respectively in the function signature.
    Each group's index will be passed to the user defined function
    and optionally available for use.

    .. versionchanged:: 1.1.0
*args
    Positional arguments to pass to func.
engine : str, default None
    * ``'cython'`` : Runs the function through C-extensions from cython.
    * ``'numba'`` : Runs the function through JIT compiled code from numba.
    * ``None`` : Defaults to ``'cython'`` or globally setting ``compute.use_numba``

    .. versionadded:: 1.1.0
engine_kwargs : dict, default None
    * For ``'cython'`` engine, there are no accepted ``engine_kwargs``
    * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil``
      and ``parallel`` dictionary keys. The values must either be ``True`` or
      ``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is
      ``{{'nopython': True, 'nogil': False, 'parallel': False}}`` and will be
      applied to the function

    .. versionadded:: 1.1.0
**kwargs
    Keyword arguments to be passed into func.

Returns
-------
{klass}

See Also
--------
{klass}.groupby.apply : Apply function func group-wise
    and combine the results together.
{klass}.groupby.transform : Aggregate using one or more
    operations over the specified axis.
{klass}.aggregate : Transforms the Series on each group
    based on the given function.

Notes
-----
When using ``engine='numba'``, there will be no "fall back" behavior internally.
The group data and group index will be passed as numpy arrays to the JITed
user defined function, and no alternative execution attempts will be tried.

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

.. versionchanged:: 1.3.0

    The resulting dtype will reflect the return value of the passed ``func``,
    see the examples below.
{examples}c                   @  s4   e Zd ZdZddddZdd Zdd	d
dZdS )GroupByPlotzE
    Class implementing the .plot attribute for groupby objects.
    GroupBy)groupbyc                 C  s
   || _ d S N)_groupby)selfrM    rQ   ?/tmp/pip-unpacked-wheel-eb6vo0j3/pandas/core/groupby/groupby.py__init__  s    zGroupByPlot.__init__c                   s     fdd}d|_ | j|S )Nc                   s   | j  S rN   )plotrP   argskwargsrQ   rR   f  s    zGroupByPlot.__call__.<locals>.frT   )__name__rO   apply)rP   rW   rX   rY   rQ   rV   rR   __call__  s    zGroupByPlot.__call__strnamec                   s    fdd}|S )Nc                    s    fdd}j |S )Nc                   s   t | j S rN   )getattrrT   rU   )rW   rX   r_   rQ   rR   rY   #  s    z0GroupByPlot.__getattr__.<locals>.attr.<locals>.f)rO   r[   )rW   rX   rY   r_   rP   rV   rR   attr"  s    z%GroupByPlot.__getattr__.<locals>.attrrQ   )rP   r_   rb   rQ   ra   rR   __getattr__!  s    zGroupByPlot.__getattr__N)rZ   
__module____qualname____doc__rS   r\   rc   rQ   rQ   rQ   rR   rK     s   rK   c                   @  sT  e Zd ZU dZded< e Zded< ejdddd	d
ddddddddhB Zded< ded
< ded< e	ddddZ
e	ddddZe	eddddZe	edddd Ze	ed!d" Ze	d#d$ Ze	d%d& Ze	ed'd( Ze	d)dd*d+Zed,ed-d.eed/d0d1d2d3ZeeZe	d:d4dd5d6Ze	d7dd8d9ZdS );BaseGroupByNIndexLabel | None_group_selectionzfrozenset[str]_apply_allowlistas_indexaxisdropna
exclusionsgrouper
group_keyskeyslevelmutatedobjobservedsortsqueezeintops.BaseGrouperboolreturnc                 C  s
   t | jS rN   )lengroupsrU   rQ   rQ   rR   __len__K  s    zBaseGroupBy.__len__r]   c                 C  s
   t | S rN   )object__repr__rU   rQ   rQ   rR   r   O  s    zBaseGroupBy.__repr__zdict[Hashable, np.ndarray]c                 C  s   | j jS )z4
        Dict {group name -> group labels}.
        )ro   r~   rU   rQ   rQ   rR   r~   T  s    zBaseGroupBy.groupsc                 C  s   | j jS rN   )ro   ngroupsrU   rQ   rQ   rR   r   \  s    zBaseGroupBy.ngroupsc                 C  s   | j jS )z5
        Dict {group name -> group indices}.
        )ro   indicesrU   rQ   rQ   rR   r   a  s    zBaseGroupBy.indicesc              
     s
  dd t |dkrg S t jdkr6ttj}nd}|d }t|trt|tsbd}t|t |t |kszfdd|D W S  tk
r } zd}t||W 5 d}~X Y nX fd	d|D fd
d|D }n|  fdd|D }fdd|D S )zd
        Safe get multiple indices, translate keys for
        datelike to underlying repr.
        c                 S  s4   t | tjrdd S t | tjr(dd S dd S d S )Nc                 S  s   t | S rN   )r   keyrQ   rQ   rR   <lambda>t      zABaseGroupBy._get_indices.<locals>.get_converter.<locals>.<lambda>c                 S  s
   t | jS rN   )r   Zasm8r   rQ   rQ   rR   r   v  r   c                 S  s   | S rN   rQ   r   rQ   rQ   rR   r   x  r   )
isinstancedatetimenpZ
datetime64)srQ   rQ   rR   get_converterp  s
    z/BaseGroupBy._get_indices.<locals>.get_converterr   Nz<must supply a tuple to get_group with multiple grouping keysc                   s   g | ]} j | qS rQ   )r   .0r_   rU   rQ   rR   
<listcomp>  s     z,BaseGroupBy._get_indices.<locals>.<listcomp>zHmust supply a same-length tuple to get_group with multiple grouping keysc                   s   g | ]} |qS rQ   rQ   )r   r   )r   rQ   rR   r     s     c                 3  s&   | ]}t d d t |D V  qdS )c                 s  s   | ]\}}||V  qd S rN   rQ   )r   rY   nrQ   rQ   rR   	<genexpr>  s     z5BaseGroupBy._get_indices.<locals>.<genexpr>.<genexpr>N)tuplezipr   )
convertersrQ   rR   r     s     z+BaseGroupBy._get_indices.<locals>.<genexpr>c                 3  s   | ]} |V  qd S rN   rQ   r   )	converterrQ   rR   r     s     c                   s   g | ]} j |g qS rQ   )r   getr   rU   rQ   rR   r     s     )r}   r   nextiterr   r   
ValueErrorKeyError)rP   namesZindex_sampleZname_samplemsgerrrQ   )r   r   r   rP   rR   _get_indicesi  s.    


zBaseGroupBy._get_indicesc                 C  s   |  |gd S )zQ
        Safe get index, translate keys for datelike to underlying repr.
        r   )r   )rP   r_   rQ   rQ   rR   
_get_index  s    zBaseGroupBy._get_indexc                 C  sB   | j d kst| jtr2| jd k	r,| j| j S | jS | j| j  S d S rN   )
_selectionr   rt   rE   ri   rU   rQ   rQ   rR   _selected_obj  s
    
zBaseGroupBy._selected_objzset[str]c                 C  s   | j  | jB S rN   )rt   _dir_additionsrj   rU   rQ   rQ   rR   r     s    zBaseGroupBy._dir_additionsrL   a          >>> df = pd.DataFrame({'A': 'a b a b'.split(), 'B': [1, 2, 3, 4]})
        >>> df
           A  B
        0  a  1
        1  b  2
        2  a  3
        3  b  4

        To get the difference between each groups maximum and minimum value in one
        pass, you can do

        >>> df.groupby('A').pipe(lambda x: x.max() - x.min())
           B
        A
        a  2
        b  2)klassexamplesz/Callable[..., T] | tuple[Callable[..., T], str]r   )funcr|   c                 O  s   t j| |f||S rN   )compipe)rP   r   rW   rX   rQ   rQ   rR   r     s    zBaseGroupBy.pipeDataFrame | Seriesc                 C  s8   |dkr| j }| |}t|s(t||j|| jdS )a  
        Construct DataFrame from group with provided name.

        Parameters
        ----------
        name : object
            The name of the group to get as a DataFrame.
        obj : DataFrame, default None
            The DataFrame to take the DataFrame out of.  If
            it is None, the object groupby was called on will
            be used.

        Returns
        -------
        group : same type as obj
        Nrl   )r   r   r}   r   Z_take_with_is_copyrl   )rP   r_   rt   ZindsrQ   rQ   rR   	get_group  s    
zBaseGroupBy.get_groupz#Iterator[tuple[Hashable, NDFrameT]]c                 C  s   | j j| j| jdS )z
        Groupby iterator.

        Returns
        -------
        Generator yielding sequence of (name, subsetted object)
        for each group
        r   )ro   get_iteratorr   rl   rU   rQ   rQ   rR   __iter__  s    
zBaseGroupBy.__iter__)N)rZ   rd   re   ri   __annotations__	frozensetrj   r8   Z_hidden_attrsr   r   r   propertyr~   r   r   r   r   r#   r   r   r"   r   r!   _pipe_templater   rK   rT   r   r   rQ   rQ   rQ   rR   rg   4  sn   

2

rg   OutputFrameOrSeries)boundc                      s|  e Zd ZU dZded< ded< edd
ddddddddddddddddZddddZdd fddZedddddZ	edddd Z
eddd!d"Zed#dd$d%Zd&dd'd(Zeddd)d*d+Zed,d,d-d.d/Zd0d1d-d2d3Zed d4d5d6d7d8Zed0d1d9d:d;Zdd<dd=d>d?Zd@ddAdBdCZedDdE ZddFddGdHdIZeddJdKdLZeddJdMdNZeedO jdPedQ dRdSdT ZedddUdVdUdWdXdYZedZd[ Zedddddd]d^d_Z d`ddd`dadbdcZ!eddddddddedfZ"dddddgdhdiZ#edddjdkdlZ$ed
d
d-dmdnZ%edodp Z&edddqdrdsdtZ'ee(dddudvZ)edwddxdydzZ*ee+d{d|ee,ddd}d~dZ-ee+d{d|ee,ddd}ddZ.ee+d{d|ee,d1dddZ/ee+d{d|e+e,de0j1ddfd@ddFdddZ2ee+d{d|ee,e0j1fd@dddZ3ee+d{d|ee,d	dddFdddZ4ee+d{d|ee,d
dddFdddZ5ee+d{d|ee,dddddZ6ee+d{d|ee,dUdddZ7ee8e9dddde0j1dddfd@dddFdddZ:ee8e9dddde0j1dfd@ddddZ;ee8e9dd	d\dddddddZ<ee8e9dd	d\dddddddZ=ee8e9dd	d\dddddddZ>ee8e9dd	d\dddddddZ?ee+d{d|ee,ddddZ@e8eAjBdd ZBedd ZCee+d{d|ee,dd ZDee+d{d|ee,dd ZEee+d{d|ee,dd ZFedddddZGee+d{d|dddZHdddZIeHjeI_ee+d{d|dddÄZJdddńZKeJjeK_ee+d{d|e+e,ddddd
dȜddʄZLeddd͜ddτZMee+d{d|dddМdd҄ZNee+d{d|dddМddԄZOee+d{d|e+e,ddddddddלddلZPee+d{d|ee,dddۄZQee+d{d|ee,ddd݄ZRee+d{d|ee,ddd߄ZSee+d{d|ee,dddZTee0j1d	d	d	ddfddd@ddddddZUee+d{d|dddZVee+d{d|ee,dddZWee+d{d|e+e,dd ddZXee+d{d|e+e,dd!ddZYedqd
dddZZee[j\dfd,dd5d,dddZ]ed"ddddddddZ^  Z_S (#  rL   a  
    Class for grouping and aggregating relational data.

    See aggregate, transform, and apply functions on this object.

    It's easiest to use obj.groupby(...) to use GroupBy, but you can also do:

    ::

        grouped = groupby(obj, ...)

    Parameters
    ----------
    obj : pandas object
    axis : int, default 0
    level : int, default None
        Level of MultiIndex
    groupings : list of Grouping objects
        Most users should ignore this
    exclusions : array-like, optional
        List of columns to exclude
    name : str
        Most users should ignore this

    Returns
    -------
    **Attributes**
    groups : dict
        {group name -> group labels}
    len(grouped) : int
        Number of groups

    Notes
    -----
    After grouping, see aggregate, apply, and transform functions. Here are
    some other brief notes about usage. When grouping by multiple groups, the
    result index will be a MultiIndex (hierarchical) by default.

    Iteration produces (key, group) tuples, i.e. chunking the data by group. So
    you can write code like:

    ::

        grouped = obj.groupby(keys, axis=axis)
        for key, group in grouped:
            # do something with the data

    Function calls on GroupBy, if not specially implemented, "dispatch" to the
    grouped data. So if you group a DataFrame and wish to invoke the std()
    method on each group, you can simply do:

    ::

        df.groupby(mapper).std()

    rather than

    ::

        df.groupby(mapper).aggregate(np.std)

    You can pass arguments to these "wrapped" functions, too.

    See the online documentation for full exposition on these topics and much
    more
    ry   ro   rz   rk   Nr   TFr   _KeysArgType | Nonerx   rh   ops.BaseGrouper | Nonezfrozenset[Hashable] | Nonert   rq   rl   rr   ro   rn   	selectionrk   rv   rp   rw   ru   rs   rm   c              
   C  s   || _ t|tstt||| _|sHt|ts8td|dkrHtd|| _	|| _
|	| _|
| _|| _|| _|| _|| _|d krddlm} ||||||	|| j| jd\}}}|| _||| _|| _|rt|nt | _d S )Nz(as_index=False only valid with DataFramer   z$as_index=False only valid for axis=0get_grouper)rl   rr   rv   ru   rs   rm   )r   r   r;   AssertionErrortyperr   r:   	TypeErrorr   rk   rq   rv   rp   rw   ru   rs   rm   pandas.core.groupby.grouperr   rt   Z_get_axis_numberrl   ro   r   rn   )rP   rt   rq   rl   rr   ro   rn   r   rk   rv   rp   rw   ru   rs   rm   r   rQ   rQ   rR   rS   G  s@    
zGroupBy.__init__r]   )rb   c                 C  sH   || j krt| |S || jkr(| | S tdt| j d| dd S )N'z' object has no attribute ')Z_internal_names_setr   __getattribute__rt   AttributeErrorr   rZ   rP   rb   rQ   rQ   rR   rc     s    

zGroupBy.__getattr__c                   s4   |dkrt | S |dkr$t dS t |S d S )NnthZ
nth_actual)r@   superr   r   	__class__rQ   rR   r     s
    zGroupBy.__getattribute__r   )r_   r|   c              
     s   j kst < tj t tjsNfddW  5 Q R  S W 5 Q R X tt	j t
  fdd}|_|S )Nc                   s
   t |  S rN   )r`   rU   r^   rQ   rR   r     r   z'GroupBy._make_wrapper.<locals>.<lambda>c                    s\   dj kr$dd d kr$jd<  fdd}|_tjkrN|S |jS )Nrl   c                   s   | f S rN   rQ   x)rW   rY   rX   rQ   rR   curried  s    z7GroupBy._make_wrapper.<locals>.wrapper.<locals>.curried)	
parametersr   rl   rZ   r<   Zplotting_methodsr[   _python_apply_general_obj_with_exclusions)rW   rX   r   rY   r_   rP   sigrV   rR   wrapper  s    



z&GroupBy._make_wrapper.<locals>.wrapper)rj   r   _group_selection_contextr`   r   r   types
MethodTyper[   r   inspect	signaturerZ   )rP   r_   r   rQ   r   rR   _make_wrapper  s    
(
zGroupBy._make_wrapperNoner{   c                 C  sv   | j }| jr,|jdk	r,| jjdkr,| jdks0dS dd |jD }t|rr| jj}|jt	|dd
 | _| d dS )z
        Create group based selection.

        Used when selection is not passed directly but instead via a grouper.

        NOTE: this should be paired with a call to _reset_group_selection
        N   c                 S  s"   g | ]}|j d kr|jr|jqS rN   )rr   in_axisr_   )r   grQ   rQ   rR   r     s     
  z0GroupBy._set_group_selection.<locals>.<listcomp>F)rv   r   )ro   rk   	groupingsrt   ndimri   r}   Z
_info_axis
differencerB   tolist_reset_cache)rP   grpZgroupersaxrQ   rQ   rR   _set_group_selection  s    

zGroupBy._set_group_selectionc                 C  s   | j dk	rd| _ | d dS )z
        Clear group based selection.

        Used for methods needing to return info on each group regardless of
        whether a group selection was previously set.
        Nr   )ri   r   rU   rQ   rQ   rR   _reset_group_selection  s    
zGroupBy._reset_group_selectionzIterator[GroupBy]c                 c  s"   |    z
| V  W 5 |   X dS )z;
        Set / reset the _group_selection_context.
        N)r   r   rU   rQ   rQ   rR   r     s    
z GroupBy._group_selection_contextzIterable[Series]c                 C  s   t | d S rN   r   rU   rQ   rQ   rR   _iterate_slices  s    zGroupBy._iterate_slicesnot_indexed_samec                   sn  ddl m}  fdd}|s|| jd} j j} jrZ jjd }|dk}|| }|jr|j	 j 
|s|j|j\}	}
t|	}	|j|	 jd}n|j| jdd}n~ jr||} jr jj} jj} jj}|| j|||dd	}n ttt|}|| j|d
}n||}|| jd} jjdkrH jjn j}t|trj|d k	rj||_|S )Nr   )concatc                   s(   t j|  D ]}| j}|  q
| S rN   )r   Znot_none	_get_axisrl   Z_reset_identity)valuesvr   rU   rQ   rR   reset_identity  s    
z/GroupBy._concat_objects.<locals>.reset_identityr   F)rl   copy)rl   rq   levelsr   rv   )rl   rq   r   ) Zpandas.core.reshape.concatr   rl   r   r   rm   ro   
group_infoZhas_duplicatesaxesequalsindexZget_indexer_non_unique_values
algorithmsZunique1dtakereindexrp   rk   result_indexr   r   listranger}   rt   r   r_   r   r   rE   )rP   r   r   r   r   resultr   labelsmaskindexer_rp   Zgroup_levelsZgroup_namesrq   r_   rQ   rU   rR   _concat_objects  sH    
zGroupBy._concat_objectsr   )r   r|   c                 C  s   | j jr(|j| j| j| jdd |S tt| 	| j j
}|j|| jdd |j| jd}t|jt| jjk }|r|j}| jj| |_n|j| j| j| jdd |S )NT)rl   Zinplacer   )ro   Zis_monotonicZset_axisrt   r   rl   rB   r   concatenater   r   
sort_indexr}   r   r   )rP   r   Zoriginal_positionsZdropped_rowsZsorted_indexerrQ   rQ   rR   _set_result_index_ordered;  s    z!GroupBy._set_result_index_orderedz"Mapping[base.OutputKey, ArrayLike]zSeries | DataFramec                 C  s   t | d S rN   r   rP   r   rQ   rQ   rR   _indexed_output_to_ndframeZ  s    z"GroupBy._indexed_output_to_ndframez7Series | DataFrame | Mapping[base.OutputKey, ArrayLike]znpt.NDArray[np.float64] | None)outputqsc                 C  s   t |ttfr|}n
| |}| jsH| | | }tt| j	j
}n| j	j}|dk	rbt||}||_| jdkr|j}|j| jjr| jj |_| j||dS )a  
        Wraps the output of GroupBy aggregations into the expected result.

        Parameters
        ----------
        output : Series, DataFrame, or Mapping[base.OutputKey, ArrayLike]
           Data to wrap.

        Returns
        -------
        Series or DataFrame
        Nr   r  )r   rE   r:   r  rk   Z_insert_inaxis_grouper_inplaceZ_consolidaterB   r   ro   r   r   _insert_quantile_levelr   rl   r   r   rt   r   _reindex_output)rP   r  r  r   r   rQ   rQ   rR   _wrap_aggregated_output_  s     



zGroupBy._wrap_aggregated_output)r  r|   c                 C  sF   t |ttfr|}n
| |}| jdkr8|j}| jj|_| jj|_|S )aN  
        Wraps the output of GroupBy transformations into the expected result.

        Parameters
        ----------
        output : Mapping[base.OutputKey, ArrayLike]
            Data to wrap.

        Returns
        -------
        Series or DataFrame
            Series for SeriesGroupBy, DataFrame for DataFrameGroupBy
        r   )	r   rE   r:   r  rl   r   rt   columnsr   )rP   r  r   rQ   rQ   rR   _wrap_transformed_output  s    



z GroupBy._wrap_transformed_outputr   )r   r   c                 C  s   t | d S rN   r   )rP   datar   r   rQ   rQ   rR   _wrap_applied_output  s    zGroupBy._wrap_applied_outputzbool | lib.NoDefault)numeric_onlyr|   c                 C  s`   |t jkr\| jjdkrXd}| jr*| jj}n| j}| }t|j	r\t|j	s\|j
s\d}nd}|S )at  
        Determine subclass-specific default value for 'numeric_only'.

        For SeriesGroupBy we want the default to be False (to match Series behavior).
        For DataFrameGroupBy we want it to be True (for backwards-compat).

        Parameters
        ----------
        numeric_only : bool or lib.no_default

        Returns
        -------
        bool
           TF)r   
no_defaultrt   r   rl   r   r   Z_get_numeric_datar}   r  empty)rP   r  rt   checkrQ   rQ   rR   _resolve_numeric_only  s    

zGroupBy._resolve_numeric_onlyc                 C  sx   t |std| jj\}}}t||}tj||dd}|j|| jd	 }|j
|	 }	t||\}
}|
||	|fS )Nz5Numba engine can only be used with a single function.F)Z
allow_fillr   )callableNotImplementedErrorro   r   rF   r   take_ndr   rl   to_numpyr   r   Zgenerate_slices)rP   r   r
  idsr   r   sorted_indexZ
sorted_idssorted_dataZsorted_index_datastartsendsrQ   rQ   rR   _numba_prep  s    
zGroupBy._numba_prepzdict[str, bool] | None)r   engine_kwargsnumba_cache_key_strc              	   G  s   | j std| jdkr td|   | j}W 5 Q R X |jdkrH|n| }| ||\}}}	}
t	|||}||
||df| }||f}|t
kr|t
|< | jj}|jdkrd|ji}| }n
d|ji}|j|fd|i|S )	zp
        Perform groupby with a standard numerical aggregation function (e.g. mean)
        with Numba.
        z<as_index=False is not supported. Use .reset_index() instead.r   zaxis=1 is not supported.r  r   r_   r  r   )rk   r  rl   r   r   r   to_framer  r2   Zgenerate_shared_aggregatorrG   ro   r   r_   ravelr  _constructor)rP   r   r  r  Zaggregator_argsr
  dfr  r  r  r  Z
aggregatorr   	cache_keyr   Zresult_kwargsrQ   rQ   rR   _numba_agg_general  s2    

  



zGroupBy._numba_agg_general)r  c                O  sj   |  ||\}}}}	t|||}
|
|	|||t|jf| }|df}|tkrV|
t|< |jt|ddS )a(  
        Perform groupby transform routine with the numba engine.

        This routine mimics the data splitting routine of the DataSplitter class
        to generate the indices of each group in the sorted data and then passes the
        data and indices into a Numba jitted function.
        Zgroupby_transformr   r   )	r  r=   Zgenerate_numba_transform_funcr}   r  rG   r   r   argsort)rP   r
  r   r  rW   rX   r  r  r  r  Znumba_transform_funcr   r"  rQ   rQ   rR   _transform_with_numba  s&    	  	zGroupBy._transform_with_numbac                O  sZ   |  ||\}}}}	t|||}
|
|	|||t|jf| }|df}|tkrV|
t|< |S )a*  
        Perform groupby aggregation routine with the numba engine.

        This routine mimics the data splitting routine of the DataSplitter class
        to generate the indices of each group in the sorted data and then passes the
        data and indices into a Numba jitted function.
        Zgroupby_agg)r  r=   Zgenerate_numba_agg_funcr}   r  rG   )rP   r
  r   r  rW   rX   r  r  r  r  Znumba_agg_funcr   r"  rQ   rQ   rR   _aggregate_with_numba<  s    		zGroupBy._aggregate_with_numbarI   Z	dataframerJ   )inputr   c                   s   t  sr\tr4t fdd}qttd rRttd }qtdnFtt	rt| rt| }t|r| S |S t
d dn}tdd j z| || j}W nP t
k
r   |  , | || jW  5 Q R   Y W  5 Q R  S Q R X Y nX W 5 Q R X |S )Nc              
     s4   t jdd | f W  5 Q R  S Q R X d S )Nignore)all)r   Zerrstate)r   rW   r   rX   rQ   rR   rY   i  s    zGroupBy.apply.<locals>.fnanz6func must be a callable if args or kwargs are suppliedz$apply func should be callable, not 'r   zmode.chained_assignment)r   is_builtin_funcr  r   hasattrr1   r`   r   r   r]   r   r   r   r   r   )rP   r   rW   rX   rY   resr   rQ   r*  rR   r[   Z  s2    



	
@zGroupBy.applyr   zbool | None)rY   r
  r   r|   c                 C  s8   | j ||| j\}}|dkr(|p&| j}| j|||dS )aB  
        Apply function f in python space

        Parameters
        ----------
        f : callable
            Function to apply
        data : Series or DataFrame
            Data to apply f to
        not_indexed_same: bool, optional
            When specified, overrides the value of not_indexed_same. Apply behaves
            differently when the result index is equal to the input index, but
            this can be coincidental leading to value-dependent behavior.

        Returns
        -------
        Series or DataFrame
            data after applying f
        Nr   )ro   r[   rl   rs   r  )rP   rY   r
  r   r   rs   rQ   rQ   rR   r     s    
  zGroupBy._python_apply_generalc              	     s   t  fdd}i }| jdkr6| || jS t|  D ]^\}}|j}z| j	||}	W n& t
k
r   tt| d Y qBY nX tj||d}
|	||
< qB|s| || jS | |S )Nc                   s   | f S rN   rQ   r   r*  rQ   rR   r     r   z-GroupBy._python_agg_general.<locals>.<lambda>r   Zagg)labelposition)r   r,  r   r   r   	enumerater   r_   ro   
agg_seriesr   )warn_dropping_nuisance_columns_deprecatedr   r<   Z	OutputKeyr  )rP   r   rW   rX   rY   r  idxrt   r_   r   r   rQ   r*  rR   _python_agg_general  s"    



zGroupBy._python_agg_generalr   r  	min_countaliasnpfuncc             
   C  sB   |   0 | j||||d}|j| jddW  5 Q R  S Q R X d S )Nhowaltr  r7  rM   method)r   _cython_agg_general__finalize__rt   )rP   r  r7  r8  r9  r   rQ   rQ   rR   _agg_general  s    

zGroupBy._agg_generalr   )r   r   r<  r|   c                 C  s~   |j dkrt|}n.t|j}|jd dks0t|jdddf }| jj||dd}t	|t
rrt|j||jd}t||dS )zn
        Fallback to pure-python aggregation if _cython_operation raises
        NotImplementedError.
        r   Nr   T)Zpreserve_dtypedtype)r   )r   rE   r:   r   shaper   ilocro   r2  r   r5   r   Z_from_sequencerC  rD   )rP   r   r   r<  Zserr!  
res_valuesrQ   rQ   rR   _agg_py_fallback  s    	



zGroupBy._agg_py_fallbackr:  c           
        s     jdk}|rh|rXtjjsXd}dkr6d}ttj d d| dn|shjddd	d	d
 fdd}j	|dd}|st
|t
k rtt |}	|rֈjj|	_|	S |	S d S )Nr   r  anyr)  Z	bool_only.z does not implement Fr   r   r   r|   c                   sL   z j jd| jd d}W n& tk
rF   j| j d}Y nX |S )N	aggregater   rl   r7  )r   r<  )ro   _cython_operationr   r  rG  )r   r   r<  r
  r;  r7  rP   rQ   rR   
array_func(  s        
z/GroupBy._cython_agg_general.<locals>.array_funcTZignore_failures)_get_data_to_aggregater   r+   r   rC  r  r   rZ   get_numeric_datagrouped_reducer}   r3  _wrap_agged_managerro   r   r   r  )
rP   r;  r<  r  r7  is_serZkwd_namerQ  new_mgrr.  rQ   rP  rR   r?    s*    



zGroupBy._cython_agg_general)r;  r  rl   c                 K  s   t | d S rN   r   )rP   r;  r  rl   rX   rQ   rQ   rR   _cython_transformD  s    zGroupBy._cython_transform)enginer  c          
   	   O  sd  t |r|   | j}W 5 Q R X |jdkr0|n| }| j||f|d|i|}| jjdkr|tt| jj	||j
|jdS tt| jj	| |j
|jdS t|p|}t|ts| j|f||S |tjkrd| d}	t|	nz|tjk s|tjkrt| |||S t| dd t| |||}W 5 Q R X | |rN| |S | j|f||S d S )	Nr  r  r   r  r   r_   r   z2' is not a valid function name for transform(name)ru   T)rH   r   r   r   r  r%  rt   r   r:   r   r   r  rE   r  r_   r   Zget_cython_funcr   r]   Z_transform_generalr<   Ztransform_kernel_allowlistr   Zcythonized_kernelsZtransformation_kernelsr`   temp_setattrZ_can_use_transform_fast_wrap_transform_fast_result)
rP   r   rZ  r  rW   rX   r
  r!  r   r   rQ   rQ   rR   
_transformI  sL    
     




zGroupBy._transformc                 C  sp   | j }| jj\}}}|j| jjdd}| jjdkrVt|j	|}|j
||j|jd}n|j|dd}|j|_|S )z7
        Fast transform path for aggregations.
        FrK  r   r\  r   r   )r   ro   r   r   r   rt   r   r   r  r   r   r   r_   r   )rP   r   rt   r  r   outr  rQ   rQ   rR   r^  {  s    z#GroupBy._wrap_transform_fast_resultc                 C  s   t |dkrtjg dd}ntt|}|rD| jj|| jd}n^tjt | jj	t
d}|d d||t< t|t| jjdd  dg j}| j|}|S )Nr   int64rB  r   FTr   )r}   r   arrayrv   r   r   r   rl   r  r   rz   fillastyperx   tiler   rD  r   where)rP   r   rm   filteredr   rQ   rQ   rR   _apply_filter  s    
$zGroupBy._apply_filter
np.ndarray)	ascendingr|   c                 C  s  | j j\}}}t||}|| t| }}|dkrBtjdtjdS tjd|dd |dd kf }ttjt	|d |f }| 
 }	|r|	t|	| |8 }	n&t|	tj|dd df  ||	 }	tj|tjd}
tj|tjd|
|< |	|
 jtjddS )	a.  
        Parameters
        ----------
        ascending : bool, default True
            If False, number in reverse, from length of group - 1 to 0.

        Notes
        -----
        this is currently implementing sort=False
        (though the default is sort=True) for groupby in general
        r   rB  TNr   r   FrK  )ro   r   rF   r}   r   r  ra  Zr_ZdiffZnonzerocumsumrepeatintpZarangerd  )rP   rj  r  r   r   Zsortercountrunrepr`  revrQ   rQ   rR   _cumcount_array  s    
"
&zGroupBy._cumcount_arrayc                 C  s,   t | jtr| jjS t | jts$t| jjS rN   )r   rt   r:   Z_constructor_slicedrE   r   r   rU   rQ   rQ   rR   _obj_1d_constructor  s    zGroupBy._obj_1d_constructorzLiteral[('any', 'all')])val_testskipnac                   sP   ddd fdd}dddd	dd
dd}| j tjdttjdd||| d	S )zO
        Shared func to call any / all Cython GroupBy implementations.
        r   ztuple[np.ndarray, type]valsr|   c                   s   t | jrH r,tjdd tgd}|| } n| jtdd} ttj| } n*t| t	rd| j
jtdd} n| jtdd} | tjtfS )Nc                 S  s   t | st| S dS )NT)r/   rz   r   rQ   rQ   rR   r     r   z9GroupBy._bool_agg.<locals>.objs_to_bool.<locals>.<lambda>)ZotypesFrK  )r,   rC  r   Z	vectorizerz   rd  r   ndarrayr   r3   _dataviewint8)rw  r   ru  rQ   rR   objs_to_bool  s    
 

z'GroupBy._bool_agg.<locals>.objs_to_boolFri  r   rz   )r   	inferencenullabler|   c                 S  s.   |rt | jtdd| dkS | j|ddS d S )NFrK  r   )r4   rd  rz   )r   r~  r  rQ   rQ   rR   result_to_bool  s    z)GroupBy._bool_agg.<locals>.result_to_boolT)r  cython_dtype
needs_maskneeds_nullablepre_processingpost_processingrt  ru  )F)_get_cythonized_result
libgroupbyZgroup_any_allr   rC  r{  )rP   rt  ru  r}  r  rQ   r|  rR   	_bool_agg  s     

zGroupBy._bool_aggrM   r^   r|  c                 C  s   |  d|S )a  
        Return True if any value in the group is truthful, else False.

        Parameters
        ----------
        skipna : bool, default True
            Flag to ignore nan values during truth testing.

        Returns
        -------
        Series or DataFrame
            DataFrame or Series of boolean values, where a value is True if any element
            is True within its respective group, False otherwise.
        rI  r  rP   ru  rQ   rQ   rR   rI    s    zGroupBy.anyc                 C  s   |  d|S )a  
        Return True if all values in the group are truthful, else False.

        Parameters
        ----------
        skipna : bool, default True
            Flag to ignore nan values during truth testing.

        Returns
        -------
        Series or DataFrame
            DataFrame or Series of boolean values, where a value is True if all elements
            are True within its respective group, False otherwise.
        r)  r  r  rQ   rQ   rR   r)    s    zGroupBy.allc              	     s   |   }| jj\ } dk|jdkddd fdd}||}t| dd | |}W 5 Q R X |jdkr| jj|_	| j
|d	d
S )z
        Compute count of group, excluding missing values.

        Returns
        -------
        Series or DataFrame
            Count of values within each group.
        r   r   r   )bvaluesr|   c                   sr   | j dkr"t| dd @ }nt|  @ }tj| dd}rn|j dksTt|jd dksft|d S |S )Nr   r   )r   Zmax_binrl   r  r   )r   r/   reshaper   Zcount_level_2dr   rD  )r  ZmaskedZcountedr  Z	is_seriesr   r   rQ   rR   hfunc8  s    
zGroupBy.count.<locals>.hfuncru   Tr   
fill_value)rS  ro   r   r   rU  r   r]  rV  r   r   r  )rP   r
  r   r  rX  r   rQ   r  rR   rn  &  s    



zGroupBy.count)Zsee_alsoZcython)r  rZ  r  c                   sX   |  | t|r,ddlm} | ||dS | jd fdd d}|j| jdd	S d
S )a,  
        Compute mean of groups, excluding missing values.

        Parameters
        ----------
        numeric_only : bool, default True
            Include only float, int, boolean columns. If None, will attempt to use
            everything, then use only numeric data.

        engine : str, default None
            * ``'cython'`` : Runs the operation through C-extensions from cython.
            * ``'numba'`` : Runs the operation through JIT compiled code from numba.
            * ``None`` : Defaults to ``'cython'`` or globally setting
              ``compute.use_numba``

            .. versionadded:: 1.4.0

        engine_kwargs : dict, default None
            * For ``'cython'`` engine, there are no accepted ``engine_kwargs``
            * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil``
              and ``parallel`` dictionary keys. The values must either be ``True`` or
              ``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is
              ``{{'nopython': True, 'nogil': False, 'parallel': False}}``

            .. versionadded:: 1.4.0

        Returns
        -------
        pandas.Series or pandas.DataFrame
        %(see_also)s
        Examples
        --------
        >>> df = pd.DataFrame({'A': [1, 1, 2, 1, 2],
        ...                    'B': [np.nan, 2, 3, 4, 5],
        ...                    'C': [1, 2, 1, 1, 2]}, columns=['A', 'B', 'C'])

        Groupby one column and return the mean of the remaining columns in
        each group.

        >>> df.groupby('A').mean()
             B         C
        A
        1  3.0  1.333333
        2  4.0  1.500000

        Groupby two columns and return the mean of the remaining column.

        >>> df.groupby(['A', 'B']).mean()
                 C
        A B
        1 2.0  2.0
          4.0  1.0
        2 3.0  1.0
          5.0  2.0

        Groupby one column and return the mean of only particular column in
        the group.

        >>> df.groupby('A')['B'].mean()
        A
        1    3.0
        2    4.0
        Name: B, dtype: float64
        r   )sliding_meanZgroupby_meanmeanc                   s   t | j dS Nr  )rE   r  r   Znumeric_only_boolrQ   rR   r     r   zGroupBy.mean.<locals>.<lambda>r<  r  rM   r=  N)r  rH   pandas.core._numba.kernelsr  r#  r?  r@  rt   )rP   r  rZ  r  r  r   rQ   r  rR   r  T  s    I

zGroupBy.meanr  c                   s2   |  | | jd fdd d}|j| jd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 True
            Include only float, int, boolean columns. If None, will attempt to use
            everything, then use only numeric data.

        Returns
        -------
        Series or DataFrame
            Median of values within each group.
        medianc                   s   t | j dS r  )rE   r  r   r  rQ   rR   r     r   z GroupBy.median.<locals>.<lambda>r  rM   r=  )r  r?  r@  rt   )rP   r  r   rQ   r  rR   r    s    

zGroupBy.medianr   z
str | None)ddofrZ  r  c                 C  sP   t |r*ddlm} t| ||d|S | jtjdt	tj
dd |dS dS )	a  
        Compute standard deviation of groups, excluding missing values.

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

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

        engine : str, default None
            * ``'cython'`` : Runs the operation through C-extensions from cython.
            * ``'numba'`` : Runs the operation through JIT compiled code from numba.
            * ``None`` : Defaults to ``'cython'`` or globally setting
              ``compute.use_numba``

            .. versionadded:: 1.4.0

        engine_kwargs : dict, default None
            * For ``'cython'`` engine, there are no accepted ``engine_kwargs``
            * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil``
              and ``parallel`` dictionary keys. The values must either be ``True`` or
              ``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is
              ``{{'nopython': True, 'nogil': False, 'parallel': False}}``

            .. versionadded:: 1.4.0

        Returns
        -------
        Series or DataFrame
            Standard deviation of values within each group.
        r   sliding_varZgroupby_stdTc                 S  s
   t | S rN   )r   sqrtrw  r~  rQ   rQ   rR   r     r   zGroupBy.std.<locals>.<lambda>)needs_countsr  r  r  N)rH   r  r  r   r  r#  r  r  Z	group_varrC  float64)rP   r  rZ  r  r  rQ   rQ   rR   std  s    )
zGroupBy.stdc              
     s   t |r$ddlm} | ||d S  dkrP| tj}| jd fdd|dS  fd	d}|   | 	|W  5 Q R  S Q R X d
S )a  
        Compute variance of groups, excluding missing values.

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

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

        engine : str, default None
            * ``'cython'`` : Runs the operation through C-extensions from cython.
            * ``'numba'`` : Runs the operation through JIT compiled code from numba.
            * ``None`` : Defaults to ``'cython'`` or globally setting
              ``compute.use_numba``

            .. versionadded:: 1.4.0

        engine_kwargs : dict, default None
            * For ``'cython'`` engine, there are no accepted ``engine_kwargs``
            * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil``
              and ``parallel`` dictionary keys. The values must either be ``True`` or
              ``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is
              ``{{'nopython': True, 'nogil': False, 'parallel': False}}``

            .. versionadded:: 1.4.0

        Returns
        -------
        Series or DataFrame
            Variance of values within each group.
        r   r  Zgroupby_varr   varc                   s   t | j dS Nr  )rE   r  r   r  rQ   rR   r   4  r   zGroupBy.var.<locals>.<lambda>r  c                   s   | j  dS r  )r  r   r  rQ   rR   r   8  r   N)
rH   r  r  r#  r  r   r  r?  r   r5  )rP   r  rZ  r  r  r  r   rQ   r  rR   r     s$    )   

zGroupBy.varr  c                 C  s   | j |d}|jdkr*|t|   }n`|j| j }|  }|j	|}|j	|}|j
dd|f  t|j
dd|f   < |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.

        Returns
        -------
        Series or DataFrame
            Standard error of the mean of values within each group.
        r  r   N)r  r   r   r  rn  r  r   rn   uniqueZget_indexer_forrE  )rP   r  r   colscountsZresult_ilocsZcount_ilocsrQ   rQ   rR   sem<  s    
.zGroupBy.semc                 C  sV   | j  }t| jtr*| j|| jjd}n
| |}| jsH|d	 }| j
|ddS )z
        Compute group sizes.

        Returns
        -------
        DataFrame or Series
            Number of rows in each group as a Series if as_index is True
            or a DataFrame if as_index is False.
        r^   sizer   r  )ro   r  r   rt   rE   rs  r_   rk   renamereset_indexr  r   rQ   rQ   rR   r  Z  s    

zGroupBy.sizesum)fnamenoZmc)r  r7  rZ  r  c              	   C  sl   t |r"ddlm} | ||dS | |}t| dd | j||dtj	d}W 5 Q R X | j
|ddS d S )	Nr   )sliding_sumZgroupby_sumru   Taddr6  r  )rH   r  r  r#  r  r   r]  rA  r   r  r  )rP   r  r7  rZ  r  r  r   rQ   rQ   rR   r  u  s     	
zGroupBy.sumprod)r  r7  c                 C  s   |  |}| j||dtjdS )Nr  r6  )r  rA  r   r  rP   r  r7  rQ   rQ   rR   r    s    
   zGroupBy.prodminc                 C  s   | j ||dtjdS )Nr  r6  )rA  r   r  r  rQ   rQ   rR   r    s       zGroupBy.minmaxc                 C  s   | j ||dtjdS )Nr  r6  )rA  r   r  r  rQ   rQ   rR   r    s       zGroupBy.maxfirstc                 C  s$   d	ddddd}| j ||d|dS )
Nr   r   rx   rt   rl   c                 S  sH   dddd}t | tr&| j||dS t | tr8|| S tt| d S )NrE   r   c                 S  s&   | j t| j  }t|stjS |d S )z-Helper function for first item that isn't NA.r   rb  r0   r}   r   r+  r   ZarrrQ   rQ   rR   r    s    z2GroupBy.first.<locals>.first_compat.<locals>.firstr   r   r:   r[   rE   r   r   )rt   rl   r  rQ   rQ   rR   first_compat  s    

z#GroupBy.first.<locals>.first_compatr  r6  )r   rA  )rP   r  r7  r  rQ   rQ   rR   r    s    zGroupBy.firstlastc                 C  s$   d	ddddd}| j ||d|dS )
Nr   r   rx   r  c                 S  sH   dddd}t | tr&| j||dS t | tr8|| S tt| d S )NrE   r   c                 S  s&   | j t| j  }t|stjS |d S )z,Helper function for last item that isn't NA.r   r  r  rQ   rQ   rR   r    s    z/GroupBy.last.<locals>.last_compat.<locals>.lastr   r  )rt   rl   r  rQ   rQ   rR   last_compat  s    

z!GroupBy.last.<locals>.last_compatr  r6  )r   r  )rP   r  r7  r  rQ   rQ   rR   r    s    zGroupBy.lastr:   c                 C  s~   | j jdkrl| j}t|j}|s(td| jjd|jdddd}dd	d
dg}| j j	|| jj
|d}| |S | dd | jS )a  
        Compute open, high, low and close values of a group, excluding missing values.

        For multiple groupings, the result index will be a MultiIndex

        Returns
        -------
        DataFrame
            Open, high, low and close values within each group.
        r   zNo numeric types to aggregaterM  ohlcr   r   rN  openhighlowcloser[  c                 S  s   |   S rN   )r  r   rQ   rQ   rR   r   	  r   zGroupBy.ohlc.<locals>.<lambda>)rt   r   r   r+   rC  r7   ro   rO  r   Z_constructor_expanddimr   r  Z_apply_to_column_groupbysr   )rP   rt   Z
is_numericrF  Z	agg_namesr   rQ   rQ   rR   r    s.    
      
 zGroupBy.ohlcc              
     sV   |   D |  fdd}| jdkr8|jW  5 Q R  S | W  5 Q R  S Q R X d S )Nc                   s   | j f  S rN   )describer   rX   rQ   rR   r   	  r   z"GroupBy.describe.<locals>.<lambda>r   )r   r[   rl   r   Zunstack)rP   rX   r   rQ   r  rR   r  	  s
    

zGroupBy.describec                 O  s   ddl m} || |f||S )a<  
        Provide resampling when using a TimeGrouper.

        Given a grouper, the function resamples it according to a string
        "string" -> "frequency".

        See the :ref:`frequency aliases <timeseries.offset_aliases>`
        documentation for more details.

        Parameters
        ----------
        rule : str or DateOffset
            The offset string or object representing target grouper conversion.
        *args, **kwargs
            Possible arguments are `how`, `fill_method`, `limit`, `kind` and
            `on`, and other arguments of `TimeGrouper`.

        Returns
        -------
        Grouper
            Return a new grouper with our resampler appended.

        See Also
        --------
        Grouper : Specify a frequency to resample with when
            grouping by a key.
        DatetimeIndex.resample : Frequency conversion and resampling of
            time series.

        Examples
        --------
        >>> idx = pd.date_range('1/1/2000', periods=4, freq='T')
        >>> df = pd.DataFrame(data=4 * [range(2)],
        ...                   index=idx,
        ...                   columns=['a', 'b'])
        >>> df.iloc[2, 0] = 5
        >>> df
                            a  b
        2000-01-01 00:00:00  0  1
        2000-01-01 00:01:00  0  1
        2000-01-01 00:02:00  5  1
        2000-01-01 00:03:00  0  1

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

        >>> df.groupby('a').resample('3T').sum()
                                 a  b
        a
        0   2000-01-01 00:00:00  0  2
            2000-01-01 00:03:00  0  1
        5   2000-01-01 00:00:00  5  1

        Upsample the series into 30 second bins.

        >>> df.groupby('a').resample('30S').sum()
                            a  b
        a
        0   2000-01-01 00:00:00  0  1
            2000-01-01 00:00:30  0  0
            2000-01-01 00:01:00  0  1
            2000-01-01 00:01:30  0  0
            2000-01-01 00:02:00  0  0
            2000-01-01 00:02:30  0  0
            2000-01-01 00:03:00  0  1
        5   2000-01-01 00:02:00  5  1

        Resample by month. Values are assigned to the month of the period.

        >>> df.groupby('a').resample('M').sum()
                    a  b
        a
        0   2000-01-31  0  3
        5   2000-01-31  5  1

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

        >>> df.groupby('a').resample('3T', closed='right').sum()
                                 a  b
        a
        0   1999-12-31 23:57:00  0  1
            2000-01-01 00:00:00  0  2
        5   2000-01-01 00:00:00  5  1

        Downsample the series into 3 minute bins and close the right side of
        the bin interval, but label each bin using the right edge instead of
        the left.

        >>> df.groupby('a').resample('3T', closed='right', label='right').sum()
                                 a  b
        a
        0   2000-01-01 00:00:00  0  1
            2000-01-01 00:03:00  0  2
        5   2000-01-01 00:03:00  5  1
        r   )get_resampler_for_grouping)Zpandas.core.resampler  )rP   ZrulerW   rX   r  rQ   rQ   rR   resample	  s    bzGroupBy.resamplec                 O  s,   ddl m} || jf|| j| jd|S )zV
        Return a rolling grouper, providing rolling functionality per group.
        r   )RollingGroupby)_grouperZ	_as_index)pandas.core.windowr  r   ro   rk   )rP   rW   rX   r  rQ   rQ   rR   rollings	  s    zGroupBy.rollingc                 O  s(   ddl m} || jf|d| ji|S )zc
        Return an expanding grouper, providing expanding
        functionality per group.
        r   )ExpandingGroupbyr  )r  r  r   ro   )rP   rW   rX   r  rQ   rQ   rR   	expanding	  s    zGroupBy.expandingc                 O  s(   ddl m} || jf|d| ji|S )zO
        Return an ewm grouper, providing ewm functionality per group.
        r   )ExponentialMovingWindowGroupbyr  )r  r  r   ro   )rP   rW   rX   r  rQ   rQ   rR   ewm	  s    zGroupBy.ewmzLiteral[('ffill', 'bfill')])	directionc                   s   |dkrd}| j j\}}}tj|ddjtjdd}|dkrJ|ddd }ttj||||| j	d d	d	d
 fdd}| j
}| jdkr|j}|j}||}	||	}
t|
tr|j|
_| |
S )a  
        Shared function for `pad` and `backfill` to call Cython method.

        Parameters
        ----------
        direction : {'ffill', 'bfill'}
            Direction passed to underlying Cython function. `bfill` will cause
            values to be filled backwards. `ffill` and any other values will
            default to a forward fill
        limit : int, default None
            Maximum number of consecutive values to fill. If `None`, this
            method will convert to -1 prior to passing to Cython

        Returns
        -------
        `Series` or `DataFrame` with filled values

        See Also
        --------
        pad : Returns Series with minimum number of char in object.
        backfill : Backward fill the missing values in the dataset.
        Nr   Z	mergesort)kindFrK  bfill)r   sorted_labelsr  limitrm   r   rL  c                   s   t | }| jdkr<tj| jtjd} ||d t| |S t| tj	r\tj| j| j
d}nt| j| j| j
d}tt| D ]F}tj| jd tjd} ||| d t| | |||d d f< q~|S d S )Nr   rB  )r`  r   )r/   r   r   r  rD  rm  r   r  r   rx  rC  r   _emptyr   r}   )r   r   r   r`  iZcol_funcrQ   rR   blk_func	  s    

zGroupBy._fill.<locals>.blk_funcr   )ro   r   r   r$  rd  rm  r   r  Zgroup_fillna_indexerrm   r   rl   r   Z_mgrr[   r   r   rE   r_   r	  )rP   r  r  r  r   r  r  rt   mgrres_mgrZnew_objrQ   r  rR   _fill	  s0    	



zGroupBy._fillc                 C  s   | j d|dS )a:  
        Forward fill the values.

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

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

        See Also
        --------
        Series.ffill: Returns Series with minimum number of char in object.
        DataFrame.ffill: Object with missing values filled or None if inplace=True.
        Series.fillna: Fill NaN values of a Series.
        DataFrame.fillna: Fill NaN values of a DataFrame.
        ffillr  r  rP   r  rQ   rQ   rR   r  	  s    zGroupBy.ffillc                 C  s   t jdtt d | j|dS )NzMpad is deprecated and will be removed in a future version. Use ffill instead.
stacklevelr  )warningswarnFutureWarningr%   r  r  rQ   rQ   rR   pad
  s    zGroupBy.padc                 C  s   | j d|dS )a/  
        Backward fill the values.

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

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

        See Also
        --------
        Series.bfill :  Backward fill the missing values in the dataset.
        DataFrame.bfill:  Backward fill the missing values in the dataset.
        Series.fillna: Fill NaN values of a Series.
        DataFrame.fillna: Fill NaN values of a DataFrame.
        r  r  r  r  rQ   rQ   rR   r  
  s    zGroupBy.bfillc                 C  s   t jdtt d | j|dS )NzRbackfill is deprecated and will be removed in a future version. Use bfill instead.r  r  )r  r  r  r%   r  r  rQ   rQ   rR   backfill3
  s    zGroupBy.backfillzPositionalIndexer | tuplezLiteral[('any', 'all', None)])r   rm   r|   c              
   C  s*  |s|    | |}| jj\}}}||dk@ }| |}| jsR|W  5 Q R  S | jj}| jdkr|||  |_| j	st
|tr||}| |}n|||  |_| jr|j| jdn|W  5 Q R  S Q R X t|std|dkrtd| dtt|}|dkr|nd| }| jj|| jd}	| jd	kr\| jd	kr\| jj}
|
|
|	j }n0dd
lm} ||	| j| j| j| j| jd\}}}|	j|| j| j| jd}| || }}||k j }t!|r|" rt#j$|j%|< t!| jt!|	kst!|t!| jjkr| jj|_n|| jj}|S )ae	  
        Take the nth row from each group if n is an int, otherwise a subset of rows.

        Can be either a call or an index. dropna is not available with index notation.
        Index notation accepts a comma separated list of integers and slices.

        If dropna, will take the nth non-null row, dropna is either
        'all' or 'any'; this is equivalent to calling dropna(how=dropna)
        before the groupby.

        Parameters
        ----------
        n : int, slice or list of ints and slices
            A single nth value for the row or a list of nth values or slices.

            .. versionchanged:: 1.4.0
                Added slice and lists containing slices.
                Added index notation.

        dropna : {'any', 'all', None}, default None
            Apply the specified dropna operation before counting which row is
            the nth row. Only supported if n is an int.

        Returns
        -------
        Series or DataFrame
            N-th value within each group.
        %(see_also)s
        Examples
        --------

        >>> df = pd.DataFrame({'A': [1, 1, 2, 1, 2],
        ...                    'B': [np.nan, 2, 3, 4, 5]}, columns=['A', 'B'])
        >>> g = df.groupby('A')
        >>> g.nth(0)
             B
        A
        1  NaN
        2  3.0
        >>> g.nth(1)
             B
        A
        1  2.0
        2  5.0
        >>> g.nth(-1)
             B
        A
        1  4.0
        2  5.0
        >>> g.nth([0, 1])
             B
        A
        1  NaN
        1  2.0
        2  3.0
        2  5.0
        >>> g.nth(slice(None, -1))
             B
        A
        1  NaN
        1  2.0
        2  3.0

        Index notation may also be used

        >>> g.nth[0, 1]
             B
        A
        1  NaN
        1  2.0
        2  3.0
        2  5.0
        >>> g.nth[:-1]
             B
        A
        1  NaN
        1  2.0
        2  3.0

        Specifying `dropna` allows count ignoring ``NaN``

        >>> g.nth(0, dropna='any')
             B
        A
        1  2.0
        2  3.0

        NaNs denote group exhausted when using dropna

        >>> g.nth(3, dropna='any')
            B
        A
        1 NaN
        2 NaN

        Specifying `as_index=False` in `groupby` keeps the original index.

        >>> df.groupby('A', as_index=False).nth(1)
           A    B
        1  1  2.0
        4  2  5.0
        r   r   r   z4dropna option only supported for an integer argumentrH  z_For a DataFrame or Series groupby.nth, dropna must be either None, 'any' or 'all', (was passed z).)r;  rl   Nr   )r   rl   rr   rv   rs   )rk   rv   rl   )&r   "_make_mask_from_positional_indexerro   r   _mask_selected_objrk   r   rl   r   ru   r   rA   r   r  r  rv   r   r)   r   r   rx   rt   rm   rq   rr   isinr   r   rs   rM   r  r   r   r}   rI  r   r+  loc)rP   r   rm   r   r  r   r`  r   max_lenZdroppedrl   ro   r   ZgrbZsizesr   rQ   rQ   rR   r   >
  sj    n




*

	   
zGroupBy.nth      ?linearinterpolationc                   sl  dddddddddfd	d
t |}|r8|g}tj|tjd}| jj\}}t|ttj	||d t|dkr|
 d nd}t|dk||ddd fdd}| j}	|	jdk}
|  }|j|dd}|
s2t|jt|jkr2tt| d t|jdkr2|j|dd td|
rD| |}n
|	|}|r^| |S | j||dS )a  
        Return group values at the given quantile, a la numpy.percentile.

        Parameters
        ----------
        q : float or array-like, default 0.5 (50% quantile)
            Value(s) between 0 and 1 providing the quantile(s) to compute.
        interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}
            Method to use when the desired quantile falls between two points.

        Returns
        -------
        Series or DataFrame
            Return type determined by caller of GroupBy object.

        See Also
        --------
        Series.quantile : Similar method for Series.
        DataFrame.quantile : Similar method for DataFrame.
        numpy.percentile : NumPy method to compute qth percentile.

        Examples
        --------
        >>> df = pd.DataFrame([
        ...     ['a', 1], ['a', 2], ['a', 3],
        ...     ['b', 1], ['b', 3], ['b', 5]
        ... ], columns=['key', 'val'])
        >>> df.groupby('key').quantile()
            val
        key
        a    2.0
        b    3.0
        r   z"tuple[np.ndarray, np.dtype | None]rv  c                 S  s   t | rtdd }t| jrLt| tr:| jttj	d}n| }ttj
}nt| jrrt| trr| jttj	d}nt| jrtd}t| t}n`t| jrtd}t| t}n:t| trt| rttj}| jttj	d}n
t| }||fS )Nz7'quantile' cannot be performed against 'object' dtypes!)rC  Zna_valuezdatetime64[ns]ztimedelta64[ns])r,   r   r*   rC  r   r6   r  floatr   r+  ra  r&   r'   Zasarrayrd  r.   r(   r  )rw  r~  r`  rQ   rQ   rR   pre_processor'  s.    






z'GroupBy.quantile.<locals>.pre_processorri  znp.dtype | None)rw  r~  r|   c                   s"   |rt |r dks| |} | S )N>   r  midpoint)r*   rd  r  r  rQ   rR   post_processorD  s    
z(GroupBy.quantile.<locals>.post_processorrB  )r   r  r  r   r   r   rL  c           
        s   t | }| \}}d}|jdkrB|jd }t|tf}n}tj|ftjd}||f}t|j	tj
dd}|jdkr |d |||d n.t|D ]$}	 ||	 ||	 ||	 ||	 d q|jdkr|d}n|| }||S )	Nr   r  r   rB  FrK  )r   r   Zsort_indexerK)r/   r   rD  r   Zbroadcast_tor}   r  r  Zlexsortrd  rm  r   r  r  )
r   r   rw  r~  ncolsZshaped_labelsr`  orderZsort_arrr  )r   labels_for_lexsortr   nqsr  r  rQ   rR   r  a  s*    

 

"
z"GroupBy.quantile.<locals>.blk_funcTrR  quantileF*All columns were dropped in grouped_reducer  )r-   r   rb  r  ro   r   r}   r   r  Zgroup_quantiler  rf  r   r   rS  rU  itemsr3  r   r   rV  r   r  )rP   qr  Zorig_scalarr  r  r   Zna_label_for_sortingr  rt   rW  r  r  r.  rQ   )r   r  r  r   r  r  r  rR   r    sD    $   


zGroupBy.quantilerj  c              
   C  sX   |   F | jj}| j| jjd |tjd}|s>| jd | }|W  5 Q R  S Q R X dS )a)  
        Number each group from 0 to the number of groups - 1.

        This is the enumerative complement of cumcount.  Note that the
        numbers given to the groups match the order in which the groups
        would be seen when iterating over the groupby object, not the
        order they are first observed.

        Parameters
        ----------
        ascending : bool, default True
            If False, number in reverse, from number of group - 1 to 0.

        Returns
        -------
        Series
            Unique numbers for each group.

        See Also
        --------
        .cumcount : Number the rows in each group.

        Examples
        --------
        >>> df = pd.DataFrame({"A": list("aaabba")})
        >>> df
           A
        0  a
        1  a
        2  a
        3  b
        4  b
        5  a
        >>> df.groupby('A').ngroup()
        0    0
        1    0
        2    0
        3    1
        4    1
        5    0
        dtype: int64
        >>> df.groupby('A').ngroup(ascending=False)
        0    1
        1    1
        2    1
        3    0
        4    0
        5    1
        dtype: int64
        >>> df.groupby(["A", [1,1,2,3,2,1]]).ngroup()
        0    0
        1    0
        2    1
        3    3
        4    2
        5    0
        dtype: int64
        r   rB  r   N)	r   r   r   rs  ro   r   r   ra  r   )rP   rj  r   r   rQ   rQ   rR   ngroup  s    =

  zGroupBy.ngroupc              
   C  sF   |   4 | j| j}| j|d}| ||W  5 Q R  S Q R X dS )a  
        Number each item in each group from 0 to the length of that group - 1.

        Essentially this is equivalent to

        .. code-block:: python

            self.apply(lambda x: pd.Series(np.arange(len(x)), x.index))

        Parameters
        ----------
        ascending : bool, default True
            If False, number in reverse, from length of group - 1 to 0.

        Returns
        -------
        Series
            Sequence number of each element within each group.

        See Also
        --------
        .ngroup : Number the groups themselves.

        Examples
        --------
        >>> df = pd.DataFrame([['a'], ['a'], ['a'], ['b'], ['b'], ['a']],
        ...                   columns=['A'])
        >>> df
           A
        0  a
        1  a
        2  a
        3  b
        4  b
        5  a
        >>> df.groupby('A').cumcount()
        0    0
        1    1
        2    2
        3    0
        4    1
        5    3
        dtype: int64
        >>> df.groupby('A').cumcount(ascending=False)
        0    3
        1    2
        2    1
        3    1
        4    0
        5    0
        dtype: int64
        r  N)r   r   r   rl   rr  rs  )rP   rj  r   Z	cumcountsrQ   rQ   rR   cumcount  s    7
zGroupBy.cumcountaveragekeep)r>  rj  	na_optionpctrl   c                   sb   |dkrd}t |||||d dkrLdd< |  fddS | jdd
 dS )a_
  
        Provide the rank of values within each group.

        Parameters
        ----------
        method : {'average', 'min', 'max', 'first', 'dense'}, default 'average'
            * average: average rank of group.
            * min: lowest rank in group.
            * max: highest rank in group.
            * first: ranks assigned in order they appear in the array.
            * dense: like 'min', but rank always increases by 1 between groups.
        ascending : bool, default True
            False for ranks by high (1) to low (N).
        na_option : {'keep', 'top', 'bottom'}, default 'keep'
            * keep: leave NA values where they are.
            * top: smallest rank if ascending.
            * bottom: smallest rank if descending.
        pct : bool, default False
            Compute percentage rank of data within each group.
        axis : int, default 0
            The axis of the object over which to compute the rank.

        Returns
        -------
        DataFrame with ranking of values within each group
        %(see_also)s
        Examples
        --------
        >>> df = pd.DataFrame(
        ...     {
        ...         "group": ["a", "a", "a", "a", "a", "b", "b", "b", "b", "b"],
        ...         "value": [2, 4, 2, 3, 5, 1, 2, 4, 1, 5],
        ...     }
        ... )
        >>> df
          group  value
        0     a      2
        1     a      4
        2     a      2
        3     a      3
        4     a      5
        5     b      1
        6     b      2
        7     b      4
        8     b      1
        9     b      5
        >>> for method in ['average', 'min', 'max', 'dense', 'first']:
        ...     df[f'{method}_rank'] = df.groupby('group')['value'].rank(method)
        >>> df
          group  value  average_rank  min_rank  max_rank  dense_rank  first_rank
        0     a      2           1.5       1.0       2.0         1.0         1.0
        1     a      4           4.0       4.0       4.0         3.0         4.0
        2     a      2           1.5       1.0       2.0         1.0         2.0
        3     a      3           3.0       3.0       3.0         2.0         3.0
        4     a      5           5.0       5.0       5.0         4.0         5.0
        5     b      1           1.5       1.0       2.0         1.0         1.0
        6     b      2           3.0       3.0       3.0         2.0         3.0
        7     b      4           4.0       4.0       4.0         3.0         4.0
        8     b      1           1.5       1.0       2.0         1.0         2.0
        9     b      5           5.0       5.0       5.0         4.0         5.0
        >   r  topbottomz3na_option must be one of 'keep', 'top', or 'bottom')ties_methodrj  r   r  r   r  r>  c                   s   | j f  ddS )NF)rl   r  )rankr   rl   rX   rQ   rR   r   q  r   zGroupBy.rank.<locals>.<lambda>r  F)r  rl   )r  )r   popr[   rY  )rP   r>  rj  r   r  rl   r   rQ   r  rR   r    s&    H zGroupBy.rankc                   s<   t d|ddg  dkr0|  fddS | jdS )zq
        Cumulative product for each group.

        Returns
        -------
        Series or DataFrame
        cumprodr  ru  r   c                   s   | j f d iS Nrl   )r  r   r  rQ   rR   r     r   z!GroupBy.cumprod.<locals>.<lambda>)r  nvZvalidate_groupby_funcr[   rY  rP   rl   rW   rX   rQ   r  rR   r  z  s    zGroupBy.cumprodc                   s<   t d|ddg  dkr0|  fddS | jdS )zm
        Cumulative sum for each group.

        Returns
        -------
        Series or DataFrame
        rk  r  ru  r   c                   s   | j f d iS r	  )rk  r   r  rQ   rR   r     r   z GroupBy.cumsum.<locals>.<lambda>)rk  r
  r  rQ   r  rR   rk    s    zGroupBy.cumsumc                   s6   | dd} dkr&|  fddS | jdd|dS )	zm
        Cumulative min for each group.

        Returns
        -------
        Series or DataFrame
        ru  Tr   c                   s   t j|  S rN   )r   Zminimum
accumulater   r   rQ   rR   r     r   z GroupBy.cummin.<locals>.<lambda>cumminFr  ru  r   r[   rY  rP   rl   rX   ru  rQ   r   rR   r    s    zGroupBy.cumminc                   s6   | dd} dkr&|  fddS | jdd|dS )	zm
        Cumulative max for each group.

        Returns
        -------
        Series or DataFrame
        ru  Tr   c                   s   t j|  S rN   )r   maximumr  r   r   rQ   rR   r     r   z GroupBy.cummax.<locals>.<lambda>cummaxFr  r  r  rQ   r   rR   r    s    zGroupBy.cummaxznp.dtype)	base_funcr  r  r  r  r  c	                   s0  	 |}rtstdr2ts2td	j}
|
j\}} j}t |d ddd 	f
dd}	j}|jdk}		 }|r|
 }|j|d	d
}|s
t|jt|jkr
|dd}tt	| t|jdkr
|j|dd
 td|r	|}n
||}	|S )ap  
        Get result for Cythonized functions.

        Parameters
        ----------
        base_func : callable, Cythonized function to be called
        cython_dtype : np.dtype
            Type of the array that will be modified by the Cython call.
        numeric_only : bool, default True
            Whether only numeric datatypes should be computed
        needs_counts : bool, default False
            Whether the counts should be a part of the Cython call
        needs_mask : bool, default False
            Whether boolean mask needs to be part of the Cython call
            signature
        needs_nullable : bool, default False
            Whether a bool specifying if the input is nullable is part
            of the Cython call signature
        pre_processing : function, default None
            Function to be applied to `values` prior to passing to Cython.
            Function should return a tuple where the first element is the
            values to be passed to Cython and the second element is an optional
            type which the values should be converted to after being returned
            by the Cython operation. This function is also responsible for
            raising a TypeError if the values have an invalid type. Raises
            if `needs_values` is False.
        post_processing : function, default None
            Function to be applied to result of Cython function. Should accept
            an array of values as the first argument and type inferences as its
            second argument, i.e. the signature should be
            (ndarray, Type). If `needs_nullable=True`, a third argument should be
            `nullable`, to allow for processing specific to nullable values.
        **kwargs : dict
            Extra arguments to be passed back to Cython funcs

        Returns
        -------
        `Series` or `DataFrame`  with filled values
        z%'post_processing' must be a callable!z$'pre_processing' must be a callable!)r   r   rL  c           
        sv  | j } | jdkrdn| jd }tj| d}||f}t |d}d }rptj	jtjd}t||d}| }r|\}}|j	dd}|jdkr|d}t||d}rt
| tj}|jdkr|d	d}t||d
}rt| t}t||d}|f  | jdkrD|jd dks4t|j|d d df }rpi }	rbt| t|	d< ||f|	}|j S )Nr   rB  )r`  )r  FrK  )r   r   )r   r   )r   )r  r   r  )r   r   rD  r   zerosr  r   r   ra  rd  r/   rz  Zuint8r   r3   r   )
r   r  r   r   Z
inferencesr  rw  r   Zis_nullableZ	pp_kwargs
r  r  rX   r  r  r  r   r  r  rP   rQ   rR   r     sD    




z0GroupBy._get_cythonized_result.<locals>.blk_funcr   TrR  Zgroup_ r   Fr  )r  r  r   ro   r   rZ   r   r   r   rS  rT  rU  r}   r  replacer3  r   r   rV  r   r  )rP   r  r  r  r  r  r  r  r  rX   ro   r  r   r;  r  rt   rW  r  r  Zhowstrr`  rQ   r  rR   r    s8    4
&2

zGroupBy._get_cythonized_resultc                   s   dk	s dkr(|   fddS | jj\}}}tjt|tjd}t||| | j	}	|	j
| j|	j| j |fidd}
|
S )u  
        Shift each group by periods observations.

        If freq is passed, the index will be increased using the periods and the freq.

        Parameters
        ----------
        periods : int, default 1
            Number of periods to shift.
        freq : str, optional
            Frequency string.
        axis : axis to shift, default 0
            Shift direction.
        fill_value : optional
            The scalar value to use for newly introduced missing values.

        Returns
        -------
        Series or DataFrame
            Object shifted within each group.

        See Also
        --------
        Index.shift : Shift values of Index.
        tshift : Shift the time index, using the index’s frequency
            if available.
        Nr   c                   s   |   S rN   )shiftr   rl   r  freqperiodsrQ   rR   r   o  r   zGroupBy.shift.<locals>.<lambda>rB  T)r  Z
allow_dups)r[   ro   r   r   r  r}   ra  r  Zgroup_shift_indexerr   Z_reindex_with_indexersrl   r   )rP   r  r  rl   r  r  r   r   Zres_indexerrt   r.  rQ   r  rR   r  P  s    zGroupBy.shiftr  c           	        s|   dk	s dkr*|   fddS dkr:ddt| d}|j| jj| jd}|j| jd}|| d	 S )
z
        Calculate pct_change of each value to previous entry in group.

        Returns
        -------
        Series or DataFrame
            Percentage changes within each group.
        Nr   c                   s   | j  dS )N)r  fill_methodr  r  rl   )
pct_changer   rl   r  r  r  r  rQ   rR   r     s   z$GroupBy.pct_change.<locals>.<lambda>r  r  r   )r  r  rl   r   )r[   r`   rM   ro   codesrl   r  )	rP   r  r  r  r  rl   ZfilledZfill_grpZshiftedrQ   r  rR   r    s    	zGroupBy.pct_change   c                 C  s"   |    | td|}| |S )a  
        Return first n rows of each group.

        Similar to ``.apply(lambda x: x.head(n))``, but it returns a subset of rows
        from the original DataFrame with original index and order preserved
        (``as_index`` flag is ignored).

        Parameters
        ----------
        n : int
            If positive: number of entries to include from start of each group.
            If negative: number of entries to exclude from end of each group.

        Returns
        -------
        Series or DataFrame
            Subset of original Series or DataFrame as determined by n.
        %(see_also)s
        Examples
        --------

        >>> df = pd.DataFrame([[1, 2], [1, 4], [5, 6]],
        ...                   columns=['A', 'B'])
        >>> df.groupby('A').head(1)
           A  B
        0  1  2
        2  5  6
        >>> df.groupby('A').head(-1)
           A  B
        0  1  2
        Nr   r  slicer  rP   r   r   rQ   rQ   rR   head  s    #zGroupBy.headc                 C  s4   |    |r | t| d}n
| g }| |S )a  
        Return last n rows of each group.

        Similar to ``.apply(lambda x: x.tail(n))``, but it returns a subset of rows
        from the original DataFrame with original index and order preserved
        (``as_index`` flag is ignored).

        Parameters
        ----------
        n : int
            If positive: number of entries to include from end of each group.
            If negative: number of entries to exclude from start of each group.

        Returns
        -------
        Series or DataFrame
            Subset of original Series or DataFrame as determined by n.
        %(see_also)s
        Examples
        --------

        >>> df = pd.DataFrame([['a', 1], ['a', 2], ['b', 1], ['b', 2]],
        ...                   columns=['A', 'B'])
        >>> df.groupby('A').tail(1)
           A  B
        1  a  2
        3  b  2
        >>> df.groupby('A').tail(-1)
           A  B
        1  a  2
        3  b  2
        Nr"  r$  rQ   rQ   rR   tail  s
    $
zGroupBy.tail)r   r|   c                 C  sD   | j jd }||dk@ }| jdkr,| j| S | jjdd|f S dS )a  
        Return _selected_obj with mask applied to the correct axis.

        Parameters
        ----------
        mask : np.ndarray
            Boolean mask to apply.

        Returns
        -------
        Series or DataFrame
            Filtered _selected_obj.
        r   r   N)ro   r   rl   r   rE  )rP   r   r  rQ   rQ   rR   r    s
    

zGroupBy._mask_selected_objr   )r  r  r  r|   c                 C  s  | j j}t|dkr|S | jr"|S tdd |D s8|S dd |D }| j j}|dk	rj|| |dg }tj||d	 \}}| j
r| j| j|dd	d
|i}	|jf |	S dd t|D }
t|
 \}}|jt|dd}|| j jj|d	|d}|j|d}|jddS )aI  
        If we have categorical groupers, then we might want to make sure that
        we have a fully re-indexed output to the levels. This means expanding
        the output space to accommodate all values in the cartesian product of
        our groups, regardless of whether they were observed in the data or
        not. This will expand the output space if there are missing groups.

        The method returns early without modifying the input if the number of
        groupings is less than 2, self.observed == True or none of the groupers
        are categorical.

        Parameters
        ----------
        output : Series or DataFrame
            Object resulting from grouping and applying an operation.
        fill_value : scalar, default np.NaN
            Value to use for unobserved categories if self.observed is False.
        qs : np.ndarray[float64] or None, default None
            quantile values, only relevant for quantile.

        Returns
        -------
        Series or DataFrame
            Object (potentially) re-indexed to include all possible groups.
        r   c                 s  s   | ]}t |jttfV  qd S rN   )r   Zgrouping_vectorr5   rA   r   pingrQ   rQ   rR   r   3  s   z*GroupBy._reindex_output.<locals>.<genexpr>c                 S  s   g | ]
}|j qS rQ   )Zgroup_indexr'  rQ   rQ   rR   r   9  s     z+GroupBy._reindex_output.<locals>.<listcomp>N)r   r   Fr  c                 s  s"   | ]\}}|j r||jfV  qd S rN   )r   r_   )r   r  r(  rQ   rQ   rR   r   U  s     )r   rl   )r   r  )rr   T)drop)ro   r   r}   ru   rI  r   appendrC   from_productZ	sortlevelrk   rt   Z_get_axis_namerl   r   r1  r   r)  r   Z	set_indexr   r  )rP   r  r  r  r   Zlevels_listr   r   r   dZin_axis_grpsZg_numsZg_namesrQ   rQ   rR   r  	  sH     

     zGroupBy._reindex_outputz
int | Nonezfloat | NonezSequence | Series | NonezRandomState | None)r   fracr  weightsrandom_statec                 C  s   t |||}|dk	r*t j| j|| jd}t|}| j| j| j}g }	|D ]r\}
}| j	|
 }t
|}|dk	rv|}n|dk	stt|| }t j ||||dkrdn|| |d}|	||  qNt|	}	| jj|	| jdS )a  
        Return a random sample of items from each group.

        You can use `random_state` for reproducibility.

        .. versionadded:: 1.1.0

        Parameters
        ----------
        n : int, optional
            Number of items to return for each group. Cannot be used with
            `frac` and must be no larger than the smallest group unless
            `replace` is True. Default is one if `frac` is None.
        frac : float, optional
            Fraction of items to return. Cannot be used with `n`.
        replace : bool, default False
            Allow or disallow sampling of the same row more than once.
        weights : list-like, optional
            Default None results in equal probability weighting.
            If passed a list-like then values must have the same length as
            the underlying DataFrame or Series object and will be used as
            sampling probabilities after normalization within each group.
            Values must be non-negative with at least one positive element
            within each group.
        random_state : int, array-like, BitGenerator, np.random.RandomState, np.random.Generator, optional
            If int, array-like, or BitGenerator, seed for random number generator.
            If np.random.RandomState or np.random.Generator, use as given.

            .. versionchanged:: 1.4.0

                np.random.Generator objects now accepted

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

        See Also
        --------
        DataFrame.sample: Generate random samples from a DataFrame object.
        numpy.random.choice: Generate a random sample from a given 1-D numpy
            array.

        Examples
        --------
        >>> df = pd.DataFrame(
        ...     {"a": ["red"] * 2 + ["blue"] * 2 + ["black"] * 2, "b": range(6)}
        ... )
        >>> df
               a  b
        0    red  0
        1    red  1
        2   blue  2
        3   blue  3
        4  black  4
        5  black  5

        Select one row at random for each distinct value in column a. The
        `random_state` argument can be used to guarantee reproducibility:

        >>> df.groupby("a").sample(n=1, random_state=1)
               a  b
        4  black  4
        2   blue  2
        1    red  1

        Set `frac` to sample fixed proportions rather than counts:

        >>> df.groupby("a")["b"].sample(frac=0.5, random_state=2)
        5    5
        2    2
        0    0
        Name: b, dtype: int64

        Control sample probabilities within groups by setting weights:

        >>> df.groupby("a").sample(
        ...     n=1,
        ...     weights=[1, 1, 1, 0, 0, 1],
        ...     random_state=1,
        ... )
               a  b
        5  black  5
        2   blue  2
        0    red  0
        Nr   )r  r  r.  r/  )sampleZprocess_sampling_sizeZpreprocess_weightsr   rl   r   r/  ro   r   r   r}   r   roundr*  r   r   r   )rP   r   r-  r  r.  r/  r  Zweights_arrZgroup_iteratorZsampled_indicesr   rt   Zgrp_indicesZ
group_sizeZsample_sizeZ
grp_samplerQ   rQ   rR   r0  g  s6    `  


zGroupBy.sample)Nr   NNNNTTTFFFT)F)N)F)N)Tr   )r   )Tr   )T)T)T)r   NN)r   NN)r   )Fr   )Fr   )Fr   )Fr   )N)N)N)N)N)N)r  r  )T)T)r  Tr  Fr   )r   )r   )r   )r   )r   Nr   N)r   r  NNr   )r!  )r!  )NNFNN)`rZ   rd   re   rf   r   r   rS   rc   r   r   r   r   r   r   r   r   r   r  r  r	  r  r  r  r#  r%  r&  r!   _apply_docsformatr[   r   r5  rA  rG  r?  rY  r_  r^  rh  rr  r   rs  r  r"   _common_see_alsorI  r)  rn  r   r  r  r  r  r  r  r  r$   _groupby_agg_method_templater  r  r  r  r  r  r  r:   r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  rk  r  r  r  r  r  r%  r&  r  r   NaNr  r0  __classcell__rQ   rQ   r   rR   rL      s  
C             ,:
	(
C6*
' 
6"
 (2  1
".+T  5  9 	!

eP		 C D:    [ -$)]    rL   TFr;   r   rx   r   rz   )rt   byrl   ro   rk   rv   rp   rw   ru   rs   rm   r|   c                 C  sj   t | trddlm} |}n*t | tr8ddlm} |}ntd|  || |||||||||	|
|||dS )Nr   )SeriesGroupBy)DataFrameGroupByzinvalid type: r   )r   rE   Zpandas.core.groupby.genericr9  r:   r:  r   )rt   r8  rl   rr   ro   rn   r   rk   rv   rp   rw   ru   rs   rm   r9  r   r:  rQ   rQ   rR   get_groupby  s.    

r;  rB   znpt.NDArray[np.float64]rC   )r4  r  r|   c                   s   t | | jrvtt| } t| \}}t| j|g } fdd| jD t	
|t | g }t||| jdg d}nt| |g}|S )a  
    Insert the sequence 'qs' of quantiles as the inner-most level of a MultiIndex.

    The quantile level in the MultiIndex is a repeated copy of 'qs'.

    Parameters
    ----------
    idx : Index
    qs : np.ndarray[float64]

    Returns
    -------
    MultiIndex
    c                   s   g | ]}t | qS rQ   )r   rl  )r   r   r  rQ   rR   r   -  s     z*_insert_quantile_level.<locals>.<listcomp>N)r   r   r   )r}   Z	_is_multir   rC   rB   Z	factorizer   r   r   r   re  r   r+  )r4  r  Z	lev_codesZlevr   r   mirQ   r<  rR   r    s    
&r  r]   r   )r;  r|   c                 C  s,   t jd| j d| d| dtt d d S )NzDropping invalid columns in rJ  zQ is deprecated. In a future version, a TypeError will be raised. Before calling .z=, select only columns which should be valid for the function.r  )r  r  rZ   r  r%   )clsr;  rQ   rQ   rR   r3  4  s
    r3  )Nr   NNNNTTTFFFT)rf   
__future__r   
contextlibr   r   	functoolsr   r   r   textwrapr   r   typingr   r   r	   r
   r   r   r   r   r   r   r   r   r  Znumpyr   Zpandas._config.configr   Zpandas._libsr   r   Zpandas._libs.groupbyZ_libsrM   r  Zpandas._typingr   r   r   r   r   r   r   r   Zpandas.compat.numpyr   r  Zpandas.errorsr    Zpandas.util._decoratorsr!   r"   r#   r$   Zpandas.util._exceptionsr%   Zpandas.core.dtypes.commonr&   r'   r(   r)   r*   r+   r,   r-   r.   Zpandas.core.dtypes.missingr/   r0   Zpandas.corer1   Zpandas.core._numbar2   Zpandas.core.algorithmscorer   Zpandas.core.arraysr3   r4   r5   r6   Zpandas.core.baser7   r8   r9   Zpandas.core.commoncommonr   Zpandas.core.framer:   Zpandas.core.genericr;   Zpandas.core.groupbyr<   r=   r>   Zpandas.core.groupby.indexingr?   r@   Zpandas.core.indexes.apirA   rB   rC   Zpandas.core.internals.blocksrD   Zpandas.core.sampler0  Zpandas.core.seriesrE   Zpandas.core.sortingrF   Zpandas.core.util.numba_rG   rH   r4  r2  r5  r   Z_transform_templateZ_agg_templaterK   Z_KeysArgTyperg   r   rL   r;  r  r3  rQ   rQ   rQ   rR   <module>   s   8(
,	5+ 4|M
	 J                                      (/