B
    W0d<                @  s  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 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.m/Z0 ddl1m2Z2 ddl3m4Z4m5Z5m6Z6m7Z7 ddl8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@ ddlAmBZBmCZC ddlDmEZE ddlFmG  mHZH ddlImJZJmKZKmLZLmMZM ddlNmOZOmPZPmQZQ ddlRmG  mSZT ddlUmVZV ddlWmXZX ddlYmZZZm[Z[m\Z\ ddl]m^Z^m_Z_m`Z` ddlambZb ddlcmdZd ddlemfZf ddlgmhZhmiZi er4ddlmjZj dZkdddd Zld!Zmd"Znd#Zod$Zpe-G d%d& d&ePZqed'd(d)d*d+Zreeee eegef eeegef  eeef f ZsG d,d- d-ePeQe( Zted.eXd/ZuG d0d' d'ete( Zve7evd;d3d4d5d6d7d7d7d7d7d7d7d'd8d9d:ZwdS )<a  
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)TYPE_CHECKINGCallableHashableIterableIteratorListMappingSequenceTypeVarUnioncast)option_context)	Timestamplib)	ArrayLikeFFrameOrSeriesFrameOrSeriesUnion
IndexLabelScalarTfinal)function)AbstractMethodError)AppenderSubstitutioncache_readonlydoc)is_bool_dtypeis_datetime64_dtypeis_float_dtypeis_integer_dtypeis_numeric_dtypeis_object_dtype	is_scalaris_timedelta64_dtype)isnanotna)nanops)BaseMaskedArrayBooleanArrayCategoricalExtensionArray)	DataErrorPandasObjectSelectionMixin)	DataFrame)NDFrame)basenumba_ops)CategoricalIndexIndex
MultiIndex)ensure_block_shape)Series)get_group_index_sorter)NUMBA_FUNC_CACHEmaybe_use_numba)Literalz
        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
    -----
    In the current implementation ``apply`` calls ``func`` twice on the
    first group to decide whether it can take a fast or slow code
    path. This can lead to unexpected behavior if ``func`` has
    side-effects, as they will take effect twice for the first
    group.

    .. versionchanged:: 1.3.0

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

    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
    transformed values.

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)selfrG    rJ   M/var/www/html/venv/lib/python3.7/site-packages/pandas/core/groupby/groupby.py__init__  s    zGroupByPlot.__init__c               s     fdd}d|_ | j|S )Nc               s   | j  S )N)plot)rI   )argskwargsrJ   rK   f  s    zGroupByPlot.__call__.<locals>.frM   )__name__rH   apply)rI   rN   rO   rP   rJ   )rN   rO   rK   __call__  s    zGroupByPlot.__call__str)namec               s    fdd}|S )Nc                s    fdd}j |S )Nc               s   t | j S )N)getattrrM   )rI   )rN   rO   rU   rJ   rK   rP     s    z0GroupByPlot.__getattr__.<locals>.attr.<locals>.f)rH   rR   )rN   rO   rP   )rU   rI   )rN   rO   rK   attr  s    z%GroupByPlot.__getattr__.<locals>.attrrJ   )rI   rU   rW   rJ   )rU   rI   rK   __getattr__  s    zGroupByPlot.__getattr__N)rQ   
__module____qualname____doc__rL   rS   rX   rJ   rJ   rJ   rK   rE     s   rE   rF   zIterator[GroupBy])rG   returnc             c  s"   |    z
| V  W d|   X dS )z2
    Set / reset the group_selection_context.
    N)_set_group_selection_reset_group_selection)rG   rJ   rJ   rK   group_selection_context&  s    
r_   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 );BaseGroupByNzIndexLabel | None_group_selectionzfrozenset[str]_apply_allowlistas_indexaxisdropna
exclusionsgrouper
group_keyskeyslevelmutatedobjobservedsortsqueezeintzops.BaseGrouperbool)r\   c             C  s
   t | jS )N)lengroups)rI   rJ   rJ   rK   __len__R  s    zBaseGroupBy.__len__rT   c             C  s
   t | S )N)object__repr__)rI   rJ   rJ   rK   rv   V  s    zBaseGroupBy.__repr__zdict[Hashable, np.ndarray]c             C  s   | j jS )z4
        Dict {group name -> group labels}.
        )rg   rs   )rI   rJ   rJ   rK   rs   [  s    zBaseGroupBy.groupsc             C  s   | j jS )N)rg   ngroups)rI   rJ   rJ   rK   rw   c  s    zBaseGroupBy.ngroupsc             C  s   | j jS )z5
        Dict {group name -> group indices}.
        )rg   indices)rI   rJ   rJ   rK   rx   h  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syfdd|D S  tk
r } zd}t||W d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 )N)r   )keyrJ   rJ   rK   <lambda>{      zABaseGroupBy._get_indices.<locals>.get_converter.<locals>.<lambda>c             S  s
   t | jS )N)r   Zasm8)ry   rJ   rJ   rK   rz   }  r{   c             S  s   | S )NrJ   )ry   rJ   rJ   rK   rz     r{   )
isinstancedatetimenpZ
datetime64)srJ   rJ   rK   get_converterw  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 rJ   )rx   ).0rU   )rI   rJ   rK   
<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 rJ   rJ   )r   r   )r   rJ   rK   r     s    c             3  s&   | ]}t d d t |D V  qdS )c             s  s   | ]\}}||V  qd S )NrJ   )r   rP   nrJ   rJ   rK   	<genexpr>  s    z5BaseGroupBy._get_indices.<locals>.<genexpr>.<genexpr>N)tuplezip)r   rU   )
convertersrJ   rK   r     s    z+BaseGroupBy._get_indices.<locals>.<genexpr>c             3  s   | ]} |V  qd S )NrJ   )r   rU   )	converterrJ   rK   r     s    c               s   g | ]} j |g qS rJ   )rx   get)r   rU   )rI   rJ   rK   r     s    )rr   rx   nextiterr|   r   
ValueErrorKeyError)rI   namesZindex_sampleZname_samplemsgerrrJ   )r   r   r   rI   rK   _get_indicesp  s,    


