o
    5cF;                    @  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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l0m1Z2 ddl3m4Z4m5Z5 ddl6m7Z7m8Z8m9Z9m:Z: ddl;m<Z< ddl=m>Z> ddl?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZH ddlImJZJmKZK ddlLmMZM ddlNmOZO ddlPmQ  mRZR ddlSmTZTmUZUmVZVmWZW ddlXmYZYmZZZ ddl[mQ  m\Z] ddl^m_Z_ ddl`maZa ddlbmcZcmdZdmeZe ddlfmgZgmhZh ddlimjZjmkZkmlZlmmZm ddlnmoZo ddlpmQ  mqZq ddlrmsZs ddltmuZu ddlvmwZwmxZx erIddlymzZzm{Z{m|Z| d Z}d!d"d#d$Z~d%Zd&Zd'Zd(ZeG d)d* d*eYZeeee eegef eeegef  eeef f ZG d+d, d,eYeZe* egZed-ead.ZG d/d0 d0ee* Ze:e							1	1	1	2	2	2	1dSdTdEdFZdUdLdMZdVdQdRZdS )Wa  
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LiteralMappingSequenceTypeVarUnioncastfinal)option_context)	Timestamplib)	ArrayLike
IndexLabelNDFrameTPositionalIndexerRandomStateScalarTnpt)function)AbstractMethodError	DataError)AppenderSubstitutioncache_readonlydoc)find_stack_level)ensure_dtype_can_hold_na)	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)PandasObjectSelectionMixin)	DataFrame)NDFrame)basenumba_ops)GroupByIndexingMixinGroupByNthSelector)CategoricalIndexIndex
MultiIndex
RangeIndex)ensure_block_shape)Series)get_group_index_sorter)get_jit_argumentsmaybe_use_numba)ExpandingGroupbyExponentialMovingWindowGroupbyRollingGroupbyz
        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}
    a&  
    >>> df = pd.DataFrame({'A': 'a a b'.split(),
    ...                    'B': [1,2,3],
    ...                    'C': [4,6,5]})
    >>> g1 = df.groupby('A', group_keys=False)
    >>> g2 = df.groupby('A', group_keys=True)

    Notice that ``g1`` have ``g2`` have two groups, ``a`` and ``b``, and only
    differ in their ``group_keys`` argument. 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:

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

    In the above, the groups are not part of the index. We can have them included
    by using ``g2`` where ``group_keys=True``:

    >>> g2[['B', 'C']].apply(lambda x: x / x.sum())
                B    C
    A
    a 0  0.333333  0.4
      1  0.666667  0.6
    b 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``.

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

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

    The ``group_keys`` argument has no effect here because the result is not
    like-indexed (i.e. :ref:`a transform <groupby.transform>`) when compared
    to the input.

    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:

    >>> g1.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())
    >>> g1 = s.groupby(s.index, group_keys=False)
    >>> g2 = s.groupby(s.index, group_keys=True)

    From ``s`` above we can see that ``g`` has two groups, ``a`` and ``b``.
    Notice that ``g1`` have ``g2`` have two groups, ``a`` and ``b``, and only
    differ in their ``group_keys`` argument. 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``.

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

    In the above, the groups are not part of the index. We can have them included
    by using ``g2`` where ``group_keys=True``:

    >>> g2.apply(lambda x: x*2 if x.name == 'a' else x/2)
    a  a    0.0
       a    2.0
    b  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:

    >>> g1.apply(lambda x: x.max() - x.min())
    a    1
    b    0
    dtype: int64

    The ``group_keys`` argument has no effect here because the result is not
    like-indexed (i.e. :ref:`a transform <groupby.transform>`) when compared
    to the input.

    >>> g2.apply(lambda x: x.max() - x.min())
    a    1
    b    0
    dtype: int64)templatedataframe_examples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.
aO  
Apply a ``func`` with arguments to this %(klass)s object and return its result.

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

>>> h(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
ac  
Call function producing a same-indexed %(klass)s on each group.

Returns 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. See the Notes section below for requirements.

    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.

.. deprecated:: 1.5.0

    When using ``.transform`` on a grouped DataFrame and the transformation function
    returns a DataFrame, currently pandas does not align the result's index
    with the input's index. This behavior is deprecated and alignment will
    be performed in a future version of pandas. You can apply ``.to_numpy()`` to the
    result of the transformation function to avoid alignment.

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')[['C', 'D']]
>>> 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.0  6.0
1  3.0  8.0
2  4.0  6.0
3  3.0  8.0
4  4.0  6.0
5  3.0  8.0

.. versionchanged:: 1.3.0

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

>>> grouped.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                   @  s,   e Zd ZdZdddZdd	 ZdddZdS )GroupByPlotzE
    Class implementing the .plot attribute for groupby objects.
    groupbyGroupByreturnNonec                 C  s
   || _ d S N)_groupby)selfrR    rY   Q/var/www/html/gps/gps/lib/python3.10/site-packages/pandas/core/groupby/groupby.py__init__V  s   
zGroupByPlot.__init__c                   s     fdd}d|_ | j|S )Nc                   s   | j  i S rV   )plotrX   argskwargsrY   rZ   fZ  s   zGroupByPlot.__call__.<locals>.fr\   )__name__rW   apply)rX   r_   r`   ra   rY   r^   rZ   __call__Y  s   zGroupByPlot.__call__namestrc                   s    fdd}|S )Nc                    s    fdd}j |S )Nc                   s   t | j i S rV   )getattrr\   r]   )r_   r`   re   rY   rZ   ra   b  s   z0GroupByPlot.__getattr__.<locals>.attr.<locals>.f)rW   rc   )r_   r`   ra   re   rX   r^   rZ   attra  s   z%GroupByPlot.__getattr__.<locals>.attrrY   )rX   re   ri   rY   rh   rZ   __getattr__`  s   zGroupByPlot.__getattr__N)rR   rS   rT   rU   )re   rf   )rb   
__module____qualname____doc__r[   rd   rj   rY   rY   rY   rZ   rQ   P  s
    
rQ   c                   @  s*  e Zd ZU dZded< e Zded< ejh dB Zded< d	ed
< dZ	ded< ded< e
d4ddZe
d5ddZe
ed6ddZe
ed4ddZe
ed7ddZe
dd Ze
dd  Ze
ed!d" Ze
d8d$d%Zed&ed'd(eed9d,d-ZeeZe
d:d;d/d0Ze
d<d2d3ZdS )=BaseGroupByNIndexLabel | None_group_selectionzfrozenset[str]_apply_allowlist>   objaxiskeyssortleveldropnagroupermutatedsqueezeas_indexobserved
exclusions
group_keysintrs   ops.BaseGrouperrx   _KeysArgType | Nonert   bool | lib.NoDefaultr~   rT   c                 C  s
   t | jS rV   )lengroupsr]   rY   rY   rZ   __len__  s   
zBaseGroupBy.__len__rf   c                 C  
   t | S rV   )object__repr__r]   rY   rY   rZ   r     s   
zBaseGroupBy.__repr__dict[Hashable, np.ndarray]c                 C     | j jS )z4
        Dict {group name -> group labels}.
        )rx   r   r]   rY   rY   rZ   r        zBaseGroupBy.groupsc                 C  r   rV   )rx   ngroupsr]   rY   rY   rZ   r        zBaseGroupBy.ngroups$dict[Hashable, npt.NDArray[np.intp]]c                 C  r   )z5
        Dict {group name -> group indices}.
        )rx   indicesr]   rY   rY   rZ   r     r   zBaseGroupBy.indicesc              
     s   dd t |dkrg S t jdkrttj}nd}|d }t|trjt|ts1d}t|t |t |ksWz
fdd|D W S  tyV } zd}t||d}~ww 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  s0   t | tjr
dd S t | tjrdd S dd S )Nc                 S     t | S rV   )r   keyrY   rY   rZ   <lambda>      zABaseGroupBy._get_indices.<locals>.get_converter.<locals>.<lambda>c                 S  s
   t | jS rV   )r   asm8r   rY   rY   rZ   r        
 c                 S  s   | S rV   rY   r   rY   rY   rZ   r     s    )
isinstancedatetimenp
datetime64)srY   rY   rZ   get_converter  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 rY   )r   .0re   r]   rY   rZ   
<listcomp>      z,BaseGroupBy._get_indices.<locals>.<listcomp>zHmust supply a same-length tuple to get_group with multiple grouping keysc                   s   g | ]} |qS rY   rY   )r   r   )r   rY   rZ   r         c                 3  s(    | ]}t d d t |D V  qdS )c                 s  s    | ]	\}}||V  qd S rV   rY   )r   ra   nrY   rY   rZ   	<genexpr>  s    z5BaseGroupBy._get_indices.<locals>.<genexpr>.<genexpr>N)tuplezipr   )
convertersrY   rZ   r     s   & z+BaseGroupBy._get_indices.<locals>.<genexpr>c                 3  s    | ]} |V  qd S rV   rY   r   )	converterrY   rZ   r     s    c                   s   g | ]	} j |g qS rY   )r   getr   r]   rY   rZ   r     s    )r   r   nextiterr   r   
ValueErrorKeyError)rX   namesindex_samplename_samplemsgerrrY   )r   r   r   rX   rZ   _get_indices  s2   



zBaseGroupBy._get_indicesc                 C  s   |  |gd S )zQ
        Safe get index, translate keys for datelike to underlying repr.
        r   )r   )rX   re   rY   rY   rZ   
_get_index  s   zBaseGroupBy._get_indexc                 C  s>   | j d u st| jtr| jd ur| j| j S | jS | j| j  S rV   )
_selectionr   rr   rG   rp   r]   rY   rY   rZ   _selected_obj  s
   
zBaseGroupBy._selected_objset[str]c                 C  s   | j  | jB S rV   )rr   _dir_additionsrq   r]   rY   rY   rZ   r     s   zBaseGroupBy._dir_additionsrS   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examplesfunc/Callable[..., T] | tuple[Callable[..., T], str]r   c                 O  s   t j| |g|R i |S rV   )compipe)rX   r   r_   r`   rY   rY   rZ   r     s   zBaseGroupBy.pipeDataFrame | Seriesc                 C  s8   |du 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rs   )r   r   r   r   _take_with_is_copyrs   )rX   re   rr   indsrY   rY   rZ   	get_group  s   
zBaseGroupBy.get_group#Iterator[tuple[Hashable, NDFrameT]]c                 C  sB   | j }t|trt|dkrtjdtt d | jj	| j
| jdS )z
        Groupby iterator.

        Returns
        -------
        Generator yielding sequence of (name, subsetted object)
        for each group
           zIn a future version of pandas, a length 1 tuple will be returned when iterating over a groupby with a grouper equal to a list of length 1. Don't supply a list with a single grouper to avoid this warning.