zBaseGroupBy._get_indicesc             C  s   |  |gd S )zQ
        Safe get index, translate keys for datelike to underlying repr.
        r   )r   )rI   rU   rJ   rJ   rK   
_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 )N)
_selectionr|   rl   r>   ra   )rI   rJ   rJ   rK   _selected_obj  s
    
zBaseGroupBy._selected_objzset[str]c             C  s   | j  | jB S )N)rl   _dir_additionsrb   )rI   rJ   rJ   rK   r     s    zBaseGroupBy._dir_additionsrF   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 )N)compipe)rI   r   rN   rO   rJ   rJ   rK   r     s    zBaseGroupBy.piper   c             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)rd   )r   r   rr   r   Z_take_with_is_copyrd   )rI   rU   rl   ZindsrJ   rJ   rK   	get_group  s    
zBaseGroupBy.get_groupz(Iterator[tuple[Hashable, FrameOrSeries]]c             C  s   | j j| j| jdS )z
        Groupby iterator.

        Returns
        -------
        Generator yielding sequence of (name, subsetted object)
        for each group
        )rd   )rg   get_iteratorrl   rd   )rI   rJ   rJ   rK   __iter__  s    
zBaseGroupBy.__iter__)N)rQ   rY   rZ   ra   __annotations__	frozensetrb   r3   Z_hidden_attrsr   rt   rv   propertyrs   rw   rx   r   r   r!   r   r   r    r   r   _pipe_templater   rE   rM   r   r   rJ   rJ   rJ   rK   r`   ;  sR   
3	r`   OutputFrameOrSeries)boundc               @  sz  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ed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d+d,d-d.Zd+d,d/d0Zddd$d1d2Zd3dd4d5d6Zed7d8 Zedd9d:d;Zedd9d<d=Zeed> jd?ed@ dAdBdC ZedDdEdEdFdGdHZedIdJ ZeddddddLdMdNZdOdddOdPdQdRZddddddSdTdUZdddddVdWdXZedddYdZd[Zed\d] Z eddd^d_d`daZ!ee"dbddcddZ#ededf Z$ee%dgdhee&dddidjdkZ'ee%dgdhee&dddidldmZ(e%dgdhee&dndo Z)ee%dgdhe%e&dpe*j+fd3dqdrdsZ,ee%dgdhee&e*j+fd3dqdtduZ-ee%dgdhee&dddwdxdyZ.ee%dgdhee&dddwdzd{Z/ee%dgdhee&dddwd|d}Z0ee%dgdhee&dEdd~dZ1ee2e3dddde*j+dfd3ddddZ4ee2e3dddde*j+dfd3ddddZ5ee2e3dd	dKdddddddZ6ee2e3dd	dKdddddddZ7ee2e3dd	dKdddddddZ8ee2e3dd	dKdddddddZ9ee%dgdhee&ddddZ:ee2e;j<dd Z<edd Z=ee%dgdhee&dd Z>ee%dgdhee&dd Z?ee%dgdhee&dd Z@edddddZAee%dgdhdddZBeBZCee%dgdhdddZDeDZEee%dgdhe%e&dpdddddddZFedddddZGee%dgdhdddddZHee%dgdhdddddZIee%dgdhee&dddddddddZJee%dgdhee&dddZKee%dgdhee&dddZLee%dgdhee&dddZMee%dgdhee&dddĄZNed	e*j+d	d	d	d	dd	d	d	ddfdddd3dddddddddǜddɄZOee%dgdhddd˄ZPee%dgdhee&ddd΄ZQee%dgdhe%e&dpdddфZRee%dgdhe%e&dpdddӄZSeeTjUfd'dd'd՜ddׄZVeddddddڜdd܄ZWdS )rF   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
    zops.BaseGrouperrg   rq   rc   Nr   TFr   z_KeysArgType | Nonerp   zIndexLabel | Nonezops.BaseGrouper | Nonezfrozenset[Hashable] | None)rl   ri   rd   rj   rg   rf   	selectionrc   rn   rh   ro   rm   rk   re   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)rd   rj   rn   rm   rk   re   )r   r|   r6   AssertionErrortyperj   r5   	TypeErrorr   rc   ri   rn   rh   ro   rm   rk   re   pandas.core.groupby.grouperr   rl   Z_get_axis_numberrd   rg   r   rf   )rI   rl   ri   rd   rj   rg   rf   r   rc   rn   rh   ro   rm   rk   re   r   rJ   rJ   rK   rL   N  s>    
zGroupBy.__init__rT   )rW   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_setru   __getattribute__rl   AttributeErrorr   rQ   )rI   rW   rJ   rJ   rK   rX     s    

zGroupBy.__getattr__r   )rU   r\   c          	     s   j kstt0 tj t tjsBfddS W d Q R X tt	j t
  fdd}|_|S )Nc               s
   t |  S )N)rV   )rI   )rU   rJ   rK   rz     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 )Nrd   c               s   | f S )NrJ   )x)rN   rP   rO   rJ   rK   curried  s    z7GroupBy._make_wrapper.<locals>.wrapper.<locals>.curried)	
parametersr   rd   rQ   r7   Zplotting_methodsrR   _python_apply_general_obj_with_exclusions)rN   rO   r   )rP   rU   rI   sig)rN   rO   rK   wrapper  s    



z&GroupBy._make_wrapper.<locals>.wrapper)rb   r   r_   rV   r   r|   types
MethodTyperR   r   inspect	signaturerQ   )rI   rU   r   rJ   )rP   rU   rI   r   rK   _make_wrapper  s    

zGroupBy._make_wrapperNone)r\   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 )N)rj   in_axisrU   )r   grJ   rJ   rK   r     s    z0GroupBy._set_group_selection.<locals>.<listcomp>F)rn   r   )rg   rc   	groupingsrl   ndimra   rr   Z
_info_axis
differencer;   tolist_reset_cache)rI   grpZgroupersaxrJ   rJ   rK   r]     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   )ra   r   )rI   rJ   rJ   rK   r^     s    
zGroupBy._reset_group_selectionzIterable[Series]c             C  s   t | d S )N)r   )rI   rJ   rJ   rK   _iterate_slices  s    zGroupBy._iterate_slices)not_indexed_samec               sd  ddl m}  fdd}|s|| jd} jrF dd j j n j j}|jr|j j 	|s|j
|j\}}	t|}|j| jd}n|j| jdd	}nz jr||} jr|}
 jj} jj}|| j|
||dd
}n ttt|}|| j|d}n||}|| jd} jjdkr> jjn j}t|tr`|d k	r`||_|S )Nr   )concatc               s,   x&t j|  D ]}| j}|  qW | S )N)r   Znot_none	_get_axisrd   Z_reset_identity)valuesvr   )rI   rJ   rK   reset_identity  s    z/GroupBy._concat_objects.<locals>.reset_identity)rd   c             S  s   dS )NTrJ   )r   rJ   rJ   rK   rz     r{   z)GroupBy._concat_objects.<locals>.<lambda>F)rd   copy)rd   ri   levelsr   rn   )rd   ri   r   )pandas.core.reshape.concatr   rd   re   filteraxesr   r   Zhas_duplicatesequalsindexZget_indexer_non_unique_values
algorithmsZunique1dtakereindexrh   rc   rg   r   r   listrangerr   rl   r   rU   r   r|   r>   )rI   ri   r   r   r   r   resultr   Zindexer_rh   Zgroup_levelsZgroup_namesrU   rJ   )rI   rK   _concat_objects  s@    

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)rd   Zinplace)rd   )rg   Zis_monotonicZset_axisrl   r   rd   r;   r~   concatenater   result_index
sort_indexrr   r   r   )rI   r   Zoriginal_positionsZdropped_rowsZsorted_indexerrJ   rJ   rK   _set_result_index_ordered-  s    z!GroupBy._set_result_index_orderedz"Mapping[base.OutputKey, ArrayLike])outputc             C  s   t | d S )N)r   )rI   r   rJ   rJ   rK   _wrap_aggregated_outputL  s    zGroupBy._wrap_aggregated_outputc             C  s   t | d S )N)r   )rI   r   rJ   rJ   rK   _wrap_transformed_outputO  s    z GroupBy._wrap_transformed_outputc             C  s   t | d S )N)r   )rI   datari   r   r   rJ   rJ   rK   _wrap_applied_outputR  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_defaultrl   r   rd   r   r   Z_get_numeric_datarr   columnsempty)rI   r   rl   checkrJ   rJ   rK   _resolve_numeric_onlyU  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_fill)rd   )callableNotImplementedErrorrg   
group_infor?   r   take_ndr   rd   to_numpyr   r   Zgenerate_slices)rI   r   r   idsr   rw   sorted_indexZ
sorted_idssorted_dataZsorted_index_datastartsendsrJ   rJ   rK   _numba_prep  s    
zGroupBy._numba_prep)engine_kwargsc            O  sz   |  ||\}}}}	| j }
t|||}||	|||t|
t|jf| }|df}|tkrf|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   )rd   )r   rg   _get_group_keysr8   Zgenerate_numba_transform_funcrr   r   r@   r   r~   Zargsort)rI   r   r   r   rN   rO   r   r   r   r   rh   Znumba_transform_funcr   	cache_keyrJ   rJ   rK   _transform_with_numba  s     	


zGroupBy._transform_with_numbac            O  s   |  ||\}}}}	| j }
t|||}||	|||t|
t|jf| }|df}|tkrf|t|< | jjdkrt	j
|
| jjd}nt|
| jjd d}||f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_aggr   )r   r   )rU   )r   rg   r   r8   Zgenerate_numba_agg_funcrr   r   r@   Znkeysr<   from_tuplesr   r;   )rI   r   r   r   rN   rO   r   r   r   r   rh   Znumba_agg_funcr   r   r   rJ   rJ   rK   _aggregate_with_numba  s$    	

zGroupBy._aggregate_with_numbarC   Z	dataframerD   )inputr   c               s   t  sr\tr4t fdd}q`ttd rRttd }q`tdn}tdd L y| 	|| j
}W n2 tk
r   t|  | 	|| j
S Q R X Y nX W d Q R X |S )Nc          	     s(   t jdd | f S Q R X d S )Nignore)all)r~   Zerrstate)r   )rN   r   rO   rJ   rK   rP     s    zGroupBy.apply.<locals>.fnanz6func must be a callable if args or kwargs are suppliedzmode.chained_assignment)r   is_builtin_funcr   r   hasattrr-   rV   r   r   r   r   r   r_   )rI   r   rN   rO   rP   r   rJ   )rN   r   rO   rK   rR     s     
	
$zGroupBy.applyr   r   )rP   r   r\   c             C  s0   | j ||| j\}}}| j||||p*| jdS )a-  
        Apply function f in python space

        Parameters
        ----------
        f : callable
            Function to apply
        data : Series or DataFrame
            Data to apply f to

        Returns
        -------
        Series or DataFrame
            data after applying f
        )r   )rg   rR   rd   r   rk   )rI   rP   r   ri   r   rk   rJ   rJ   rK   r   
  s    zGroupBy._python_apply_generalc          	     s   t  fdd}i }| jdkr6| || jS x|t|  D ]l\}}|j}y| j	||}	W n4 t
k
r   tjdt| j dtdd wDY nX tj||d}
|	||
< qDW |s| || jS | |S )	Nc               s   | f S )NrJ   )r   )rN   r   rO   rJ   rK   rz   &  r{   z-GroupBy._python_agg_general.<locals>.<lambda>r   zDropping invalid columns in z.agg is deprecated. In a future version, a TypeError will be raised. Before calling .agg, select only columns which should be valid for the aggregating function.   )
stacklevel)labelposition)r   r   rw   r   r   	enumerater   rU   rg   
agg_seriesr   warningswarnr   rQ   FutureWarningr7   	OutputKeyr   )rI   r   rN   rO   rP   r   idxrl   rU   r   ry   rJ   )rN   r   rO   rK   _python_agg_general#  s(    

zGroupBy._python_agg_general)r   	min_countaliasnpfuncc         	   C  s6   t | $ | j||||d}|j| jddS Q R X d S )N)howaltr   r  rG   )method)r_   _cython_agg_general__finalize__rl   )rI   r   r  r  r  r   rJ   rJ   rK   _agg_generalH  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   r>   r5   r   shaper   ilocrg   r  r|   r0   r   Z_from_sequencer  r=   )rI   r   r   r  Zserdf
res_valuesrJ   rJ   rK   _agg_py_fallback\  s    	



zGroupBy._agg_py_fallback)r  r  r   r  c             C  s   t | d S )N)r   )rI   r  r  r   r  rJ   rJ   rK   r    s    zGroupBy._cython_agg_general)r  r   rd   c             K  s   t | d S )N)r   )rI   r  r   rd   rO   rJ   rJ   rK   _cython_transform  s    zGroupBy._cython_transform)enginer   c      
   	   O  sd  t |rt|  | j}W d 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 d Q R X | |rN| |S | j|f||S d S )	Nr   r   )r   r   )r   rU   r   z2' is not a valid function name for transform(name)rm   T)rA   r_   r   r   Zto_framer   rl   r   r5   _constructorr   r   r>   ZravelrU   r   Zget_cython_funcr|   rT   Z_transform_generalr7   Ztransform_kernel_allowlistr   Zcythonized_kernelsZtransformation_kernelsrV   temp_setattrZ_can_use_transform_fastZ_wrap_transform_fast_result)
rI   r   r  r   rN   rO   r   r  r   r   rJ   rJ   rK   
_transform  s0    





zGroupBy._transformc             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   int64)r  )rd   FTr   )rr   r~   arrayrn   r   r   r   rd   r   r   rq   fillastyperp   Ztiler   r  r   where)rI   rx   re   filteredmaskrJ   rJ   rK   _apply_filter  s    
$zGroupBy._apply_filterz
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   )r  TNr  r   F)r   )rg   r   r?   rr   r~   r   r#  Zr_diffZnonzerocumsumrepeatintparanger&  )rI   r+  r   r   rw   ZsortercountrunrepoutrevrJ   rJ   rK   _cumcount_array  s    
"
&zGroupBy._cumcount_arrayztype[Series]c             C  s,   t | jtr| jjS t | jts$t| jjS )N)r|   rl   r5   Z_constructor_slicedr>   r   r   )rI   rJ   rJ   rK   _obj_1d_constructor  s    zGroupBy._obj_1d_constructorc               sR   ddd fdd}dddd	dd
dd}| j dddttjddd||| dS )zO
        Shared func to call any / all Cython GroupBy implementations.
        r   ztuple[np.ndarray, type])valsr\   c               sn   t | r8 r"tdd | D } q^tdd | D } n&t| trT| jjtdd} n
| t} | tj	tfS )Nc             S  s    g | ]}t |st|nd qS )T)r+   rq   )r   r   rJ   rJ   rK   r   
  s    z;GroupBy._bool_agg.<locals>.objs_to_bool.<locals>.<listcomp>c             S  s   g | ]}t |qS rJ   )rq   )r   r   rJ   rJ   rK   r     s    F)r   )
r(   r~   r$  r|   r.   _datar&  rq   viewint8)r8  )skipnarJ   rK   objs_to_bool  s    

z'GroupBy._bool_agg.<locals>.objs_to_boolFz
np.ndarrayr   rq   )r   	inferencenullabler\   c             S  s.   |rt | jtdd| dkS | j|ddS d S )NF)r   r  )r/   r&  rq   )r   r>  r?  rJ   rJ   rK   result_to_bool  s    z)GroupBy._bool_agg.<locals>.result_to_boolZgroup_any_allT)
	aggregater   cython_dtypeneeds_values
needs_maskneeds_nullablepre_processingpost_processingval_testr<  )F)_get_cythonized_resultr~   r  r;  )rI   rH  r<  r=  r@  rJ   )r<  rK   	_bool_agg   s    
zGroupBy._bool_aggrG   )rU   )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.
        any)rJ  )rI   r<  rJ   rJ   rK   rK  ,  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   )rJ  )rI   r<  rJ   rJ   rK   r   @  s    zGroupBy.allc             C  s   t dS )z
        Compute count of group, excluding missing values.

        Returns
        -------
        Series or DataFrame
            Count of values within each group.
        N)r   )rI   rJ   rJ   rK   r1  T  s    zGroupBy.count)Zsee_also)r   c               s2   |    | jd fdd d}|j| jd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.

        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
        meanc               s   t | j dS )N)r   )r>   rL  )r   )r   rJ   rK   rz     r{   zGroupBy.mean.<locals>.<lambda>)r  r   rG   )r  )r   r  r  rl   )rI   r   r   rJ   )r   rK   rL  b  s    3

zGroupBy.meanc               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 )N)r   )r>   rM  )r   )r   rJ   rK   rz     r{   z GroupBy.median.<locals>.<lambda>)r  r   rG   )r  )r   r  r  rl   )rI   r   r   rJ   )r   rK   rM    s    

zGroupBy.medianr   )ddofc          
   C  s&   | j dddddttjdd |dS )aw  
        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.

        Returns
        -------
        Series or DataFrame
            Standard deviation of values within each group.
        Z	group_varTc             S  s
   t | S )N)r~   sqrt)r8  r>  rJ   rJ   rK   rz     r{   zGroupBy.std.<locals>.<lambda>)rA  needs_countsrC  needs_2drB  rG  rN  )rI  r~   r  float64)rI   rN  rJ   rJ   rK   std  s    
zGroupBy.stdc          	     sV    dkr,|  tj}| jd fdd|dS  fdd}t|  | |S Q R X dS )ac  
        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.

        Returns
        -------
        Series or DataFrame
            Variance of values within each group.
        r   varc               s   t | j dS )N)rN  )r>   rT  )r   )rN  rJ   rK   rz     r{   zGroupBy.var.<locals>.<lambda>)r  r   c               s   | j  dS )N)rN  )rT  )r   )rN  rJ   rK   rz     r{   N)r   r   r   r  r_   r  )rI   rN  r   r   rJ   )rN  rK   rT    s    
zGroupBy.varc             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.
        )rN  r   N)rS  r   r~   rO  r1  r   r   rf   uniqueZget_indexer_forr  )rI   rN  r   colscountsZresult_ilocsZcount_ilocsrJ   rJ   rK   sem  s    
.zGroupBy.semc             C  sX   | j  }t| jjtr,| j|| jjd}n
| |}| jsJ|	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.
        )rU   sizer   )
fill_value)rg   rY  
issubclassrl   r   r>   r7  rU   rc   renamereset_index_reindex_output)rI   r   rJ   rJ   rK   rY    s    

zGroupBy.sizesum)fnamenoZmc)r   r  c          	   C  sF   |  |}t| dd | j||dtjd}W d Q R X | j|ddS )Nrm   Tadd)r   r  r  r  r   )rZ  )r   r   r!  r  r~   r_  r^  )rI   r   r  r   rJ   rJ   rK   r_  .  s    
zGroupBy.sumprodc             C  s   |  |}| j||dtjdS )Nrc  )r   r  r  r  )r   r  r~   rc  )rI   r   r  rJ   rJ   rK   rc  B  s    
zGroupBy.prodminc             C  s   | j ||dtjdS )Nrd  )r   r  r  r  )r  r~   rd  )rI   r   r  rJ   rJ   rK   rd  M  s    zGroupBy.minmaxc             C  s   | j ||dtjdS )Nre  )r   r  r  r  )r  r~   re  )rI   r   r  rJ   rJ   rK   re  T  s    zGroupBy.maxfirstc             C  s$   d	ddddd}| j ||d|dS )
Nr   r   rp   )rl   rd   c             S  sH   dddd}t | tr&| j||dS t | tr8|| S tt| d S )Nr>   )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   )r$  r,   rr   r~   r   )r   arrrJ   rJ   rK   rf  _  s    z2GroupBy.first.<locals>.first_compat.<locals>.first)rd   )r|   r5   rR   r>   r   r   )rl   rd   rf  rJ   rJ   rK   first_compat^  s    

z#GroupBy.first.<locals>.first_compatrf  )r   r  r  r  )r   )r  )rI   r   r  rh  rJ   rJ   rK   rf  [  s    zGroupBy.firstlastc             C  s$   d	ddddd}| j ||d|dS )
Nr   r   rp   )rl   rd   c             S  sH   dddd}t | tr&| j||dS t | tr8|| S tt| d S )Nr>   )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,   rr   r~   r   )r   rg  rJ   rJ   rK   ri  x  s    z/GroupBy.last.<locals>.last_compat.<locals>.last)rd   )r|   r5   rR   r>   r   r   )rl   rd   ri  rJ   rJ   rK   last_compatw  s    

z!GroupBy.last.<locals>.last_compatri  )r   r  r  r  )r   )r  )rI   r   r  rj  rJ   rJ   rK   ri  t  s    zGroupBy.lastr5   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 aggregaterA  ohlcr   r  )rd   r  openhighlowclose)r   r   c             S  s   |   S )N)rk  )r   rJ   rJ   rK   rz     r{   zGroupBy.ohlc.<locals>.<lambda>)rl   r   r   r'   r  r2   rg   Z_cython_operationr   Z_constructor_expanddimr   r^  Z_apply_to_column_groupbysr   )rI   rl   Z
is_numericr  Z	agg_namesr   rJ   rJ   rK   rk    s    

zGroupBy.ohlcc          	     s>   t | , |  fdd}| jdkr,|jS | S Q R X d S )Nc               s   | j f  S )N)describe)r   )rO   rJ   rK   rz     r{   z"GroupBy.describe.<locals>.<lambda>r   )r_   rR   rd   r   Zunstack)rI   rO   r   rJ   )rO   rK   rp    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.resamplerq  )rI   rulerN   rO   rq  rJ   rJ   rK   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.windowrt  r   rg   rc   )rI   rN   rO   rt  rJ   rJ   rK   rolling   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   )ExpandingGroupbyru  )rv  rx  r   rg   )rI   rN   rO   rx  rJ   rJ   rK   	expanding1  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   )ExponentialMovingWindowGroupbyru  )rv  rz  r   rg   )rI   rN   rO   rz  rJ   rJ   rK   ewmB  s    zGroupBy.ewmzLiteral[('ffill', 'bfill')])	directionc          
   C  s0   |dkrd}| j dddttjd||| jd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group_fillna_indexerFT)r   rD  rB  result_is_indexr|  limitre   )rI  r~   r  r#  re   )rI   r|  r~  rJ   rJ   rK   _fillR  s    
zGroupBy._fillc             C  s   | j d|dS )a6  
        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.pad: Returns Series with minimum number of char in object.
        DataFrame.pad: 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  )rI   r~  rJ   rJ   rK   pady  s    zGroupBy.padc             C  s   | j d|dS )a5  
        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.backfill :  Backward fill the missing values in the dataset.
        DataFrame.backfill:  Backward fill the missing values in the dataset.
        Series.fillna: Fill NaN values of a Series.
        DataFrame.fillna: Fill NaN values of a DataFrame.
        bfill)r~  )r  )rI   r~  rJ   rJ   rK   backfill  s    zGroupBy.backfillzint | list[int]zLiteral[('any', 'all', None)])r   re   r\   c          	   C  sn  t ttf}t||tfs td|st|tr8|g}nt||rNtt |}tj|tjd}t	|  t
|  |}t
| jddd | }||B }| jj\}	}
}
||	dk@ }| j| }| js|S | jj}||	|  |_| jst|tr||}| |}| jr| S |S Q R X t||r0td|d	krJtd
| d|dkrX|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d}|# |$| }}||k j%}t&|r&|' r&tj(|j)|< t&| jt&|ksPt&|t&| jjkr\| jj|_n|| jj}|S )a  
        Take the nth row from each group if n is an int, or a subset of rows
        if n is a list of ints.

        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 or list of ints
            A single nth value for the row or a list of nth values.
        dropna : {'any', 'all', None}, default None
            Apply the specified dropna operation before counting which row is
            the nth row.

        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

        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
        z0n needs to be an int or a list/set/tuple of ints)r  F)r+  r   r  Nz8dropna option with a list of nth values is not supported)rK  r   zQFor a DataFrame groupby, dropna must be either None, 'any' or 'all', (was passed z).r   )r  rd   )r   )ry   rd   rj   rn   rk   )rc   rn   )*setr   r   r|   rp   r   r~   r$  r/  r_   Zin1dr6  rg   r   r   rc   r   r   rm   r:   r   r^  rn   r   r   rl   re   rd   ri   rj   isinr   r   rk   rG   rY  nthr   rr   rK  r   loc)rI   r   re   Zvalid_containersZ
nth_valuesZ	nth_arrayZ	mask_leftZ
mask_rightr)  r   r   r4  r   max_lenZdroppedrd   rg   r   Zgrbsizesr   rJ   rJ   rK   r    sj    O








zGroupBy.nth      ?linear)interpolationc       	        sF  ddl m} ddddddd	dd
 fddt|r`jdddddttj| d