stacklevelr   )rt   r   listr   warningswarnFutureWarningr&   rx   get_iteratorr   rs   )rX   rt   rY   rY   rZ   __iter__/  s   
zBaseGroupBy.__iter__)rT   r   )rT   rf   )rT   r   )rT   r   )rT   r   )r   r   rT   r   rV   rT   r   )rT   r   )rb   rk   rl   rp   __annotations__	frozensetrq   r9   _hidden_attrsrt   r   r   r   propertyr   r   r   r   r   r$   r   r   r#   r   r"   _pipe_templater   rQ   r\   r   r   rY   rY   rY   rZ   rn   s  sV   
 
2

rn   OutputFrameOrSeries)boundc                   @  s\  e Zd ZU dZded< ded< e																dddd Zd d#d$Zed!d'd(Zed"d)d*Z	ed"d+d,Z
ed#d.d/Zd$d1d2Ze				d%d&d5d6Zed'd9d:Zd(d=d>Ze	d)d*dCdDZed+dEdFZ				d%d,dIdJZd-dMdNZd.dPdQZedRdS Zd/dWdXZeddYdZd[ZeddYd\d]Zeed^ jd_ed` dad0dbdcZe					d1d2didjZed	dkdldmZe		nd3d4drdsZ d5dwdxZ!e	n	d6d7dzd{Z"	d8d9d|d}Z#eddd~ddZ$ed:ddZ%edd Z&ed;d<ddZ'ee(d=ddZ)ed>ddZ*ee+ddee,d;d?ddZ-ee+ddee,d;d?ddZ.ee+ddee,d0ddZ/ee+dde+e,de0j1ddfd@ddZ2ee+ddee,e0j1fdAddZ3ee+ddee,ddde0j1fdBddZ4ee+ddee,ddde0j1fdBddZ5ee+ddee,de0j1fdCddZ6ee+ddee,dDddZ7ee8e9dddde0j1dddfdEddZ:ee8e9dddde0j1dfdFddZ;ee8e9dd	dnd			n		dGdHddZ<ee8e9dd	dnd			n		dGdHddZ=ee+dddIdJddZ>ee+dddIdJddZ?ee+ddee,dKddZ@e8eAjBdd ZBedd ZCee+ddee,dLddĄZDee+ddee,dMddǄZEee+ddee,dNddʄZFed)dOdd΄ZGee+ddd)ddЄZHd)dd҄ZIee+ddd)ddԄZJd)ddքZKee(e+dde+e,ddPddلZL	d)dQddބZMedde0j1fdRddZNee+ddd;dSddZOee+ddd;dSddZPee+dde+e,d						dTdUddZQee+ddee,dVd0ddZRee+ddee,dVd0ddZSee+ddee,dWd0ddZTee+ddee,dWd0ddZUee0j1d	d	d	ddfdXddZVee+dddYdd ZWee+ddee,dZd[ddZXee+ddee,d\ddZYee+dde+e,dd]d^dd	ZZee+dde+e,dd]d^d
dZ[ed_ddZ\ee]j^dfd`ddZ_e						dadbddZ`dS (c  rS   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
    r   rx   boolr{   Nr   TFrr   r   rt   r   rs   r   rv   ro   ops.BaseGrouper | Noner}   frozenset[Hashable] | None	selectionru   r~   r   rz   r|   ry   rw   rT   rU   c              
   C  s   || _ t|tsJ t||| _|s$t|tstd|dkr$td|| _|| _	|	| _
|
| _|| _|| _|| _|| _|d u rWddlm} ||||||	|| j| jd\}}}|| _||| _|| _|rlt|| _d S t | _d S )Nz(as_index=False only valid with DataFramer   z$as_index=False only valid for axis=0get_grouper)rs   rv   ru   r|   ry   rw   )r   r   r<   typerv   r;   	TypeErrorr   r{   rt   ru   r~   rz   r|   ry   rw   pandas.core.groupby.grouperr   rr   _get_axis_numberrs   rx   r   r}   )rX   rr   rt   rs   rv   rx   r}   r   r{   ru   r~   rz   r|   ry   rw   r   rY   rY   rZ   r[     s@   
zGroupBy.__init__ri   rf   c                 C  sD   || j v rt| |S || jv r| | S tdt| j d| d)N'z' object has no attribute ')_internal_names_setr   __getattribute__rr   AttributeErrorr   rb   )rX   ri   rY   rY   rZ   rj     s   

zGroupBy.__getattr__re   r   c                   s   j v sJ  ' tj t tjs+tt	fddW  d    S W d    n1 s5w   Y  tt
j t  fdd}|_|S )Nc                   s
   t |  S rV   )rg   r]   re   rY   rZ   r     r   z'GroupBy._make_wrapper.<locals>.<lambda>c                    s   dj v rdd d u rjd< dtj} fdd}|_tjv r.|S tj	v }|r<j
jr<j
S j|j
|| d}jjdkrmjdkrm|jdkrmj
j|j}t|dkrmtt| jjrx|rx|}|S )Nrs   numeric_onlyc                   sT   t   d}t d|t | g R i W  d    S 1 s#w   Y  d S )Nz"The default value of numeric_only ignore)r   catch_warningsfilterwarningsr   )xmatch)r_   ra   r`   rY   rZ   curried  s
   
$z7GroupBy._make_wrapper.<locals>.wrapper.<locals>.curried)is_transformnot_indexed_samer   r   )
parametersr   rs   r   
no_defaultrb   r=   plotting_methodsrc   transformation_kernels_obj_with_exclusionsempty_python_apply_generalr   ndimcolumns
differencer   )warn_dropping_nuisance_columns_deprecatedr   rx   has_dropped_na_set_result_index_ordered)r_   r`   r   r   r   resultmissingra   re   rX   sigr^   rZ   wrapper  s4   





 

z&GroupBy._make_wrapper.<locals>.wrapper)rq   _group_selection_contextrg   r   r   types
MethodTyper   r   rc   r   inspect	signaturerb   )rX   re   r   rY   r   rZ   _make_wrapper  s   
	
4zGroupBy._make_wrapperc                 C  sz   | j }| jr|jdur| jjdkr| jdu sdS dd |jD }t|r;| jj}|jt	|dd
 | _| d dS 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
        Nr   c                 S  s"   g | ]}|j d u r|jr|jqS rV   )rv   in_axisre   )r   grY   rY   rZ   r   6  s   " z0GroupBy._set_group_selection.<locals>.<listcomp>F)ru   r   )rx   r{   	groupingsrr   r   rp   r   
_info_axisr   rC   tolist_reset_cache)rX   grpgroupersaxrY   rY   rZ   _set_group_selection#  s    

zGroupBy._set_group_selectionc                 C  s"   | j durd| _ | d dS 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   )rp   r
  r]   rY   rY   rZ   _reset_group_selection>  s   
zGroupBy._reset_group_selectionIterator[GroupBy]c                 c  s*    |    z
| V  W |   dS |   w )z;
        Set / reset the _group_selection_context.
        N)r  r  r]   rY   rY   rZ   r   K  s
   z GroupBy._group_selection_contextIterable[Series]c                 C     t | rV   r    r]   rY   rY   rZ   _iterate_slicesV  s   zGroupBy._iterate_slicesr   override_group_keysc                   sj  ddl m}  fdd} jrA|sA||} jr0 jj} jj} jj}|| j|||dd}	njt	t
t|}
|| j|
d}	nY|s|| jd}	 j j} jrb jjd }|d	k}|| }|jr|	j j |st|j}|	j|\}}|	j| jd}	n|	j| jdd
}	n||}|| jd}	 jjdkr jjn j}t|	tr|d ur||	_|	S )Nr   )concatc                   s(   t j|  D ]}| j}|  q| S rV   )r   not_none	_get_axisrs   _reset_identity)valuesvr  r]   rY   rZ   reset_identitye  s   
z/GroupBy._concat_objects.<locals>.reset_identityF)rs   rt   levelsr   ru   )rs   rt   r   rs   copyr   ) pandas.core.reshape.concatr  r~   r{   rx   result_indexr  r   rs   r   ranger   r   r  rw   
group_infohas_duplicatesaxesequals
algorithmsunique1d_valuesindexget_indexer_non_uniquetakereindexrr   r   re   r   r   rG   )rX   r  r   r  r  r  r~   group_levelsgroup_namesr   rt   r  labelsmasktargetindexer_re   rY   r]   rZ   _concat_objects\  sH   
zGroupBy._concat_objectsr   r   c                 C  s   | j | j}| jjr| jjs|j|| jdd}|S t| j }|j|| jdd}|j	| jd}| jjrA|j
tt|| jd}|j|| jdd}|S )NFr  r   )rr   r  rs   rx   is_monotonicr   set_axisrC   result_ilocs
sort_indexr.  rE   r   )rX   r   obj_axisoriginal_positionsrY   rY   rZ   r     s   z!GroupBy._set_result_index_ordered"Mapping[base.OutputKey, ArrayLike]Series | DataFramec                 C  r  rV   r  rX   r   rY   rY   rZ   _indexed_output_to_ndframe  r   z"GroupBy._indexed_output_to_ndframeoutput7Series | DataFrame | Mapping[base.OutputKey, ArrayLike]qsnpt.NDArray[np.float64] | Nonec                 C  s   t |ttfr
|}n| |}| js$| | | }tt| j	j
}n| j	j}|dur1t||}||_| jdkrK|j}|j| jjrK| 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   rC  )r   rG   r;   r@  r{   _insert_inaxis_grouper_inplace_consolidaterC   r#  rx   r   r"  _insert_quantile_levelr+  rs   r   r'  rr   r   _reindex_output)rX   rA  rC  r   r+  rY   rY   rZ   _wrap_aggregated_output  s    



zGroupBy._wrap_aggregated_outputc                 C  sF   t |ttfr
|}n| |}| jdkr|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   rG   r;   r@  rs   r   rr   r   r+  )rX   rA  r   rY   rY   rZ   _wrap_transformed_output  s   



z GroupBy._wrap_transformed_outputr  r   c                 C  r  rV   r  )rX   datar  r   r  rY   rY   rZ   _wrap_applied_output  s   zGroupBy._wrap_applied_outputhowr   c              	   C  s   |t ju r0| jjdkr.|dk}| jr| jj}n| j}| }t|j	r-t|j	s-|j
s-d}nd}|re| jjdkret| jjsetjt| j d| d| d| jj dtt d tt| j d| d	|S )
a  
        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
        axis : int
            Axis passed to the groupby op (not self.axis).

        Returns
        -------
        bool
           r   F.z called with numeric_only= and dtype z;. This will raise a TypeError in a future version of pandas)categoryr   z  does not implement numeric_only)r   r   rr   r   rs   r   r   _get_numeric_datar   r   r   r-   dtyper   r   r   rb   r   r&   NotImplementedError)rX   rN  r   rs   rr   checkrY   rY   rZ   _resolve_numeric_only#  s2   

zGroupBy._resolve_numeric_onlyr   c                 C  sL   | j jdkr |jdkr"t|jt| j jk r$tt| || dS dS dS dS )a:  Emit warning on numeric_only behavior deprecation when appropriate.

        Parameters
        ----------
        how : str
            Groupby kernel name.
        result :
            Result of the groupby operation.
        numeric_only : bool or lib.no_default
            Argument as passed by user.
        r   N)r   r   r   r   r   r   )rX   rN  r   r   rY   rY   rZ   _maybe_warn_numeric_only_deprX  s   
z%GroupBy._maybe_warn_numeric_only_deprc                 C  s   | j j\}}}t||}tj||dd}|j|| jd }t| j j	dkr*t
d|j}t|tr>| j j	d j}	||	}|| }
t||\}}|||
|fS )NF)
allow_fillr   r   zAMore than 1 grouping labels are not supported with engine='numba'r   )rx   r$  rH   r(  take_ndr-  rs   to_numpyr   r  rU  r+  r   rD   re   get_level_valuesr   generate_slices)rX   rL  idsr5  r   sorted_index
sorted_idssorted_data
index_data	group_keysorted_index_datastartsendsrY   rY   rZ   _numba_prepp  s&   


zGroupBy._numba_prepr   engine_kwargsdict[str, bool] | Nonec                 G  s   | j std| jdkrtd|   | j}W d   n1 s"w   Y  |jdkr.|n| }| |\}}}}	tj	|fi t
|}
|
|	||dg|R  }| jj}|jdkrdd|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.NrO  r   re   r   r+  )r{   rU  rs   r   r   r   to_framerg  r4   generate_shared_aggregatorrI   rx   r"  re   ravelr   _constructor)rX   r   rh  aggregator_argsrL  dfre  rf  r_  ra  
aggregatorr   r+  result_kwargsrY   rY   rZ   _numba_agg_general  s.   






zGroupBy._numba_agg_general)rh  c                O  sf   |  |\}}}}	t| tj|fi t||}
|
|	|||t|jg|R  }|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.
        r   r   )
rg  r>   validate_udfgenerate_numba_transform_funcrI   r   r   r-  r   argsort)rX   rL  r   rh  r_   r`   re  rf  r_  ra  numba_transform_funcr   rY   rY   rZ   _transform_with_numba  s"   	