S  fdd|D }||j|d}tt	d|j
j jdg }t|j
j j}tt||j
j _t|tr||}n|j|jd}|| |j
j _t|jj t|jgj }|j|jdS 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   )r   r   z"tuple[np.ndarray, np.dtype | None])r8  r\   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!)r  Zna_valuezdatetime64[ns]ztimedelta64[ns])r(   r   r&   r  r|   r1   r   floatr~   r   r#  r#   r$   Zasarrayr&  r*   r%   rR  )r8  r>  r4  rJ   rJ   rK   pre_processor	  s,    






z'GroupBy.quantile.<locals>.pre_processorz
np.ndarrayztype | None)r8  r>  r\   c               s"   |rt |r dks| |} | S )N>   midpointr  )r&   r&  )r8  r>  )r  rJ   rK   post_processor	  s
    
z(GroupBy.quantile.<locals>.post_processorgroup_quantileTF)	rA  r   rC  rD  rB  rF  rG  qr  c               s0   g | ](}j d dddttj| d	qS )r  T)rA  rC  rD  rB  rF  rG  r  r  )rI  r~   r  rR  )r   Zqi)r  r  r  rI   rJ   rK   r   	  s   z$GroupBy.quantile.<locals>.<listcomp>)rd   ri   r   )rd   N)Zpandasr   r)   rI  r~   r  rR  rd   r   r   r   Znlevelsr$  r   r0  rr   r|   r>   Zreorder_levelsr  reshaperw   r   flattenr   )	rI   r  r  r   resultsr   orderZindex_namesrx   rJ   )r  r  r  rI   rK   quantile_	  s8    #