zGroupBy._transform_with_numbac                O  sV   |  |\}}}}	t| tj|fi t||}
|
|	|||t|jg|R  }|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.
        )rg  r>   rs  generate_numba_agg_funcrI   r   r   )rX   rL  r   rh  r_   r`   re  rf  r_  ra  numba_agg_funcr   rY   rY   rZ   _aggregate_with_numba  s"   	
zGroupBy._aggregate_with_numbarN   	dataframerO   )inputr   c                   sj  t ttr4t| r,t| }t|r| i S  s#r*td |S td d s8r\trIt	 fdd}ntt
d rXtt
d }ntd}tdd H z	| || j}W n- ty   |   | || jW  d     Y W  d    S 1 sw   Y  Y n	w W d    |S W d    |S 1 sw   Y  |S )	Nz"Cannot pass arguments to property z$apply func should be callable, not 'r   c                   sF   t jdd | g R i W  d    S 1 sw   Y  d S )Nr   )all)r   errstate)r  r_   r   r`   rY   rZ   ra     s   $zGroupBy.apply.<locals>.fnanz6func must be a callable if args or kwargs are suppliedzmode.chained_assignment)r   is_builtin_funcr   rf   hasattrrg   callabler   r   r   r3   r   r   r   r   )rX   r   r_   r`   resra   r   rY   r  rZ   rc     sL   




	

zGroupBy.applyra   rL  bool | Noner   is_aggc                 C  s   | j ||| j\}}|du r|p| j}d}|ot|dk}	|s7| jtju r7|s7|	s7d}
tj	|
t
t d d}| j||||p?|dS )aK  
        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.
        is_transform : bool, default False
            Indicator for whether the function is actually a transform
            and should not have group keys prepended. This is used
            in _make_wrapper which generates both transforms (e.g. diff)
            and non-transforms (e.g. corr)
        is_agg : bool, default False
            Indicator for whether the function is an aggregation. When the
            result is empty, we don't want to warn for this case.
            See _GroupBy._python_agg_general.

        Returns
        -------
        Series or DataFrame
            data after applying f
        NFr   a|  Not prepending group keys to the result index of transform-like apply. In the future, the group keys will be included in the index, regardless of whether the applied function returns a like-indexed object.
To preserve the previous behavior, use

	>>> .groupby(..., group_keys=False)

To adopt the future behavior and silence this warning, use 

	>>> .groupby(..., group_keys=True)r   T)r  )rx   rc   rs   ry   r   r~   r   r   r   r   r   r&   rM  )rX   ra   rL  r   r   r  r  ry   r  is_empty_aggr   rY   rY   rZ   r     s(   %

zGroupBy._python_apply_general)raise_on_typeerrorc             	     s   t  fdd}i }| jdkr| j|| jddS t|  D ]1\}}|j}	z	| j	||}
W n t
yH   |r= tt| ddd Y q#w tj|	|d	}|
||< q#|s^| || jS | |S )
Nc                   s   | g R i S rV   rY   r   r  rY   rZ   r   h  r   z-GroupBy._python_agg_general.<locals>.<lambda>r   T)r  aggFr   )labelposition)r   r  r   r   r   	enumerater  re   rx   
agg_seriesr   r   r   r=   	OutputKeyrJ  )rX   r   r  r_   r`   ra   rA  idxrr   re   r   r   rY   r  rZ   _python_agg_generale  s,   




zGroupBy._python_agg_generalr  	min_countaliasnpfuncc                C  sN   |    | j||||d}|j| jddW  d    S 1 s w   Y  d S )N)rN  altr   r  rR   method)r   _cython_agg_general__finalize__rr   )rX   r   r  r  r  r   rY   rY   rZ   _agg_general  s   

$zGroupBy._agg_generalr   r   r  c                 C  s~   |j dkr
t|}nt|j}|jd dksJ |jdddf }| jj||dd}t|t	r9t
|j||jd}t||dS )zn
        Fallback to pure-python aggregation if _cython_operation raises
        NotImplementedError.
        r   Nr   T)preserve_dtyperT  )r   )r   rG   r;   r   shapeilocrx   r  r   r7   r   _from_sequencerT  rF   )rX   r  r   r  serro  
res_valuesrY   rY   rZ   _agg_py_fallback  s   
	


zGroupBy._agg_py_fallbackignore_failuresc                   s   j |dd} jdk}t}	|r?|r7tjjs7d}
dv r'd}
ttj	 d d|
 d|s?j
d	d
d fdd}j||d}|sbt||	k rbtt| |}|rsjj|_|S |S )Nr   r   r   r   anyr}  	bool_onlyrP  z does not implement Fr   r  r   rT   c                   sR   zj jd| fjd d}W |S  ty(   j| j d}Y |S w )N	aggregater   rs   r  )r   r  )rx   _cython_operationr   rU  r  )r  r   r  rL  rN  r`   r  rX   rY   rZ   
array_func  s    z/GroupBy._cython_agg_general.<locals>.array_funcr  r  r   rT   r   )rW  _get_data_to_aggregater   r   r-   r   rT  rU  r   rb   get_numeric_datagrouped_reducer   _wrap_agged_managerrx   r"  r+  rI  )rX   rN  r  r   r  r  r`   numeric_only_boolis_serorig_lenkwd_namer  new_mgrr  rY   r  rZ   r    s.   



zGroupBy._cython_agg_generalc                 K  r  rV   r  )rX   rN  r   rs   r`   rY   rY   rZ   _cython_transform  r   zGroupBy._cython_transform)enginerh  c          
      O  st  t |rY|   | j}W d    n1 sw   Y  |jdkr"|n| }| j||g|R d|i|}| jjdkrItt| jj	||j
|jdS tt| jj	| |j
|jdS t|p_|}t|tsq| j|g|R i |S |tjvrd| d}	t|	|tjv s|tjv rt| ||i |S t| dd t| ||i |}W d    n1 sw   Y  | |S )	NrO  rh  r+  r   r+  re   r   z2' is not a valid function name for transform(name)r|   T)rJ   r   r   r   rj  rw  rr   r   r;   rm  r+  r   rG   rl  re   r   get_cython_funcr   rf   _transform_generalr=   transform_kernel_allowlistr   cythonized_kernelsr   rg   temp_setattr_wrap_transform_fast_result)
rX   r   r  rh  r_   r`   rL  ro  r   r   rY   rY   rZ   
_transform  sB   





zGroupBy._transformc                 C  s   | j }| jj\}}}|j| jj| jdd}| jjdkr.t	|j
|}|j||j|jd}|S |jdkr5dn| j}|j||dd}|j|| j|d}|S )z7
        Fast transform path for aggregations.
        Fr  r   r  r   )rs   convert_indicesr   )r   rx   r$  r.  r"  rs   rr   r   r(  rZ  r*  rm  r+  re   _taker8  r  )rX   r   rr   r^  r5  outrA  rs   rY   rY   rZ   r  5  s   	z#GroupBy._wrap_transform_fast_resultc                 C  s   t |dkrtjg dd}ntt|}|r#| jj|| jd}|S tjt | jj	t
d}|d d||t< t|t| jjdd  dg j}| j|}|S )Nr   int64r  r   FTr   )r   r   arrayru   concatenater   r-  rs   r   r+  r   fillastyper   tiler   r  r   where)rX   r   rw   filteredr2  rY   rY   rZ   _apply_filterQ  s   
$zGroupBy._apply_filter	ascending
np.ndarrayc                 C  s2  | j j\}}}t||}|| t|}}|dkr!tjdtjdS tjd|dd |dd kf }ttjt	|d |f }| 
 }	|rS|	t|	| |8 }	nt|	tj|dd df  ||	 }	| j jr{t|dktj|	jtjdd}	n|	jtjdd}	tj|tjd}
tj|tj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   Fr  )rx   r$  rH   r   r   r   r  r_diffnonzerocumsumrepeatr   r  r  r  float64intparange)rX   r  r^  r5  r   sortercountrunrepr  revrY   rY   rZ   _cumcount_arrayb  s"   
"
&"zGroupBy._cumcount_arrayc                 C  s,   t | jtr
| jjS t | jtsJ | jjS rV   )r   rr   r;   _constructor_slicedrG   rm  r]   rY   rY   rZ   _obj_1d_constructor  s   zGroupBy._obj_1d_constructorval_testLiteral['any', 'all']skipnac                   sB   d f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.
        valsr   rT   tuple[np.ndarray, type]c                   s   t | jr$ rtjdd tgd}|| } n| jtdd} ttj| } nt| t	r2| 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)r1   r   r  rY   rY   rZ   r     r   z9GroupBy._bool_agg.<locals>.objs_to_bool.<locals>.<lambda>)otypesFr  )r.   rT  r   	vectorizer   r  r   ndarrayr   r5   _dataviewint8)r  r   r  rY   rZ   objs_to_bool  s   