zGroupBy.quantile)r+  c          	   C  sL   t | : | jj}| j| jjd |tjd}|s>| jd | }|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   )r  r   N)	r_   r   r   r7  rg   r   r~   r#  rw   )rI   r+  r   r   rJ   rJ   rK   ngroup	  s    =
zGroupBy.ngroupc          	   C  s:   t | ( | j| j}| j|d}| ||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   rd   r6  r7  )rI   r+  r   Z	cumcountsrJ   rJ   rK   cumcount-
  s    7
zGroupBy.cumcountaveragekeep)r  r+  	na_optionpctrd   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
        >   r  topbottomz3na_option must be one of 'keep', 'top', or 'bottom')ties_methodr+  r  r  r   r  r  c               s   | j f  ddS )NF)rd   r   )rank)r   )rd   rO   rJ   rK   rz   
  r{   zGroupBy.rank.<locals>.<lambda>r  F)r   rd   )r  )r   poprR   r  )rI   r  r+  r  r  rd   r   rJ   )rd   rO   rK   r  i
  s    %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   r<  r   c               s   | j f d iS )Nrd   )r  )r   )rd   rO   rJ   rK   rz   
  r{   z!GroupBy.cumprod.<locals>.<lambda>)r  )nvvalidate_groupby_funcrR   r  )rI   rd   rN   rO   rJ   )rd   rO   rK   r  
  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
        r-  r   r<  r   c               s   | j f d iS )Nrd   )r-  )r   )rd   rO   rJ   rK   rz   
  r{   z GroupBy.cumsum.<locals>.<lambda>)r-  )r  r  rR   r  )rI   rd   rN   rO   rJ   )rd   rO   rK   r-  
  s    zGroupBy.cumsumc               s(    dkr|   fddS | jdddS )zm
        Cumulative min for each group.

        Returns
        -------
        Series or DataFrame
        r   c               s   t j|  S )N)r~   minimum
accumulate)r   )rd   rJ   rK   rz   
  r{   z GroupBy.cummin.<locals>.<lambda>cumminF)r   )rR   r  )rI   rd   rO   rJ   )rd   rK   r  
  s    zGroupBy.cumminc               s(    dkr|   fddS | jdddS )zm
        Cumulative max for each group.

        Returns
        -------
        Series or DataFrame
        r   c               s   t j|  S )N)r~   maximumr  )r   )rd   rJ   rK   rz   
  r{   z GroupBy.cummax.<locals>.<lambda>cummaxF)r   )rR   r  )rI   rd   rO   rJ   )rd   rK   r  
  s    zGroupBy.cummaxznp.dtypez
int | None)r  rB  rA  r   rP  rC  rQ  rE  r  rD  needs_ngroupsr}  c       &      K  s  |  |}|r|rtd|r.t|s.td|rNt|sBtd|sNtd| j}|j\}}}i }tt|}d}xt|  D ]\}}|j	}|j
}|rt|jsq|r|}nt|}tj||d}|r|d}t||}d}|rtj| jtjd}t||}|r|} |ry|| \} }W nd tk
r }! zDt|!}|d	d}"tjd
t| j d|" d|" dtdd wW dd}!~!X Y nX | j|dd} |r| d} t|| }t||}|	dk	rt||	}|
rt|tj}#t||#}|rt||}|r0t |t!}$t||$d}|r0t||$d}|f | |rJ|d}|r\t"#||}|rl|||}t$j%||d}%|||%< qW |s|dkrt||r| &|S | '|S dS )a
  
        Get result for Cythonized functions.

        Parameters
        ----------
        how : str, Cythonized function name to be called
        cython_dtype : np.dtype
            Type of the array that will be modified by the Cython call.
        aggregate : bool, default False
            Whether the result should be aggregated to match the number of
            groups
        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_values : bool, default False
            Whether the values should be a part of the Cython call
            signature
        needs_2d : bool, default False
            Whether the values and result of the Cython call signature
            are 2-dimensional.
        min_count : int, default None
            When not None, min_count for the Cython call
        needs_mask : bool, default False
            Whether boolean mask needs to be part of the Cython call
            signature
        needs_ngroups : bool, default False
            Whether number of groups is 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
        result_is_index : bool, default False
            Whether the result of the Cython operation is an index of
            values to be retrieved, instead of the actual values themselves
        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
        z6'result_is_index' and 'aggregate' cannot both be True!z%'post_processing' must be a callable!z$'pre_processing' must be a callable!z>Cannot use 'pre_processing' without specifying 'needs_values'! )r  )r  r   NZgroup_zDropping invalid columns in .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  F)r   )r?  r  )r  r  )(r   r   r   rg   r   rV   
libgroupbyr  r   rU   r   r'   r  rr   r~   Zzerosr  r   rw   r#  r   rT   replacer  r	  r   rQ   r
  r&  r+   r:  Zuint8r|   r.   r   r   r7   r  r   r   )&rI   r  rB  rA  r   rP  rC  rQ  rE  r  rD  r  r}  rF  rG  rO   rg   r   r   rw   r   Z	base_func	error_msgr  rl   rU   r   Z	result_szr   r   Z