z'GroupBy._bool_agg.<locals>.objs_to_boolFr   r  	inferencer   nullabler   c                 S  s*   |rt | jtdd| dkS | j|ddS )NFr  r  )r6   r  r   )r   r  r  rY   rY   rZ   result_to_bool  s   z)GroupBy._bool_agg.<locals>.result_to_boolT)r   cython_dtype
needs_maskneeds_nullablepre_processingpost_processingr  r  N)r  r   rT   r  )F)r   r  r  r   r  r   rT   r   )_get_cythonized_result
libgroupbygroup_any_allr   rT  r  )rX   r  r  r  r  rY   r  rZ   	_bool_agg  s   

zGroupBy._bool_aggrR   r   c                 C     |  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.
        r  r  rX   r  rY   rY   rZ   r       zGroupBy.anyc                 C  r  )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  rY   rY   rZ   r}    r  zGroupBy.allc                   s   |   }| jj\ } dk|jdkd fdd}||}t| dd	 | |}W d
   n1 s:w   Y  |jdkrI| 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   bvaluesr   rT   c                   sr   | j dkrt| dd @ }nt|  @ }tj| dd}r7|j dks*J |jd dks3J |d S |S )Nr   r  )r1  max_binrs   rO  r   )r   r1   reshaper   count_level_2dr  )r  maskedcountedr^  	is_seriesr2  r   rY   rZ   hfunc  s   
zGroupBy.count.<locals>.hfuncr|   TNr   
fill_value)r  r   rT   r   )r  rx   r$  r   r  r   r  r  r"  r+  rI  )rX   rL  r5  r  r  r   rY   r  rZ   r    s   



zGroupBy.count)see_alsocythonr  c                   sX   | j d|dd t|rddlm} | ||S | 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.

        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
        meanr   r   )sliding_meanc                      t | j dS Nr  )rG   r  r  r  rY   rZ   r   j      zGroupBy.mean.<locals>.<lambda>r  r   rR   r  )rW  rJ   pandas.core._numba.kernelsr  rr  r  r  rr   )rX   r   r  rh  r  r   rY   r  rZ   r    s   I
zGroupBy.meanc                   s8   | j d|dd | 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.
        medianr   r   c                   r  r  )rG   r  r  r  rY   rZ   r     r  z GroupBy.median.<locals>.<lambda>r  rR   r  )rW  r  r  rr   )rX   r   r   rY   r  rZ   r  o  s   
zGroupBy.medianr   ddof
str | Nonec                 C  s   t |rddlm} t| |||S | jd|dd}|r;| jjdkr;t	| jj
s;tt| j d| d| jj
 | jtjt
tj|dd	d
 |d}| d|| |S )aE  
        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

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

            .. versionadded:: 1.5.0

        Returns
        -------
        Series or DataFrame
            Standard deviation of values within each group.
        r   sliding_varstdr   r   z.std called with numeric_only=rQ  Tc                 S  r   rV   )r   sqrtr  r  rY   rY   rZ   r     r   zGroupBy.std.<locals>.<lambda>)r  r   needs_countsr  r  )rJ   r  r  r   r  rr  rW  rr   r   r-   rT  r   r   rb   r  r  	group_varr  rX  )rX   r  r  rh  r   r  r  r   rY   rY   rZ   r    s6   /


zGroupBy.stdc                   sD   t |rddlm} | || S | jd fdd||tju  dS )a1  
        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

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

            .. versionadded:: 1.5.0

        Returns
        -------
        Series or DataFrame
            Variance of values within each group.
        r   r  varc                   r  )Nr  )rG   r  r  r  rY   rZ   r   	  r  zGroupBy.var.<locals>.<lambda>)r  r   r  r  )rJ   r  r  rr  r  r   r   )rX   r  r  rh  r   r  rY   r  rZ   r    s   /
zGroupBy.varc           	   	   C  s$  | j d|dd}|r'| jjdkr't| jjs'tt| j d| d| jj | j||d}| 	d|| |jdkrE|t
|   }|S |j| j }|  }|j|}|j|}t & tdd	 |jd
d
|f  t
|jd
d
|f   < W d
   |S 1 sw   Y  |S )a  
        Compute standard error of the mean of groups, excluding missing values.

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

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

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

            .. versionadded:: 1.5.0

        Returns
        -------
        Series or DataFrame
            Standard error of the mean of values within each group.
        semr   r   r   z.sem called with numeric_only=rQ  )r  r   r   z*.*will attempt to set the values inplace.*N)rW  rr   r   r-   rT  r   r   rb   r  rX  r   r  r  r   r   r}   uniqueget_indexer_forr   r   r   r  )	rX   r  r   r  r   colscountsr9  count_ilocsrY   rY   rZ   r   	  s@   



0
zGroupBy.semc                 C  sV   | j  }t| jtr| j|| jjd}n| |}| js$|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  )rx   r&  r   rr   rG   r  re   r{   renamereset_indexrI  r?  rY   rY   rZ   r&  H	  s   

zGroupBy.sizesum)fnamenomcc                 C  sp   t |rddlm} | ||S t| dd | j||dtjd}W d    n1 s,w   Y  | j	|ddS )Nr   )sliding_sumr|   Tr)  r   r  r  r  r  )
rJ   r  r-  rr  r   r  r  r   r)  rI  )rX   r   r  r  rh  r-  r   rY   rY   rZ   r)  d	  s   	zGroupBy.sumprodc                 C  s   | j ||dtjdS )Nr/  r.  )r  r   r/  )rX   r   r  rY   rY   rZ   r/  	  s   
zGroupBy.prodminc                 C  6   t |rddlm} | ||dS | j||dtjdS )Nr   sliding_min_maxFr0  r.  )rJ   r  r3  rr  r  r   r0  rX   r   r  r  rh  r3  rY   rY   rZ   r0  	     	zGroupBy.minmaxc                 C  r1  )Nr   r2  Tr6  r.  )rJ   r  r3  rr  r  r   r6  r4  rY   rY   rZ   r6  	  r5  zGroupBy.maxc                 C     dddd}| j ||d|d	S )a  
        Compute the first non-null entry of each column.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns.
        min_count : int, default -1
            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
            First non-null of values within each group.

        See Also
        --------
        DataFrame.groupby : Apply a function groupby to each row or column of a
            DataFrame.
        DataFrame.core.groupby.GroupBy.last : Compute the last non-null entry of each
            column.
        DataFrame.core.groupby.GroupBy.nth : Take the nth row from each group.

        Examples
        --------
        >>> df = pd.DataFrame(dict(A=[1, 1, 3], B=[None, 5, 6], C=[1, 2, 3],
        ...                        D=['3/11/2000', '3/12/2000', '3/13/2000']))
        >>> df['D'] = pd.to_datetime(df['D'])
        >>> df.groupby("A").first()
             B  C          D
        A
        1  5.0  1 2000-03-11
        3  6.0  3 2000-03-13
        >>> df.groupby("A").first(min_count=2)
            B    C          D
        A
        1 NaN  1.0 2000-03-11
        3 NaN  NaN        NaT
        >>> df.groupby("A").first(numeric_only=True)
             B  C
        A
        1  5.0  1
        3  6.0  3
        r   rr   r   rs   r   c                 S  @   ddd}t | tr| j||dS t | tr|| S tt| )Nr   rG   c                 S  &   | j t| j  }t|stjS |d S )z-Helper function for first item that isn't NA.r   r  r2   r   r   r  r   arrrY   rY   rZ   first	     z2GroupBy.first.<locals>.first_compat.<locals>.firstr   r   rG   r   r;   rc   rG   r   r   )rr   rs   r=  rY   rY   rZ   first_compat	     


z#GroupBy.first.<locals>.first_compatr=  r.  Nr   rr   r   rs   r   r  )rX   r   r  rA  rY   rY   rZ   r=  	  s   1zGroupBy.firstc                 C  r7  )an  
        Compute the last non-null entry of each column.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns. If None, will attempt to use
            everything, then use only numeric data.
        min_count : int, default -1
            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
            Last non-null of values within each group.

        See Also
        --------
        DataFrame.groupby : Apply a function groupby to each row or column of a
            DataFrame.
        DataFrame.core.groupby.GroupBy.first : Compute the first non-null entry of each
            column.
        DataFrame.core.groupby.GroupBy.nth : Take the nth row from each group.

        Examples
        --------
        >>> df = pd.DataFrame(dict(A=[1, 1, 3], B=[5, None, 6], C=[1, 2, 3]))
        >>> df.groupby("A").last()
             B  C
        A
        1  5.0  2
        3  6.0  3
        r   rr   r   rs   r   c                 S  r8  )Nr   rG   c                 S  r9  )z,Helper function for last item that isn't NA.r  r:  r;  rY   rY   rZ   last#
  r>  z/GroupBy.last.<locals>.last_compat.<locals>.lastr   r?  r@  )rr   rs   rF  rY   rY   rZ   last_compat"
  rB  z!GroupBy.last.<locals>.last_compatrF  r.  NrC  rD  rE  )rX   r   r  rG  rY   rY   rZ   rF  	  s   &zGroupBy.lastr;   c                 C  sz   | j jdkr4| j}t|j}|std| jjd|jdddd}g d}| 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 aggregater  ohlcr   r  r  )openhighlowcloser  c                 S  s   |   S rV   )rH  r  rY   rY   rZ   r   Y
  r   zGroupBy.ohlc.<locals>.<lambda>)rr   r   r   r-   rT  r!   rx   r  r*  _constructor_expanddimr"  rI  _apply_to_column_groupbysr   )rX   rr   
is_numericr  	agg_namesr   rY   rY   rZ   rH  8
  s    



zGroupBy.ohlcc                   s   |   V t| jdkr3| jjdi  }| jjdkr|}n| }| jjd d W  d    S | j	 fdd| jdd}| j
dkrO|jW  d    S | W  d    S 1 s]w   Y  d S )Nr   r   c                   s   | j di  S )NrY   )describer  r`   rY   rZ   r   h
  r  z"GroupBy.describe.<locals>.<lambda>T)r   rY   )r   r   r   rQ  r   unstackrj  r   r  r   rs   )rX   r`   	describedr   rY   rR  rZ   rQ  \
  s$   
	

$zGroupBy.describec                 O  s$   ddl m} || |g|R i |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)pandas.core.resamplerU  )rX   ruler_   r`   rU  rY   rY   rZ   resamplep
  s   bzGroupBy.resamplerM   c                 O  s.   ddl m} || jg|R | j| jd|S )zV
        Return a rolling grouper, providing rolling functionality per group.
        r   )rM   )_grouper	_as_index)pandas.core.windowrM   r   rx   r{   )rX   r_   r`   rM   rY   rY   rZ   rolling
  s   zGroupBy.rollingrK   c                 O  *   ddl m} || jg|R d| ji|S )zc
        Return an expanding grouper, providing expanding
        functionality per group.
        r   )rK   rY  )r[  rK   r   rx   )rX   r_   r`   rK   rY   rY   rZ   	expanding
  s   zGroupBy.expandingrL   c                 O  r]  )zO
        Return an ewm grouper, providing ewm functionality per group.
        r   )rL   rY  )r[  rL   r   rx   )rX   r_   r`   rL   rY   rY   rZ   ewm
  s   zGroupBy.ewm	directionLiteral['ffill', 'bfill']c                   s   |du rd}j j\}}}tj|ddjtjdd}|dkr%|ddd }ttj||||j	d d fdd}j
}jdkrD|j}|j}||}	||	}
t|
trZ|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  	mergesort)kindFr  bfill)r1  sorted_labelsr`  limitrw   r  r   rT   c                   s   t | }| jdkrtj| jtjd} ||d t| |S t| tj	r9| j
}jjr0t| j
}tj| j|d}nt| j| j| j
d}tt| D ]#}tj| jd tjd} ||| d t| | |||d d f< qJ|S )Nr   r  )r  r2  )r1   r   r   r   r  r  r(  rZ  r   r  rT  rx   r   r'   r   _emptyr#  r   )r  r2  r4  rT  r  icol_funcrX   rY   rZ   blk_func2  s    


zGroupBy._fill.<locals>.blk_funcr   r  )rx   r$  r   ru  r  r  r   r  group_fillna_indexerrw   r   rs   r   _mgrrc   rm  r   rG   re   rK  )rX   r`  rf  r^  r5  re  rk  rr   mgrres_mgrnew_objrY   ri  rZ   _fill  s0   	




zGroupBy._fillc                 C     | 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rf  rq  rX   rf  rY   rY   rZ   rs  ]     zGroupBy.ffillc                 C     t jdtt d | j|dS )aE  
        Forward fill the values.

        .. deprecated:: 1.4
            Use ffill instead.

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

        Returns
        -------
        Series or DataFrame
            Object with missing values filled.
        zMpad is deprecated and will be removed in a future version. Use ffill instead.r   rt  )r   r   r   r&   rs  rv  rY   rY   rZ   padv     zGroupBy.padc                 C  rr  )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.
        rd  rt  ru  rv  rY   rY   rZ   rd    rw  zGroupBy.bfillc                 C  rx  )aF  
        Backward fill the values.

        .. deprecated:: 1.4
            Use bfill instead.

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

        Returns
        -------
        Series or DataFrame
            Object with missing values filled.
        zRbackfill is deprecated and will be removed in a future version. Use bfill instead.r   rt  )r   r   r   r&   rd  rv  rY   rY   rZ   backfill  rz  zGroupBy.backfillrA   c                 C  r   )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
        )rA   r]   rY   rY   rZ   nth  s   kzGroupBy.nthr   PositionalIndexer | tupleLiteral['any', 'all', None]c                 C  s0  |so|   a | |}| jj\}}}||dk@ }| |}| js*|W  d    S | jj}| jdkrM|||  |_| j	sGt
|trG||}| |}n|||  |_| jr^|j| jdn|W  d    S 1 sjw   Y  t|swtd|dvrtd| dtt|}|dkr|nd| }| jj|| jd}	| jd u r| jd u r| jj}
|
|
|	j }nd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|_|S || jj}|S )Nr  r   r   z4dropna option only supported for an integer argumentr  z_For a DataFrame or Series groupby.nth, dropna must be either None, 'any' or 'all', (was passed z).)rN  rs   r   )r   rs   rv   ru   ry   )r{   ru   rs   )&r   "_make_mask_from_positional_indexerrx   r$  _mask_selected_objr{   r"  rs   r+  r|   r   rB   r.  rI  r   ru   r:  r+   r   r   r   rr   rw   rt   rv   isinr   r   ry   rR   r&  r|  r*  r   r  r   r  loc)rX   r   rw   r2  r^  r5  r  r"  max_lendroppedrs   rx   r   grbsizesr   rY   rY   rZ   _nth0  sn   




 
	

zGroupBy._nthg      ?linearinterpolationc                   s  | j d|dd}|r'| jjdkr't| jjs'tt| j d| d| jj ddddfddt|}|r<|g}t	j
|t	jd}| jj\}}t|ttj||d t|dkrd| d nd}	t	|dk|	|d fdd}
| j}|jdk}|  }|r| n|}|}|j|
|d}|tju r|st|jt|jkrtt| d| t|jdkr|j|
dd td|r| |}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.
        numeric_only : bool, default True
            Include only `float`, `int` or `boolean` data.

            .. versionadded:: 1.5.0

        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
        quantiler   r   r   z#.quantile called with numeric_only=rQ  r  r   rT   "tuple[np.ndarray, np.dtype | None]c                 S  s  t | rtdd }t| jr)t| tr| jttj	d}n| }ttj
}||fS t| jr?t| tr?| jttj	d}||fS t| jrUtd}t| t}||fS t| jrktd}t| t}||fS t| trt| rttj}| jttj	d}||fS t| }||fS )Nz7'quantile' cannot be performed against 'object' dtypes!)rT  na_valuezdatetime64[ns]ztimedelta64[ns])r.   r   r,   rT  r   r8   r[  floatr   r  r  r(   r)   asarrayr  r0   r*   r  )r  r  r  rY   rY   rZ   pre_processor  s8   







z'GroupBy.quantile.<locals>.pre_processorr  r  np.dtype | Nonec                   s"   |rt |r
 dv s| |} | S )N>   r  midpoint)r,   r  r  )r  rY   rZ   post_processor  s   
z(GroupBy.quantile.<locals>.post_processorr  )r1  rC  r  r  r  c           
        s   t | }| \}}d}|jdkr!|jd }t|tf}n}tj|ftjd}||f}t|j	tj