inferencesrW  r8  r   Zhowstrr)  Zis_nullablery   rJ   rJ   rK   rI  
  s    J
















zGroupBy._get_cythonized_resultc               sN   dk	s dkst s0|  fddS | jddttjd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 )N)shift)r   )rd   rZ  freqperiodsrJ   rK   rz     r{   zGroupBy.shift.<locals>.<lambda>Zgroup_shift_indexerFT)r   rB  r  r}  r  )r+   rR   rI  r~   r  r#  )rI   r  r  rd   rZ  rJ   )rd   rZ  r  r  rK   r    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  rd   )
pct_change)r   )rd   r  r  r~  r  rJ   rK   rz     s
   z$GroupBy.pct_change.<locals>.<lambda>r  )r~  )rd   )r  r  rd   r   )rR   rV   rG   rg   codesrd   r  )	rI   r  r  r~  r  rd   ZfilledZfill_grpZshiftedrJ   )rd   r  r  r~  r  rK   r    s    zGroupBy.pct_change   c             C  s@   |    |  |k }| jdkr(| j| S | jjdd|f S 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).

        Does not work for negative values of `n`.

        Returns
        -------
        Series or DataFrame
        %(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)
        Empty DataFrame
        Columns: [A, B]
        Index: []
        r   N)r^   r6  rd   r   r  )rI   r   r)  rJ   rJ   rK   head  s
    