dd}|jdkrM |d |||d nt|D ]}	 ||	 ||	 ||	 ||	 d qQ|jdkro|d}n|| }||S )	Nr   rO  r   r  Fr  )r  r2  sort_indexerK)r1   r   r  r   broadcast_tor   r   r  lexsortr  r  r#  rl  r  )
r  r2  r  r  ncolsshaped_labelsr  ordersort_arrrh  )r   labels_for_lexsortr   nqsr  r  rY   rZ   rk    s(   


"

z"GroupBy.quantile.<locals>.blk_funcr  F*All columns were dropped in grouped_reducerE  N)r  r   rT   r  )r  r  r  r  rT   r  r  )rW  rr   r   r-   rT  r   r   rb   r/   r   r  r  rx   r$  r   r   r  group_quantiler6  r  r   r  r  r  r   r   itemsr   r  rm  rJ  )rX   qr  r   r  orig_scalarrC  r^  r5  na_label_for_sortingrk  rr   r  rn  rL  r  ro  r  rY   )r   r  r  r   r  r  r  rZ   r    sl   ,







zGroupBy.quantilec                 C  s   |   : | jj}| jjd }| jjr!t|dktj|}tj	}ntj
}| j|||d}|s5| jd | }|W  d   S 1 sAw   Y  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  r   N)r   r   r+  rx   r$  r   r   r  r  r  r  r  r   )rX   r  r+  comp_idsrT  r   rY   rY   rZ   ngroup>  s   
=$zGroupBy.ngroupc                 C  sR   |    | j| j}| j|d}| ||W  d   S 1 s"w   Y  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  rs   r  r  )rX   r  r+  	cumcountsrY   rY   rZ   cumcount  s
   
7
$zGroupBy.cumcountaveragekeepr  	na_optionpctc           	        st   |dvr
d}t |||||d dkr.dd<  fdd}| j|| j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
        >   topr  bottomz3na_option must be one of 'keep', 'top', or 'bottom')ties_methodr  r  r  r   r  r  c                   s   | j d ddS )NF)rs   r   rY   rankr  rs   r`   rY   rZ   r     r   zGroupBy.rank.<locals>.<lambda>Tr   r  F)r   rs   Nr  )r   popr   r   r  )	rX   r  r  r  r  rs   r   ra   r   rY   r  rZ   r    s.   HzGroupBy.rankc                   L   t d|ddg  dkr fdd}| j|| jddS | jd
i S )zq
        Cumulative product for each group.

        Returns
        -------
        Series or DataFrame
        cumprodr   r  r   c                      | j dd iS Nrs   rY   r  r  r  rY   rZ   r   6  r   z!GroupBy.cumprod.<locals>.<lambda>Tr  Nr  nvvalidate_groupby_funcr   r   r  rX   rs   r_   r`   ra   rY   r  rZ   r  )  
   zGroupBy.cumprodc                   r  )zm
        Cumulative sum for each group.

        Returns
        -------
        Series or DataFrame
        r  r   r  r   c                   r  r  r  r  r  rY   rZ   r   H  r   z GroupBy.cumsum.<locals>.<lambda>Tr  Nr  r  r  rY   r  rZ   r  ;  r  zGroupBy.cumsumc                   s`   | dd} dkr( fdd}| d| }| j}|r | }| j||ddS | jd||d	S )
zm
        Cumulative min for each group.

        Returns
        -------
        Series or DataFrame
        r  Tr   c                      t j|  S rV   )r   minimum
accumulater  r   rY   rZ   r   Z      z GroupBy.cummin.<locals>.<lambda>cummaxr  cumminr   r  r   rW  r   rS  r   r  rX   rs   r   r`   r  ra   r  rr   rY   r   rZ   r  M     zGroupBy.cumminc                   s`   | dd} dkr( fdd}| d| }| j}|r | }| j||ddS | jd||dS )	zm
        Cumulative max for each group.

        Returns
        -------
        Series or DataFrame
        r  Tr   c                   r  rV   )r   maximumr  r  r   rY   rZ   r   r  r  z GroupBy.cummax.<locals>.<lambda>r  r  r  r  r  rY   r   rZ   r  e  r  zGroupBy.cummax	base_funcr  np.dtyper  r  r  c	                   s,   j }
	j|
|dd}rtstdrtstd	j}|j\}}t |d d 	f
d	d
}	j}|jdk}		 }t
|}|rT| }|j|dd}|st
|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
        r   r   z%'post_processing' must be a callable!z$'pre_processing' must be a callable!)r1  r  r   rT   c           
        st  | j } | jdkr
dn| jd }tj| d}||f}t |d}d }r8tj	jtjd}t||d}| }rB|\}}|j	dd}|jdkrS|d}t||d}rtt
| tj}|jdkrn|d	d}t||d
}rt| t}t||d}|di  | jdkr|jd dksJ |j|d d df }ri }	rt| t|	d< ||fi |	}|j S )Nr   r  )r  )r$  Fr  )r  r   )r  r  )r2  )r  r   r  rY   )r   r   r  r   zerosr  r   r   r  r  r1   r  uint8r   r5   )
r  r  r   r   
inferencesr$  r  r2  is_nullable	pp_kwargs
r  r  r`   r  r  r  r   r  r  rX   rY   rZ   rk    sD   




z0GroupBy._get_cythonized_result.<locals>.blk_funcr   Tr  group_ Fr  Nr  )rb   rW  r  r   rx   r$  r   r   r   r  r   r  r  r  replacer   r   r   r  rm  rJ  )rX   r  r  r   r  r  r  r  r  r`   rN  r  rx   r^  r5  rk  rr   r  rn  orig_mgr_lenro  howstrr  rY   r  rZ   r  }  s:   4 2


zGroupBy._get_cythonized_resultc                   s   dus dkr fdd}| j || j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 rV   )shiftr  rs   r	  freqperiodsrY   rZ   r   /  r  zGroupBy.shift.<locals>.<lambda>Tr  r  )r	  
allow_dups)r   r   rx   r$  r   r  r   r  r  group_shift_indexerr   _reindex_with_indexersrs   r&  )rX   r  r  rs   r	  ra   r^  r5  r   res_indexerrr   r  rY   r  rZ   r    s   zGroupBy.shiftr  c                   s    dkr|   fddS | j}| j d}ddg|jdkr/|jv r+|d}|| S fd	d
|j D }t|rI|dd |D }|| S )a  
        First discrete difference of element.

        Calculates the difference of each element compared with another
        element in the group (default is element in previous row).

        Parameters
        ----------
        periods : int, default 1
            Periods to shift for calculating difference, accepts negative values.
        axis : axis to shift, default 0
            Take difference over rows (0) or columns (1).

        Returns
        -------
        Series or DataFrame
            First differences.
        r   c                   s   | j  dS )Nr  rs   )r  r  )rs   r  rY   rZ   r   W  r  zGroupBy.diff.<locals>.<lambda>r  r  int16r   float32c                   s   g | ]
\}}| v r|qS rY   rY   )r   crT  )dtypes_to_f32rY   rZ   r   c  s    z GroupBy.diff.<locals>.<listcomp>c                 S  s   i | ]}|d qS )r  rY   )r   r  rY   rY   rZ   
<dictcomp>e      z GroupBy.diff.<locals>.<dictcomp>)	rc   r   r  r   rT  r  dtypesr  r   )rX   r  rs   rr   shifted	to_coercerY   )rs   r  r  rZ   r  @  s   


zGroupBy.diffrs  c           
        s   dus dkr fdd}| j || jddS du r#ddt| d}|j| 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_methodrf  r  rs   )
pct_changer  rs   r  r  rf  r  rY   rZ   r   x  s    z$GroupBy.pct_change.<locals>.<lambda>Tr  rs  rt  )rs   r~   )r  r  rs   r   )	r   r   rg   rR   rx   codesrs   r~   r  )
rX   r  r  rf  r  rs   ra   filledfill_grpr  rY   r  rZ   r  i  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  rX   r   r2  rY   rY   rZ   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  rY   rY   rZ   tail  s
   $

zGroupBy.tailr2  npt.NDArray[np.bool_]c                 C  s@   | j jd }||dk@ }| jdkr| j| S | jjdd|f S )a  
        Return _selected_obj with mask applied to the correct axis.

        Parameters
        ----------
        mask : np.ndarray[bool]
            Boolean mask to apply.

        Returns
        -------
        Series or DataFrame
            Filtered _selected_obj.
        r   r  N)rx   r$  rs   r   r  )rX   r2  r^  rY   rY   rZ   r    s
   

zGroupBy._mask_selected_objr	  r   c                 C  s  | j j}t|dkr|S | jr|S tdd |D s|S dd |D }| j j}|dur5|| |dg }tj||d	 \}}| j
rX| j| j|dd	d
|i}	|jdi |	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 rV   )r   grouping_vectorr7   rB   r   pingrY   rY   rZ   r     s
    
z*GroupBy._reindex_output.<locals>.<genexpr>c                 S  s   g | ]}|j qS rY   )group_indexr  rY   rY   rZ   r   %  r  z+GroupBy._reindex_output.<locals>.<listcomp>N)r   r   Fr	  c                 s  s$    | ]\}}|j r||jfV  qd S rV   )r  re   )r   rh  r  rY   rY   rZ   r   B  s    

)r1  rs   )r   r	  )rv   T)droprY   )rx   r  r   r|   r  r   appendrD   from_product	sortlevelr{   rr   _get_axis_namers   r.  r  r   r  r   	set_indexr"  r(  )rX   rA  r	  rC  r  levels_listr   r+  r5  din_axis_grpsg_numsg_namesrY   rY   rZ   rI    s>    

zGroupBy._reindex_output
int | Nonefracfloat | Noner  weightsSequence | Series | Nonerandom_stateRandomState | Nonec                 C  s   t |||}|durt j| j|| jd}t|}| j| j| j}g }	|D ]9\}
}| j	|
 }t
|}|dur;|}n|dusAJ t|| }t j ||||du rRdn|| |d}|	||  q't|	}	| 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	  )sampleprocess_sampling_sizepreprocess_weightsr   rs   r   r	  rx   r   r   r   roundr  r   r  r-  )rX   r   r  r  r  r	  r&  weights_arrgroup_iteratorsampled_indicesr1  rr   grp_indices
group_sizesample_size
grp_samplerY   rY   rZ   r  T  s2   `



zGroupBy.sampleNr   NNNNTTTFFFT)rr   r   rt   r   rs   r   rv   ro   rx   r   r}   r   r   ro   r{   r   ru   r   r~   r   rz   r   r|   r   ry   r   rw   r   rT   rU   )ri   rf   )re   rf   rT   r   )rT   rU   )rT   r  )rT   r  )FF)r   r   r  r   )r   r   rT   r   )r   r=  rT   r>  rV   )rA  rB  rC  rD  )rA  r=  rT   r>  )r  r   r   r   r  r   )rN  rf   r   r   rs   r   rT   r   )rN  rf   r   r   r   r   rT   rU   )r   r   rh  ri  )rT   r   )NFF)ra   r   rL  r   r   r  r   r   r  r   rT   r   )Tr  )r   r   r  r   r  rf   r  r   )r  r   r   r   r  r   rT   r   )r  T)
rN  rf   r  r   r   r   r  r   r  r   )Tr   )rN  rf   r   r   rs   r   )r   r   rT   r   )T)r  r   rT   r  )rT   r   )r  r  r  r   )r  r   )r   r   r  rf   rh  ri  )r   r   )r  r   r  r  rh  ri  r   r   )r  r   r   r   r   )r   r   r  r   r  r  rh  ri  )r   r   r  r   )Fr  NN)r   r   r  r   r  r  rh  ri  )Fr  )r   r   r  r   )rT   r;   )rT   rM   )rT   rK   )rT   rL   )r`  ra  )rT   rA   )r   r}  rw   r~  rT   r   )r  rf   r   r   )r  r   )r  Tr  Fr   )r  rf   r  r   r  rf   r  r   rs   r   rT   r   rC  )r   F)r  r   r  r  r   r   r  r   r  r   r  r   )r   Nr   N)r   r   )r  r   rs   r   rT   r   )r   rs  NNr   )r  )r   r   rT   r   )r2  r  rT   r   )rA  r   r	  r   rC  rD  rT   r   )NNFNN)
r   r  r  r  r  r   r  r  r	  r
  )arb   rk   rl   rm   r   r   r[   rj   r  r  r  r   r   r  r6  r   r@  rJ  rK  rM  rW  rX  rg  rr  rw  rz  r"   _apply_docsformatrc   r   r  r  r  r  r  r  r  r  r  r   r  r  r#   _common_see_alsor  r}  r  r   r   r  r  r  r  r   r&  r%   _groupby_agg_method_templater)  r/  r0  r6  r=  rF  rH  r;   rQ  rX  r\  r^  r_  rq  rs  ry  rd  r{  r|  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   NaNrI  r  rY   rY   rY   rZ   rS   M  s6  
 C:
I
I6!	5
"6H!(?-
'.+TG93E:!

eTl\ 2K:_ .&$)^rS   TFrr   r<   byr   rs   r   rx   r   r{   r   ru   r~   r   rz   r|   ry   rw   rT   c                 C  sj   t | trddlm} |}nt | trddlm} |}ntd|  || |||||||||	|
|||dS )Nr   )SeriesGroupBy)DataFrameGroupByzinvalid type: )rr   rt   rs   rv   rx   r}   r   r{   ru   r~   rz   r|   ry   rw   )r   rG   pandas.core.groupby.genericr  r;   r  r   )rr   r  rs   rv   rx   r}   r   r{   ru   r~   rz   r|   ry   rw   r  r   r  rY   rY   rZ   get_groupby  s.   

r   r  rC   rC  npt.NDArray[np.float64]rD   c                   s   t | | jr<tt| } t| \}}t| j|g } fdd| jD t	
|t | g }t||| jdg d}|S 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 rY   )r   r  )r   r   r  rY   rZ   r     s    z*_insert_quantile_level.<locals>.<listcomp>N)r  r  r   )r   	_is_multir   rD   rC   	factorizer   r  r  r   r  r   r  )r  rC  	lev_codeslevr  r  mirY   r"  rZ   rH    s   
&rH  rN  rf   rU   c                 C  sn   |t jur|stjd| j d| d| dtt d d S |t ju r5tjd| j d| dtt d d S d S )NzDropping invalid columns in rP  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   z%The default value of numeric_only in z is deprecated. In a future version, numeric_only will default to False. Either specify numeric_only or select only columns which should be valid for the function.)r   r   r   r   rb   r   r&   )clsrN  r   rY   rY   rZ   r   !  s.   

	
r   r  )rr   r<   r  r   rs   r   rx   r   r{   r   ru   r   r~   r   rz   r   r|   r   ry   r   rw   r   rT   rS   )r  rC   rC  r!  rT   rD   )rN  rf   rT   rU   )rm   
__future__r   
contextlibr   r   	functoolsr   r   r  textwrapr   r   typingr   r   r	   r
   r   r   r   r   r   r   r   r   r   r   numpyr   pandas._config.configr   pandas._libsr   r   pandas._libs.groupby_libsrR   r  pandas._typingr   r   r   r   r   r   r   r   pandas.compat.numpyr   r  pandas.errorsr    r!   pandas.util._decoratorsr"   r#   r$   r%   pandas.util._exceptionsr&   pandas.core.dtypes.castr'   pandas.core.dtypes.commonr(   r)   r*   r+   r,   r-   r.   r/   r0   pandas.core.dtypes.missingr1   r2   pandas.corer3   pandas.core._numbar4   pandas.core.algorithmscorer(  pandas.core.arraysr5   r6   r7   r8   pandas.core.baser9   r:   pandas.core.commoncommonr   pandas.core.framer;   pandas.core.genericr<   pandas.core.groupbyr=   r>   r?   pandas.core.groupby.indexingr@   rA   pandas.core.indexes.apirB   rC   rD   rE   pandas.core.internals.blocksrF   pandas.core.sampler  pandas.core.seriesrG   pandas.core.sortingrH   pandas.core.util.numba_rI   rJ   r[  rK   rL   rM   r  r  r  r   _transform_template_agg_templaterQ   _KeysArgTypern   r   rS   r   rH  r   rY   rY   rY   rZ   <module>   s    <(
,	5A -3 M
	 X                           #
/