zGroupBy.headc             C  sD   |    | jdd|k }| jdkr,| j| S | jjdd|f S d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).

        Does not work for negative values of `n`.

        Returns
        -------
        Series or DataFrame
        %(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)
        Empty DataFrame
        Columns: [A, B]
        Index: []
        F)r+  r   N)r^   r6  rd   r   r  )rI   r   r)  rJ   rJ   rK   tail
  s
    

zGroupBy.tailr   )r   rZ  r\   c             C  s   | j j}t|dkr|S | jr"|S tdd |D s8|S dd |D }tj|| j 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 )a  
        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.

        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 )N)r|   Zgrouping_vectorr0   r:   )r   pingrJ   rJ   rK   r   V  s   z*GroupBy._reindex_output.<locals>.<genexpr>c             S  s   g | ]
}|j qS rJ   )Zgroup_index)r   r  rJ   rJ   rK   r   [  s    z+GroupBy._reindex_output.<locals>.<listcomp>)r   r   FrZ  c             s  s"   | ]\}}|j r||jfV  qd S )N)r   rU   )r   ir  rJ   rJ   rK   r   t  s    )labelsrd   )r   rZ  )rj   T)drop)rg   r   rr   rm   rK  r<   Zfrom_productr   Z	sortlevelrc   rl   Z_get_axis_namerd   r   r  r   r  r   Z	set_indexr   r]  )rI   r   rZ  r   Zlevels_listr   r   dZin_axis_grpsZg_numsZg_namesrJ   rJ   rK   r^  0  s0    
zGroupBy._reindex_outputzfloat | NonezSequence | Series | None)r   fracr  weightsc       
        s   ddl m} dk	r>t| jjdfdd| j D }ndg| j }dk	r\t	| j
| j| j} fddt||D }	||	| 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, optional
            If int, array-like, or BitGenerator (NumPy>=1.17), seed for
            random number generator
            If np.random.RandomState, use as numpy RandomState object.

        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
        r   )r   N)r   c               s   g | ]} j | qS rJ   )r  )r   r  )r  rJ   rK   r     s    z"GroupBy.sample.<locals>.<listcomp>c          	     s(   g | ] \\}}}|j  |d qS ))r   r  r  r  random_state)sample)r   r   rl   w)r  r   r  r  rJ   rK   r     s   )rd   )r   r   r>   r   r   rx   r   rw   r   r  rg   r   rd   r   )
rI   r   r  r  r  r  r   wsZgroup_iteratorZsamplesrJ   )r  r   r  r  r  rK   r    s    ]
zGroupBy.sample)Nr   NNNNTTTFFFT)F)F)Tr  )r  )Tr   )T)T)T)r   )r   )r   )Fr  )Fr  )Fr  )Fr  )N)N)N)N)r  r  )T)T)r  Tr  Fr   )r   )r   )r   )r   )r   Nr   N)r   r  NNr   )r  )r  )NNFNN)XrQ   rY   rZ   r[   r   r   rL   rX   r   r]   r^   r   r   r   r   r   r   r   r   r   r   r   _apply_docsformatrR   r   r  r  r  r  r  r"  r*  r6  r   r7  rJ  r    _common_see_alsorK  r   r1  r   r   rL  rM  rS  rT  rX  rY  r"   _groupby_agg_method_templater_  rc  rd  re  rf  ri  rk  r5   rp  rs  rw  ry  r{  r  r  r  r  r  r  r  r  r  r  r  r-  r  r  rI  r  r  r  r  r~   NaNr^  r  rJ   rJ   rJ   rK   rF     s  
B            ,+
)B* #/% )4",9"f& - D:    2* '(##S    TFr6   z_KeysArgType | Nonerp   zops.BaseGrouper | Nonerq   )rl   byrd   rg   rc   rn   rh   ro   rm   rk   re   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: )rl   ri   rd   rj   rg   rf   r   rc   rn   rh   ro   rm   rk   re   )r|   r>   Zpandas.core.groupby.genericr  r5   r  r   )rl   r  rd   rj   rg   rf   r   rc   rn   rh   ro   rm   rk   re   r  r   r  rJ   rJ   rK   get_groupby  s,    

r  )Nr   NNNNTTTFFFT)xr[   
__future__r   
contextlibr   r}   	functoolsr   r   r   textwrapr   r   typingr   r   r	   r
   r   r   r   r   r   r   r   r  numpyr~   Zpandas._config.configr   Zpandas._libsr   r   Zpandas._libs.groupbyZ_libsrG   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.core.dtypes.commonr#   r$   r%   r&   r'   r(   r)   r*   Zpandas.core.dtypes.missingr+   r,   Zpandas.corer-   Zpandas.core.algorithmscorer   Zpandas.core.arraysr.   r/   r0   r1   Zpandas.core.baser2   r3   r4   Zpandas.core.commoncommonr   Zpandas.core.framer5   Zpandas.core.genericr6   Zpandas.core.groupbyr7   r8   r9   Zpandas.core.indexes.apir:   r;   r<   Zpandas.core.internals.blocksr=   Zpandas.core.seriesr>   Zpandas.core.sortingr?   Zpandas.core.util.numba_r@   rA   rB   r  r  r  r   Z_transform_templateZ_agg_templaterE   r_   Z_KeysArgTyper`   r   rF   r  rJ   rJ   rJ   rK   <module>   s   4(
(
8+4|L J                                