
    Pi                   (   U d Z ddlmZ ddlmZmZmZmZmZm	Z	 ddl
Z
ddlmZmZ ddl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mZ ddlm Z  ddl!m"c m#Z$ dd	l%m&Z& dd
l'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0 ddl1m2Z3 ddl4m5Z5m6Z6m7Z7 ddl8m9Z9 ddl:m;Z; ddl<m=Z=m>Z> ddl?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZL ddlMmNZNmOZOmPZP ddlQmRZRmSZS ddlTmUZU ddlVmWZWmXZXmYZYmZZZm[Z[m\Z\ ddl]m^Z^ ddl_m`Z` ddlambZbmcZc ddldmec mfZg ddlhmiZi ddljmkZk ddllmmZmmnZnmoZo ddlpmqZq ddlrmsZsmtZt ddlumvZvmwZwmxZx ddlymzZz ddl{m|Z| dd l}m~Z~ dd!lmZmZmZ er,dd"lmZ dd#lmZ dd$l'mZmZmZ dd%lmZ dd&lmZ dd'lmZmZmZ d(Zd)Zd*Zd+Ze G d, d-eb                      Zeee         z  eegef         z  eeegef                  z  eeef         z  Zd.ed/<    G d0 d1ebece-         es          Z ed2ek3          Z G d4 d5ee-                   Z	 	 	 dGdHd@ZdIdFZdS )Ja  
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)CallableHashableIterableIteratorMappingSequenceN)partialwraps)
TYPE_CHECKINGConcatenateLiteralSelf	TypeAliasTypeVarUnioncastfinaloverload)	Timestamplib)rank_1d)NA)	AnyArrayLike	ArrayLikeDtypeObj
IndexLabelIntervalClosedTypeNDFrameTPositionalIndexerRandomStatenpt)function)AbstractMethodError	DataErrorPandas4Warning)cache_readonly)find_stack_level)coerce_indexer_dtypeensure_dtype_can_hold_na)is_boolis_bool_dtypeis_float_dtypeis_hashable
is_integeris_integer_dtypeis_list_likeis_numeric_dtypeis_object_dtype	is_scalaris_string_dtypeneeds_i8_conversionpandas_dtype)isnana_value_for_dtypenotna)
algorithmssample)executor)ArrowExtensionArrayBaseMaskedArrayExtensionArrayFloatingArrayIntegerArraySparseArray)StringDtype)ArrowStringArray)PandasObjectSelectionMixin)	DataFrame)NDFrame)basenumba_ops)get_grouper)GroupByIndexingMixinGroupByNthSelector)Index
MultiIndexdefault_index)ensure_block_shape)Series)get_group_index_sorter)get_jit_argumentsmaybe_use_numbaprepare_function_arguments)
BaseOffset)	Timedelta)AnyPT)BaseIndexer)	Resampler)ExpandingGroupbyExponentialMovingWindowGroupbyRollingGroupbya  
Compute {fname} of group values.

Parameters
----------
numeric_only : bool, default {no}
    Include only float, int, boolean columns.

    .. versionchanged:: 2.0.0

        numeric_only no longer accepts ``None``.

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.

engine : str, default None {e}
    * ``'cython'`` : Runs rolling apply through C-extensions from cython.
    * ``'numba'`` : Runs rolling apply through JIT compiled code from numba.
        Only available when ``raw`` is set to ``True``.
    * ``None`` : Defaults to ``'cython'`` or globally setting
        ``compute.use_numba``

engine_kwargs : dict, default None {ek}
    * 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 both the ``func`` and the ``apply`` groupby aggregation.

Returns
-------
Series or DataFrame
    Computed {fname} of values within each group.

See Also
--------
SeriesGroupBy.min : Return the min of the group values.
DataFrameGroupBy.min : Return the min of the group values.
SeriesGroupBy.max : Return the max of the group values.
DataFrameGroupBy.max : Return the max of the group values.
SeriesGroupBy.sum : Return the sum of the group values.
DataFrameGroupBy.sum : Return the sum of the group values.

Examples
--------
{example}
aV  
Compute {fname} of group values.

Parameters
----------
numeric_only : bool, default {no}
    Include only float, int, boolean columns.

    .. versionchanged:: 2.0.0

        numeric_only no longer accepts ``None``.

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.

skipna : bool, default {s}
    Exclude NA/null values. If the entire group is NA and ``skipna`` is
    ``True``, the result will be NA.

    .. versionchanged:: 3.0.0

engine : str, default None {e}
    * ``'cython'`` : Runs rolling apply through C-extensions from cython.
    * ``'numba'`` : Runs rolling apply through JIT compiled code from numba.
        Only available when ``raw`` is set to ``True``.
    * ``None`` : Defaults to ``'cython'`` or globally setting
        ``compute.use_numba``

engine_kwargs : dict, default None {ek}
    * 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 both the ``func`` and the ``apply`` groupby aggregation.

Returns
-------
Series or DataFrame
    Computed {fname} of values within each group.

See Also
--------
SeriesGroupBy.min : Return the min of the group values.
DataFrameGroupBy.min : Return the min of the group values.
SeriesGroupBy.max : Return the max of the group values.
DataFrameGroupBy.max : Return the max of the group values.
SeriesGroupBy.sum : Return the sum of the group values.
DataFrameGroupBy.sum : Return the sum of the group values.

Examples
--------
{example}
a*  
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 = lambda x, arg2, arg3: x + 1 - arg2 * arg3
>>> g = lambda x, arg1: x * 5 / arg1
>>> f = lambda x: x ** 4
>>> df = pd.DataFrame([["a", 4], ["b", 5]], columns=["group", "value"])
>>> h(g(f(df.groupby('group')), arg1=1), arg2=2, arg3=3)  # doctest: +SKIP

You can write

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

which is much more readable.

Parameters
----------
func : callable or tuple of (callable, str)
    Function to apply to this %(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
-------
%(klass)s
    The original object with the function `func` applied.

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

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

Examples
--------
%(examples)s
a  
Call function producing a 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
----------
func : function, str
    Function to apply to each group. See the Notes section below for requirements.

    Accepted inputs are:

    - String
    - Python function
    - 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.

    If a string is chosen, then it needs to be the name
    of the groupby method you want to use.
*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``

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

**kwargs
    Keyword arguments to be passed into func.

Returns
-------
%(klass)s
    %(klass)s with the same indexes as the original object filled
    with transformed values.

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.
%(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.

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

.. versionchanged:: 2.0.0

    When using ``.transform`` on a grouped DataFrame and the transformation function
    returns a DataFrame, pandas now aligns the result's index
    with the input's index. You can call ``.to_numpy()`` on the
    result of the transformation function to avoid alignment.

Examples
--------
%(example)sc                  (    e Zd ZdZddZd Zdd
ZdS )GroupByPlotzE
    Class implementing the .plot attribute for groupby objects.
    groupbyGroupByreturnNonec                    || _         d S N)_groupby)selfre   s     o/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/pandas/core/groupby/groupby.py__init__zGroupByPlot.__init__  s        c                j    fd}d|_         | j                            || j        j                  S )Nc                     | j         i S rj   )plot)rl   argskwargss    rm   fzGroupByPlot.__call__.<locals>.f  s    49d-f---ro   rr   )__name__rk   _python_apply_general_selected_obj)rl   rs   rt   ru   s    `` rm   __call__zGroupByPlot.__call__  sH    	. 	. 	. 	. 	. 	. 
}221dm6QRRRro   namestrc                      fd}|S )Nc                 `      fd}j                             |j         j                  S )Nc                :     t          | j                  i S rj   )getattrrr   )rl   rs   rt   rz   s    rm   ru   z0GroupByPlot.__getattr__.<locals>.attr.<locals>.f  s$    /wty$//@@@@ro   )rk   rw   rx   )rs   rt   ru   rz   rl   s   `` rm   attrz%GroupByPlot.__getattr__.<locals>.attr  sN    A A A A A A A =66q$-:UVVVro    )rl   rz   r   s   `` rm   __getattr__zGroupByPlot.__getattr__  s/    	W 	W 	W 	W 	W 	W ro   N)re   rf   rg   rh   rz   r{   )rv   
__module____qualname____doc__rn   ry   r   r   ro   rm   rd   rd     sX                S S S     ro   rd   r   _KeysArgTypec                     e Zd ZU ej        h dz  Zded<   dZded<   dZded<   d	ed
<   ed*d            Z	ed+d            Z
eed,d                        Zeed*d                        Zeed-d                        Zed             Zeed                         Zed.d            Zed/d             Zed0d#            Zd1d%Zed2d'            Zed3d)            ZdS )4BaseGroupBy>
   objkeyssortleveldropnagrouperas_indexobserved
exclusions
group_keysops.BaseGrouper_grouperN_KeysArgType | Noner   IndexLabel | Noner   boolr   rg   intc                    | j         j        S rj   r   ngroupsrl   s    rm   __len__zBaseGroupBy.__len__  s    }$$ro   r{   c                6    t                               |           S rj   )object__repr__r   s    rm   r   zBaseGroupBy.__repr__  s     t$$$ro   dict[Hashable, Index]c                   t          | j        t                    r]t          | j                  dk    rEt	          j        d| j        d          d| j        d          dt          t                                 | j        j	        S )aQ  
        Dict {group name -> group labels}.

        This property provides a dictionary representation of the groupings formed
        during a groupby operation, where each key represents a unique group value from
        the specified column(s), and each value is a list of index labels
        that belong to that group.

        See Also
        --------
        core.groupby.DataFrameGroupBy.get_group : Retrieve group from a
            ``DataFrameGroupBy`` object with provided name.
        core.groupby.SeriesGroupBy.get_group : Retrieve group from a
            ``SeriesGroupBy`` object with provided name.
        core.resample.Resampler.get_group : Retrieve group from a
            ``Resampler`` object with provided name.

        Examples
        --------

        For SeriesGroupBy:

        >>> lst = ["a", "a", "b"]
        >>> ser = pd.Series([1, 2, 3], index=lst)
        >>> ser
        a    1
        a    2
        b    3
        dtype: int64
        >>> ser.groupby(level=0).groups
        {'a': ['a', 'a'], 'b': ['b']}

        For DataFrameGroupBy:

        >>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]]
        >>> df = pd.DataFrame(data, columns=["a", "b", "c"])
        >>> df
           a  b  c
        0  1  2  3
        1  1  5  6
        2  7  8  9
        >>> df.groupby(by="a").groups
        {1: [0, 1], 7: [2]}

        For Resampler:

        >>> ser = pd.Series(
        ...     [1, 2, 3, 4],
        ...     index=pd.DatetimeIndex(
        ...         ["2023-01-01", "2023-01-15", "2023-02-01", "2023-02-15"]
        ...     ),
        ... )
        >>> ser
        2023-01-01    1
        2023-01-15    2
        2023-02-01    3
        2023-02-15    4
        dtype: int64
        >>> ser.resample("MS").groups
        {Timestamp('2023-01-01 00:00:00'): np.int64(2),
         Timestamp('2023-02-01 00:00:00'): np.int64(4)}
           zWIn a future version, the keys of `groups` will be a tuple with a single element, e.g. (r   z,) , instead of a scalar, e.g. z, when grouping by a list with a single element. Use ``df.groupby(by='a').groups`` instead of ``df.groupby(by=['a']).groups`` to avoid this warning)
stacklevel)

isinstancer   listlenwarningswarnr&   r(   r   groupsr   s    rm   r   zBaseGroupBy.groups  s    B di&& 		3ty>>Q+>+>MS6:ilS S-1Yq\S S S
 +--    }##ro   c                    | j         j        S rj   r   r   s    rm   r   zBaseGroupBy.ngroups(  s     }$$ro   $dict[Hashable, npt.NDArray[np.intp]]c                    | j         j        S )ak  
        Dict {group name -> group indices}.

        The dictionary keys represent the group labels (e.g., timestamps for a
        time-based resampling operation), and the values are arrays of integer
        positions indicating where the elements of each group are located in the
        original data. This property is particularly useful when working with
        resampled data, as it provides insight into how the original time-series data
        has been grouped.

        See Also
        --------
        core.groupby.DataFrameGroupBy.indices : Provides a mapping of group rows to
            positions of the elements.
        core.groupby.SeriesGroupBy.indices : Provides a mapping of group rows to
            positions of the elements.
        core.resample.Resampler.indices : Provides a mapping of group rows to
            positions of the elements.

        Examples
        --------

        For SeriesGroupBy:

        >>> lst = ["a", "a", "b"]
        >>> ser = pd.Series([1, 2, 3], index=lst)
        >>> ser
        a    1
        a    2
        b    3
        dtype: int64
        >>> ser.groupby(level=0).indices
        {'a': array([0, 1]), 'b': array([2])}

        For DataFrameGroupBy:

        >>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]]
        >>> df = pd.DataFrame(
        ...     data, columns=["a", "b", "c"], index=["owl", "toucan", "eagle"]
        ... )
        >>> df
                a  b  c
        owl     1  2  3
        toucan  1  5  6
        eagle   7  8  9
        >>> df.groupby(by=["a"]).indices
        {np.int64(1): array([0, 1]), np.int64(7): array([2])}

        For Resampler:

        >>> ser = pd.Series(
        ...     [1, 2, 3, 4],
        ...     index=pd.DatetimeIndex(
        ...         ["2023-01-01", "2023-01-15", "2023-02-01", "2023-02-15"]
        ...     ),
        ... )
        >>> ser
        2023-01-01    1
        2023-01-15    2
        2023-02-01    3
        2023-02-15    4
        dtype: int64
        >>> ser.resample("MS").indices
        defaultdict(<class 'list'>, {Timestamp('2023-01-01 00:00:00'): [0, 1],
        Timestamp('2023-02-01 00:00:00'): [2, 3]})
        )r   indicesr   s    rm   r   zBaseGroupBy.indices-  s    J }$$ro   c                2   d t          |          r%| j                            t          j        g           S t          |t                    rt          d |D                       }t          | j                  dk    r"t          t          | j                            }nd}t          |t                    rt          |t                    sd}t          |          t          |          t          |          k    s2	 | j        |         S # t          $ r}d}t          |          |d}~ww xY wfd|D             }t          d t          ||d	
          D                       }n |          } ||          }| j                            |g           S )zd
        Safe get multiple indices, translate keys for
        datelike to underlying repr.
        c                |    t          | t          j                  rd S t          | t          j                  rd S d S )Nc                     t          |           S rj   )r   keys    rm   <lambda>z?BaseGroupBy._get_index.<locals>.get_converter.<locals>.<lambda>  s    9S>> ro   c                *    t          |           j        S rj   )r   asm8r   s    rm   r   z?BaseGroupBy._get_index.<locals>.get_converter.<locals>.<lambda>  s    9S>>#6 ro   c                    | S rj   r   r   s    rm   r   z?BaseGroupBy._get_index.<locals>.get_converter.<locals>.<lambda>  s    3 ro   )r   datetimenp
datetime64)ss    rm   get_converterz-BaseGroupBy._get_index.<locals>.get_converter{  sG     !X.// '111Ar}-- '666&&ro   c              3  P   K   | ]!}t          |          rt          j        n|V  "d S rj   )r8   r   nan).0comps     rm   	<genexpr>z)BaseGroupBy._get_index.<locals>.<genexpr>  s3      IID4::74IIIIIIro   r   Nz<must supply a tuple to get_group with multiple grouping keyszHmust supply a same-length tuple to get_group with multiple grouping keysc              3  .   K   | ]} |          V  d S rj   r   )r   r   r   s     rm   r   z)BaseGroupBy._get_index.<locals>.<genexpr>  s-      AAq--**AAAAAAro   c              3  2   K   | ]\  }} ||          V  d S rj   r   )r   ru   ns      rm   r   z)BaseGroupBy._get_index.<locals>.<genexpr>  s.      MM$!Q1MMMMMMro   Tstrict)r8   r   getr   r   r   tupler   nextiter
ValueErrorKeyErrorzip)rl   rz   index_samplemsgerr
converters	converterr   s          @rm   
_get_indexzBaseGroupBy._get_indext  s   	' 	' 	' :: 	0<##BFB///dE"" 	JIIDIIIIIDt|q  T\ 2 233LLLlE** 	#dE** &T oo%t99L 1 111	3<-- 3 3 36  %S//s23 BAAALAAAJMM#j$t*L*L*LMMMMMDD%l33I9T??D|b)))s   ?D 
D-D((D-c                    t          | j        t                    r| j        S | j        -t	          | j                  r| j        | j                 S | j        S | j        S rj   )r   r   rT   
_selectionr.   _obj_with_exclusionsr   s    rm   rx   zBaseGroupBy._selected_obj  s\     dh'' 	8O?&4?++ 1 x00
 ,,xro   set[str]c                4    | j                                         S rj   )r   _dir_additionsr   s    rm   r   zBaseGroupBy._dir_additions  s    x&&(((ro   func!Callable[Concatenate[Self, P], T]rs   P.argsrt   P.kwargsr]   c                    d S rj   r   rl   r   rs   rt   s       rm   pipezBaseGroupBy.pipe  	     Cro   tuple[Callable[..., T], str]r[   c                    d S rj   r   r   s       rm   r   zBaseGroupBy.pipe  r   ro   @Callable[Concatenate[Self, P], T] | tuple[Callable[..., T], str]c                .    t          j        | |g|R i |S )a  
        Apply a ``func`` with arguments to this GroupBy object and return its result.

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

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

        You can write

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

        which is much more readable.

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

        Returns
        -------
        GroupBy
            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 GroupBy object.

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

        Examples
        --------
        >>> 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
        )comr   r   s       rm   r   zBaseGroupBy.pipe  s'    V xd4T444V444ro   DataFrame | Seriesc                   | j         }| j        }t          |          rt          |          dk    s"t          |          rSt          |          dk    r@t	          |t
                    rt          |          dk    r	|d         }nt          |          |                     |          }t          |          st          |          | j        j	        |         S )a*  
        Construct DataFrame from group with provided name.

        Parameters
        ----------
        name : object
            The name of the group to get as a DataFrame.

        Returns
        -------
        Series or DataFrame
            Get the respective Series or DataFrame corresponding to the group provided.

        See Also
        --------
        DataFrameGroupBy.groups: Dictionary representation of the groupings formed
            during a groupby operation.
        DataFrameGroupBy.indices: Provides a mapping of group rows to positions
            of the elements.
        SeriesGroupBy.groups: Dictionary representation of the groupings formed
            during a groupby operation.
        SeriesGroupBy.indices: Provides a mapping of group rows to positions
            of the elements.

        Examples
        --------

        For SeriesGroupBy:

        >>> lst = ["a", "a", "b"]
        >>> ser = pd.Series([1, 2, 3], index=lst)
        >>> ser
        a    1
        a    2
        b    3
        dtype: int64
        >>> ser.groupby(level=0).get_group("a")
        a    1
        a    2
        dtype: int64

        For DataFrameGroupBy:

        >>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]]
        >>> df = pd.DataFrame(
        ...     data, columns=["a", "b", "c"], index=["owl", "toucan", "eagle"]
        ... )
        >>> df
                a  b  c
        owl     1  2  3
        toucan  1  5  6
        eagle   7  8  9
        >>> df.groupby(by=["a"]).get_group((1,))
                a  b  c
        owl     1  2  3
        toucan  1  5  6

        For Resampler:

        >>> ser = pd.Series(
        ...     [1, 2, 3, 4],
        ...     index=pd.DatetimeIndex(
        ...         ["2023-01-01", "2023-01-15", "2023-02-01", "2023-02-15"]
        ...     ),
        ... )
        >>> ser
        2023-01-01    1
        2023-01-15    2
        2023-02-01    3
        2023-02-15    4
        dtype: int64
        >>> ser.resample("MS").get_group("2023-01-01")
        2023-01-01    1
        2023-01-15    2
        dtype: int64
        r   r   )
r   r   r1   r   r   r   r   r   rx   iloc)rl   rz   r   r   indss        rm   	get_groupzBaseGroupBy.get_group  s    \ y
 	%CJJ!OO %4#&t99>> $&& %3t99>>Awtnn$t$$4yy 	!4.. !&t,,ro   #Iterator[tuple[Hashable, NDFrameT]]c                   | j         }| j        }| j                            | j                  }t          |          rt          |          dk    s(t          |t                    rt          |          dk    rd |D             }|S )a	  
        Groupby iterator.

        This method provides an iterator over the groups created by the ``resample``
        or ``groupby`` operation on the object. The method yields tuples where
        the first element is the label (group key) corresponding to each group or
        resampled bin, and the second element is the subset of the data that falls
        within that group or bin.

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

        See Also
        --------
        Series.groupby : Group data by a specific key or column.
        DataFrame.groupby : Group DataFrame using mapper or by columns.
        DataFrame.resample : Resample a DataFrame.
        Series.resample : Resample a Series.

        Examples
        --------

        For SeriesGroupBy:

        >>> lst = ["a", "a", "b"]
        >>> ser = pd.Series([1, 2, 3], index=lst)
        >>> ser
        a    1
        a    2
        b    3
        dtype: int64
        >>> for x, y in ser.groupby(level=0):
        ...     print(f"{x}\n{y}\n")
        a
        a    1
        a    2
        dtype: int64
        b
        b    3
        dtype: int64

        For DataFrameGroupBy:

        >>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]]
        >>> df = pd.DataFrame(data, columns=["a", "b", "c"])
        >>> df
           a  b  c
        0  1  2  3
        1  1  5  6
        2  7  8  9
        >>> for x, y in df.groupby(by=["a"]):
        ...     print(f"{x}\n{y}\n")
        (1,)
           a  b  c
        0  1  2  3
        1  1  5  6
        (7,)
           a  b  c
        2  7  8  9

        For Resampler:

        >>> ser = pd.Series(
        ...     [1, 2, 3, 4],
        ...     index=pd.DatetimeIndex(
        ...         ["2023-01-01", "2023-01-15", "2023-02-01", "2023-02-15"]
        ...     ),
        ... )
        >>> ser
        2023-01-01    1
        2023-01-15    2
        2023-02-01    3
        2023-02-15    4
        dtype: int64
        >>> for x, y in ser.resample("MS"):
        ...     print(f"{x}\n{y}\n")
        2023-01-01 00:00:00
        2023-01-01    1
        2023-01-15    2
        dtype: int64
        2023-02-01 00:00:00
        2023-02-01    3
        2023-02-15    4
        dtype: int64
        r   c              3  &   K   | ]\  }}|f|fV  d S rj   r   )r   r   groups      rm   r   z'BaseGroupBy.__iter__.<locals>.<genexpr>  s,      ??*#uvuo??????ro   )	r   r   r   get_iteratorrx   r1   r   r   r   )rl   r   r   results       rm   __iter__zBaseGroupBy.__iter__|  s    t y
++D,>?? 	@CJJ!OOtT"" %4'*4yyA~~ @????Fro   )rg   r   )rg   r{   )rg   r   )rg   r   )rg   r   )r   r   rs   r   rt   r   rg   r]   )r   r   rs   r[   rt   r[   rg   r]   )r   r   rs   r[   rt   r[   rg   r]   rg   r   )rg   r   )rv   r   r   rF   _hidden_attrs__annotations__r   r   r   r   r   propertyr   r   r   r   r'   rx   r   r   r   r   r   r   ro   rm   r   r     s9         . 2 2 2 M  $D$$$$#E####
% % % U% % % % U% I$ I$ I$ X UI$V % % % X U% C% C% C% X UC%J 0* 0* U0*d   ^ U& ) ) ) U)    X    XK5 K5 K5 K5Z \- \- \- U\-| b b b Ub b bro   r   OutputFrameOrSeries)boundc                     e Zd ZU dZded<   ded<   e	 	 	 	 	 	 	 	 	 	 ddd            ZddZedd            Ze	 	 ddd"            Z	edd%            Z
e	 ddd*            Ze	 ddd+            Z	 	 ddd.Zedd0            Zdd7Zedd8d9            Zedd8d:            Zdd;dd=Ze	 	 	 dddB            Ze	 	 dddDddK            ZddPZe	 	 	 dddQ            ZdddRZedddSdT            ZedddSdU            ZeddV            ZedW             ZedddZ            Zeedd[                        Zeddd]            Zeddd^            Z edd_            Z!e	 	 	 	 dddb            Z"edddc            Z#e	 	 	 	 	 dddf            Z$e	 	 	 	 	 dddg            Z%e	 	 	 	 	 dddk            Z&e	 dddl            Z'eddm            Z(e	 	 	 	 	 dddo            Z)e	 dddp            Z*e	 	 	 	 	 dddq            Z+e	 	 	 	 	 dddr            Z,e	 ddds            Z-e	 dddt            Z.eddu            Z/	 	 	 dddvZ0edd;ddx            Z1e	 	 	 	 	 	 ddd            Z2e	 	 dd d            Z3e	 	 	 	 	 	 	 	 	 ddd            Z4edӐdd            Z5edӐdd            Z6edӐdd            Z7eedd                        Z8	 dӐddZ9e	 	 	 ddd            Z:edd	d            Z;edd	d            Z<e	 	 	 	 d
dd            Z=eddd            Z>eddd            Z?e	 ddd            Z@e	 ddd            ZAedddeBjC        dfdd            ZDe	 ddd            ZEe	 	 	 ddd            ZFeddd            ZGeddd            ZHedd            ZIe	 	 	 	 	 dddƄ            ZJ	 	 	 dddɄZKdd˄ZLdS (  rf   t  
    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
    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)
        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   r   r   r   NTFr   r   r   r   r   r   r   ops.BaseGrouper | Noner   frozenset[Hashable] | None	selectionr   r   r   r   rg   rh   c                r   || _         t          |t                    sJ t          |                      || _        || _        || _        || _        |	| _        || _	        |t          |||||
| j	                  \  }}}|
| _        || _        || _        |rt          |          nt                      | _        d S )N)r   r   r   r   )r   r   rI   typer   r   r   r   r   r   rM   r   r   r   	frozensetr   )rl   r   r   r   r   r   r   r   r   r   r   r   s               rm   rn   zGroupBy.__init__,  s     $#w''22c22'
 		$?'2!{( ( ($GZ !3=N)J///9;;ro   r   r{   c                    || 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__r   AttributeErrorr   rv   )rl   r   s     rm   r   zGroupBy.__getattr__U  sn    4+++**466648:GT

#GGGGG
 
 	
ro   rz   c                ^   t          t          | j                  |          fd}||_        |t          j        v r|                     || j                  S |t          j        v }|                     || j        ||           }| j	        j
        r|r|                     |          }|S )z<Compute the result of an operation by using GroupBy's apply.c                     | gR i S rj   r   )xrs   ru   rt   s    rm   curriedz&GroupBy._op_via_apply.<locals>.curriedd  s#    1Q(((((((ro   )is_transformnot_indexed_same)r   r   r   rv   rJ   plotting_methodsrw   rx   transformation_kernelsr   has_dropped_na_set_result_index_ordered)rl   rz   rs   rt   r
  r  r   ru   s     ``   @rm   _op_via_applyzGroupBy._op_via_apply_  s     D233T::	) 	) 	) 	) 	) 	) 	)
   4(((--gt7IJJJt::++%%!--	 , 
 
 =' 	<L 	< 33F;;Fro   r  r  c                L   ddl m} | j        rM|sK| j        r6| j        j        }| j        j        }| j        j        } ||d|||d          }n ||d          }n|s ||d          }| j        j	        }	| j
        r| j        j        }
|
dk    }|	|         }	|	j        rn|j        d                             |	          sNt          j        |	j                  }|j	                            |          \  }}|                    |d          }n%|                    |	d          }n ||d          }| j        j        dk    r| j        j        }nt1          | j                  r| j        }nd }t5          |t6                    r	|||_        |                    | j        d	          S )
Nr   concatF)axisr   levelsnamesr   r  r   re   method)pandas.core.reshape.concatr  r   r   r   result_indexr  r  rx   indexr   idshas_duplicatesaxesequalsr;   unique1d_valuesget_indexer_non_uniquetakereindexr   ndimrz   r.   r   r   rT   __finalize__)rl   valuesr  r  r  r   group_levelsgroup_namesr   axlabelsmasktargetindexer_rz   s                   rm   _concat_objectszGroupBy._concat_objects  s    	655555? *	,< *	,} 0!]7
#}3"m1#'%    Q///! 	,VF+++F#)B{ *|X   4Q)>)>r)B)B 4#,RZ88#\@@HH
W15533 VF+++F8=A8=DD)) 	?DDDff%% 	$*:FK""48I">>>ro   r   r   c                   | j         j        }| j        j        r%| j        j        s|                    |d          }|S t          | j        j        d          }|                    |d          }|                    d          }| j        j        r1|	                    t          t          |                    d          }|                    |d          }|S )Nr   r  Fcopy)r   r  r   is_monotonicr  set_axisrP   result_ilocs
sort_indexr'  rR   r   )rl   r   r  original_positionss       rm   r  z!GroupBy._set_result_index_ordered  s     =% 	dm.J 	__U_33FM #4=#=EJJJ!3!<<"""**=' 	G ^^M#e**$=$=A^FFFQ//ro   Series | DataFrameqsnpt.NDArray[np.float64] | NonerH   c                   t          |t                    r|                                }t          | j        j                  }|J|                    dd| t          j        |t          |          t          |          z                       t          t          t          | j        j                  | j                                        d                    D ]\  }\  }}||dk    r|dn
d||z
  dz
   }||j        vr`||                    d||           B|                    d|t          t          j        |t          |                    d                     |S )	Nr   level_Tr   r   r  Fr5  )r   rT   to_framer   r   	groupingsinsertr   tile	enumerater   reversedr  get_group_levelscolumnsrP   repeat)rl   r   r=  n_groupingsr   rz   levs          rm   _insert_inaxis_grouperzGroupBy._insert_inaxis_grouper  s|    ff%% 	'__&&F$-122>MM)K))272s6{{c"gg7M+N+N  
 #,,--..00  #
 #
 	W 	WE;D# | #a''BJ G;+"5"9;;  6>)):MM!T3////MM!T53B1H1Hu+U+U+UVVVro   c                    | j         sM|                     ||          }|                                }t          t	          |                    |_        n%| j        j        }|t          ||          }||_        |S )z
        Wraps the output of GroupBy aggregations into the expected result.

        Parameters
        ----------
        result : Series, DataFrame

        Returns
        -------
        Series or DataFrame
        r=  )	r   rL  _consolidaterR   r   r  r   r  _insert_quantile_level)rl   r   r=  r  s       rm   _wrap_aggregated_outputzGroupBy._wrap_aggregated_output  s~    ( } 	! 00B0??F((**F(V55FLL M.E~ /ub99 FLro   r*  r   c                     t          |           rj   r$   )rl   datar*  r  r  s        rm   _wrap_applied_outputzGroupBy._wrap_applied_output*  s     "$'''ro   rT  c                   | j         j        }| j         j        }| j         j        }|                    |d                                          }|j        }t          |t                    rXt          | j         j
                  dk    rt          d          | j         j
        d         j        }|                    |          }|                    |                                          }t          j        ||          \  }	}
|	|
||fS )Nr   r  r   z_Grouping with more than 1 grouping labels and a MultiIndex is not supported with engine='numba')r   r   r9  _sorted_idsr&  to_numpyr  r   rQ   r   rB  NotImplementedErrorrz   get_level_valuesr   generate_slices)rl   rT  r   sorted_index
sorted_idssorted_data
index_data	group_keysorted_index_datastartsendss              rm   _numba_prepzGroupBy._numba_prep6  s    -'}1].
ii1i55>>@@Z
j*-- 	@4=*++a//)H   /27I#44Y??J&OOL99BBDD*:w??	
 	
ro   r   r   dtype_mappingdict[np.dtype, Any]engine_kwargsdict[str, bool] | Nonec                   | j         st          d          | j        }|j        dk    r|n|                                }t          j        ||dfi t          |          }| j        j	        }| j        j
        }	 |j        j        |f||	d|}
| j        j        |
j        d<   |                    |
|
j                  }|j        dk    r"|                    d          }|j        |_        n|j        |_        |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.   T)r.  r   r   )r!  rH  )r   rY  r   r(  rA  r=   generate_shared_aggregatorrV   r   r  r   _mgrapplyr  r!  _constructor_from_mgrsqueezerz   rH  )rl   r   re  rg  aggregator_kwargsrT  df
aggregatorr  r   res_mgrr   s               rm   _numba_agg_generalzGroupBy._numba_agg_generalQ  s     } 	%N   (Y!^^TT8
 
  ..	
 

 m-'"'-
"G
 
7H
 
 -4Q))')EE9>>^^I..F)FKK!\FNro   )rg  c          	     R   | j         }| j        j        }|j        dk    r|n|                                }|                     |          \  }}	}
}t          j        |           t          |||d          \  }}t          j	        |fi t          |          } |||
||	t          |j                  g|R  }|                    t          j        |          d          }|j        }|j        dk    rd|j        i}|                                }n	d|j        i} |j        |fd|i|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.
        rj  num_required_argsr   r  r   rz   rH  r  )r   r   r9  r(  rA  rd  rK   validate_udfrX   generate_numba_transform_funcrV   r   rH  r&  r   argsortr  rz   ravel_constructor)rl   r   rg  rs   rt   rT  index_sortingrq  rb  rc  r\  r^  numba_transform_funcr   r  result_kwargss                   rm   _transform_with_numbazGroupBy._transform_with_numba|  s`    (2Y!^^TT262B2B22F2F/lKD!!!1$!
 
 
f  &C 
  
%m44 
  
 &%
OO
 
 
 
 RZ66Q??
9>>#TY/M\\^^FF&5M t FFuFFFFro   c          	     p   | j         }|j        dk    r|n|                                }|                     |          \  }}}	}
t	          j        |           t          |||d          \  }}t	          j        |fi t          |          } ||
|	||t          |j
                  g|R  }| j        j        }|j        dk    rd|j        i}|                                }n	d|j
        i} |j        |fd|i|}| j        s6|                     |          }t%          t          |                    |_        |S )a*  
        Perform groupby aggregation routine with the numba engine.

        This routine mimics the data splitting routine of the DataSplitter class
        to generate the indices of each group in the sorted data and then passes the
        data and indices into a Numba jitted function.
        rj  rv  r   rz   rH  r  )r   r(  rA  rd  rK   rx  rX   generate_numba_agg_funcrV   r   rH  r   r  rz   r{  r|  r   rL  rR   r  )rl   r   rg  rs   rt   rT  rq  rb  rc  r\  r^  numba_agg_funcr   r  r  ress                   rm   _aggregate_with_numbazGroupBy._aggregate_with_numba  sn    (Y!^^TT262B2B22F2F/lKD!!!1$!
 
 
f  7
 
%m44
 
  
OO
 
 
 
 *9>>#TY/M\\^^FF&5MdEEeE}EE} 	0--c22C%c#hh//CI
ro   )include_groupsr  c                  |rt          d          t          t                    rbt          |           r?t	          |           }t          |          r |i S srt          d           |S t          d d          sr;t                    rt                    fd            }nt          d          }|                     || j	                  S )a  
        Apply function ``func`` group-wise and combine the results together.

        The function passed to ``apply`` must take a dataframe 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 dataframe as its first argument, and
            returns a dataframe, a series or a scalar. In addition the
            callable may take positional and keyword arguments.

        *args : tuple
            Optional positional arguments to pass to ``func``.

        include_groups : bool, default False
            When True, will attempt to apply ``func`` to the groupings in
            the case that they are columns of the DataFrame. If this raises a
            TypeError, the result will be computed with the groupings excluded.
            When False, the groupings will be excluded when applying ``func``.

            .. versionadded:: 2.2.0

            .. versionchanged:: 3.0.0

            The default changed from True to False, and True is no longer allowed.

        **kwargs : dict
            Optional keyword arguments to pass to ``func``.

        Returns
        -------
        Series or DataFrame
            A pandas object with the result of applying ``func`` to each group.

        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
        -----
        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
        --------
        >>> 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`` and ``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.

        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: int64

        Example 4: The function passed to ``apply`` returns ``None`` for one of the
        group. This group is filtered from the result:

        >>> g1.apply(lambda x: None if x.iloc[0, 0] == 3 else x)
           B  C
        0  1  4
        1  2  6
        )include_groups=True is no longer allowed.z"Cannot pass arguments to property z$apply func should be callable, not 'r  c                     | gR i S rj   r   )grs   r   rt   s    rm   ru   zGroupBy.apply.<locals>.fg  s#    43D333F333ro   z6func must be a callable if args or kwargs are supplied)
r   r   r{   hasattrr   callable	TypeErrorr   rw   r   )rl   r   r  rs   rt   r  ru   s    ` ``  rm   rm  zGroupBy.apply  sM   N  	JHIIIdC   	tT"" 	PdD))C== R3//// RV R$%P$%P%PQQQ
   Nt N N NOOO 	V 	~~ 	t4 4 4 4 4 4 4 4 !L   A))!T-FGGGro   ru   r   bool | Noneis_aggc                v    | j                             ||          \  }}||}|                     ||||          S )a  
        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.
        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
        )r   apply_groupwiserU  )rl   ru   rT  r  r  r  r*  mutateds           rm   rw   zGroupBy._python_apply_generalt  sP    F -774@@#&((	
 
 	
ro   r  )npfuncnumeric_only	min_countr   aliasr  Callable | Nonec               ^     | j         d||||d|}|                    | j        d          S )N)howaltr  r  re   r  r   _cython_agg_generalr)  r   )rl   r  r  r  r  rt   r   s          rm   _agg_generalzGroupBy._agg_general  sU     *) 
%	
 

 
 
 ""48I">>>ro   r  r   r(  r  c                f   |J |j         dk    rt          |d          }n?t          |j        |j                  }|j        d         dk    sJ |j        dddf         }	 | j                            ||d          }n9# t          $ r,}d	| d
|j         d}	 t          |          |	          |d}~ww xY w|j        }
|
t          k    r|                    t          d          }n:t          |
          r+|
                                }|                    ||
          }t!          ||          S )zn
        Fallback to pure-python aggregation if _cython_operation raises
        NotImplementedError.
        Nr   Fr5  dtyper   T)preserve_dtypezagg function failed [how->z,dtype->])r(  )r(  rT   rH   r]   r  shaper   r   
agg_series	Exceptionr   r   astyper5   construct_array_type_from_sequencerS   )rl   r  r*  r(  r  serrq  
res_valuesr   r   r  string_array_clss               rm   _agg_py_fallbackzGroupBy._agg_py_fallback  sb    ;!e,,,CC 686<888B 8A;!#### '!!!Q$-C
	*11#s41PPJJ 	* 	* 	*HsHHCIHHHC$s))C..c)	*
 	F??#**6*>>JJU## 	R$99;;)8858QQJ "*48888s   "B   
B6
'B11B6c                T   
 t          |          st          d                               |          
d

 fd}
                    |          }                     |          }dv r                     |d         	          }                     |          }	|	S )Nz(numeric_only accepts only Boolean valuesr  rz   r*  r   rg   c                    	  j         j        d| fj        dz
  d}|S # t          $ r$ dv rt	          | t
                    rndv r Y nw xY wJ                     | j                  }|S )N	aggregater   r  r  anyall)r  r  stdsem)r(  r  )r   _cython_operationr(  rY  r   rC   r  )r*  r   r  rT  r  rt   r  rl   s     rm   
array_funcz/GroupBy._cython_agg_general.<locals>.array_func  s    88 Q'   &  ' 	 	 	 .((Z-L-L([C+G$G$G	 ???**3TYC*PPFMs    % +AAidxminidxmaxskipna)r  r  r*  r   rg   r   )r+   r   _get_data_to_aggregategrouped_reduce_wrap_agged_manager_wrap_idxmax_idxminrQ  )rl   r  r  r  r  rt   r  new_mgrr  outrT  s   ``` ``    @rm   r  zGroupBy._cython_agg_general  s     |$$ 	IGHHH**3*OO	 	 	 	 	 	 	 	 	 	 	6 %%j11&&w//&&&**3Cx@P*QQC**3//
ro   c                     t          |           rj   rS  )rl   r  r  rt   s       rm   _cython_transformzGroupBy._cython_transform  s    !$'''ro   enginerg  c               \   t          |t                    s | j        |||g|R i |S |t          j        vrd| d}t          |          |t          j        v s|t          j        v r"|
||d<   ||d<    t          | |          |i |S | j	        r | j
        |g|R ||d|S t          j        | dd          5  t          j        | d| j        j                  5   | j
        |g|R ||d|cd d d            cd d d            S # 1 swxY w Y   d d d            d S # 1 swxY w Y   d S )	Nr  z2' is not a valid function name for transform(name)r  rg  r  r   Tr   )r   r{   _transform_generalrJ   transform_kernel_allowlistr   cythonized_kernelsr  r   r   _reduction_kernel_transformr   temp_setattrr   observed_grouper)rl   r   r  rg  rs   rt   r   s          rm   
_transformzGroupBy._transform  sS    $$$ 	*4*4XXXXQWXXX888NdNNNCS//!T,,,8S0S0S!#)x *7'&74&&7777 } 7t7 (.m OU  
  z488  z4=3QRR  8t7 (.m OU 	                                        s6   ;!D!D	0D!	D	D!D	D!!D%(D%c               0   t          j        | dd          5  |dv r.t          t          d         |          } | j        |dg|R i |}n"|
||d<   ||d<    t          | |          |i |}d d d            n# 1 swxY w Y   |                     |          S )Nr   Tr  r  rg  )r   r  r   r   _idxmax_idxminr   _wrap_transform_fast_result)rl   r   r  rg  rs   rt   r   s          rm   r  z#GroupBy._reduction_kernel_transform:  s    dJ55 
	> 
	> +++G$67>>,,T4I$III&II%'-F8$.;F?+,t,,d=f==
	> 
	> 
	> 
	> 
	> 
	> 
	> 
	> 
	> 
	> 
	> 
	> 
	> 
	> 
	> //777s   AA88A<?A<c                   | j         }| j        j        }|                    | j        j        d          }| j        j        dk    r=t          j        |j	        |          }|
                    ||j        |j                  }nQ|j                            |          }|                    d||fid          }|                    |j        d          }|S )z7
        Fast transform path for aggregations.
        r   r  r   r  rz   T)
allow_dups)r   r   r  r'  r  r   r(  r;   take_ndr$  r|  r  rz   r&  _reindex_with_indexersr8  )rl   r   r   r  r  outputnew_axs          rm   r  z#GroupBy._wrap_transform_fast_resultP  s    
 ' m :CC8=A$V^S99C%%c%JJFF \&&s++F22A}3ERV2WWF__SYQ_77Fro   c                @   t          |          dk    rt          j        g d          }n&t          j        t          j        |                    }|r| j                            |d          }nt          j        t          | j        j                  t                    }|
                    d           d||                    t                    <   t          j        |g | j        j        dd          d          j        }| j                            |          }|S )Nr   int64r  r  FTr   )r   r   arrayr   concatenaterx   r&  emptyr  r   fillr  r   rD  r  r]   where)rl   r   r   filteredr/  s        rm   _apply_filterzGroupBy._apply_filterl  s    w<<1hr111GGgbnW5566G 	6)..wQ.??HH8C 2 899FFFDIIe(,D$$%74!C4#5#;ABB#?!C!CDDFD)//55Hro   	ascending
np.ndarrayc                   | j         j        }| j         j        }t          ||          }||         t	          |          }}|dk    r t          j        dt
          j                  S t
          j        d|dd         |dd         k    f         }t          j	        t
          j        t          j
        |          d         |f                   }|                                 }|r|t          j        ||         |          z  }n8t          j        |t
          j        |dd         df                  |          |z
  }| j         j        rDt          j        |dk    t
          j        |                    t
          j        d                    }n!|                    t
          j        d          }t          j        |t
          j                  }	t          j        |t
          j                  |	|<   ||	         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   Fr5  )r   r  r   rU   r   r   r  r  r_diffnonzerocumsumrI  r  r  r   r  float64intparange)
rl   r  r  r   sortercountrunrepr  revs
             rm   _cumcount_arrayzGroupBy._cumcount_array}  s    m-''W55[#c((UA::8ARX....eD#crc(c!""g--.gbeBJsOOA.5677tmmoo 	B29SXs+++CC)Cc!""gtm 45s;;cAC=' 	3(3"9bfcjj%j.P.PQQCC**RXE*22ChuBG,,,iRW555F3xro   c                    t          | j        t                    r| j        j        S t          | j        t                    sJ | j        j        S rj   )r   r   rH   _constructor_slicedrT   r|  r   s    rm   _obj_1d_constructorzGroupBy._obj_1d_constructor  sF     dh	** 	08//$(F+++++x$$ro   r  c                :    |                      dfd          S )aa  
        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.

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

        Examples
        --------
        For SeriesGroupBy:

        >>> lst = ["a", "a", "b"]
        >>> ser = pd.Series([1, 2, 0], index=lst)
        >>> ser
        a    1
        a    2
        b    0
        dtype: int64
        >>> ser.groupby(level=0).any()
        a     True
        b    False
        dtype: bool

        For DataFrameGroupBy:

        >>> data = [[1, 0, 3], [1, 0, 6], [7, 1, 9]]
        >>> df = pd.DataFrame(
        ...     data, columns=["a", "b", "c"], index=["ostrich", "penguin", "parrot"]
        ... )
        >>> df
                 a  b  c
        ostrich  1  0  3
        penguin  1  0  6
        parrot   7  1  9
        >>> df.groupby(by=["a"]).any()
               b      c
        a
        1  False   True
        7   True   True
        r  c                N    t          | d                                        S NFr5  )r  )rT   r  r	  r  s    rm   r   zGroupBy.any.<locals>.<lambda>  %    &///3363BB ro   r  r  r  rl   r  s    `rm   r  zGroupBy.any  s5    l ''BBBB ( 
 
 	
ro   c                :    |                      dfd          S )af  
        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.

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

        Examples
        --------

        For SeriesGroupBy:

        >>> lst = ["a", "a", "b"]
        >>> ser = pd.Series([1, 2, 0], index=lst)
        >>> ser
        a    1
        a    2
        b    0
        dtype: int64
        >>> ser.groupby(level=0).all()
        a     True
        b    False
        dtype: bool

        For DataFrameGroupBy:

        >>> data = [[1, 0, 3], [1, 5, 6], [7, 8, 9]]
        >>> df = pd.DataFrame(
        ...     data, columns=["a", "b", "c"], index=["ostrich", "penguin", "parrot"]
        ... )
        >>> df
                 a  b  c
        ostrich  1  0  3
        penguin  1  5  6
        parrot   7  8  9
        >>> df.groupby(by=["a"]).all()
               b      c
        a
        1  False   True
        7   True   True
        r  c                N    t          | d                                        S r  )rT   r  r  s    rm   r   zGroupBy.all.<locals>.<lambda>$  r  ro   r  r  r  s    `rm   r  zGroupBy.all  s5    n ''BBBB ( 
 
 	
ro   c                  	 |                                  }| j        j        | j        j        	dk    |j        dk    d	fd}|                    |          }|                     |          }|                     |          }|S )a;  
        Compute count of group, excluding missing values.

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

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

        Examples
        --------
        For SeriesGroupBy:

        >>> lst = ["a", "a", "b"]
        >>> ser = pd.Series([1, 2, np.nan], index=lst)
        >>> ser
        a    1.0
        a    2.0
        b    NaN
        dtype: float64
        >>> ser.groupby(level=0).count()
        a    2
        b    0
        dtype: int64

        For DataFrameGroupBy:

        >>> data = [[1, np.nan, 3], [1, np.nan, 6], [7, 8, 9]]
        >>> df = pd.DataFrame(
        ...     data, columns=["a", "b", "c"], index=["cow", "horse", "bull"]
        ... )
        >>> df
                a	  b	c
        cow     1	NaN	3
        horse	1	NaN	6
        bull	7	8.0	9
        >>> df.groupby("a").count()
            b   c
        a
        1   0   2
        7   1   1

        For Resampler:

        >>> ser = pd.Series(
        ...     [1, 2, 3, 4],
        ...     index=pd.DatetimeIndex(
        ...         ["2023-01-01", "2023-01-15", "2023-02-01", "2023-02-15"]
        ...     ),
        ... )
        >>> ser
        2023-01-01    1
        2023-01-15    2
        2023-02-01    3
        2023-02-15    4
        dtype: int64
        >>> ser.resample("MS").count()
        2023-01-01    2
        2023-02-01    2
        Freq: MS, dtype: int64
        r  r   bvaluesr   rg   c                   | j         dk    r(t          |                               dd           z  }nt          |            z  }t          j        |          }t          | t                    r@t          |d         t          j	        |j
        d         t          j                            S t          | t                    rSt          | j        t                    s9t          d          }t!          |                               |d         |          S r(|j         dk    sJ |j
        d         dk    sJ |d         S |S )	Nr   r  )r.  max_binr   r  )r/  zint64[pyarrow]rj  )r(  r8   reshaper   count_level_2dr   r?   rB   r   zerosr  bool_r>   r  rD   r7   r   r  )r  maskedcountedr  r  	is_seriesr/  r   s       rm   hfunczGroupBy.count.<locals>.hfuncr  sO   |q  g!6!6q"!=!= ==g.(WMMMG'?33 M#AJRXgmA.>bh%O%O%O    G%899 M*{C C M %%566G}}33GAJe3LLL "|q((((}Q'1,,,,qz!Nro   )r  r   rg   r   )r  r   r  r   r(  r  r  rQ  )
rl   rT  r  r  new_objr   r  r
  r/  r   s
         @@@@rm   r  zGroupBy.count(  s    F **,,m-'byIN		 	 	 	 	 	 	 	 	0 %%e,,**733--g66ro   r  !Literal['cython', 'numba'] | Nonec                    t          |          r*ddlm} |                     |t          j        |d          S |                     dfd          }|                    | j        d          S )	a_	  
        Compute mean of groups, excluding missing values.

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

            .. versionchanged:: 2.0.0

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

        skipna : bool, default True
            Exclude NA/null values. If an entire group is NA, the result will be NA.

        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``

        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}}``

        Returns
        -------
        pandas.Series or pandas.DataFrame
            Mean of values within each group. Same object type as the caller.

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

        Examples
        --------
        >>> df = pd.DataFrame(
        ...     {"A": [1, 1, 2, 1, 2], "B": [np.nan, 2, 3, 4, 5], "C": [1, 2, 1, 1, 2]},
        ...     columns=["A", "B", "C"],
        ... )

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

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

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

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

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

        >>> df.groupby("A")["B"].mean()
        A
        1    3.0
        2    4.0
        Name: B, dtype: float64
        r   )grouped_meanmin_periodsr  meanc                P    t          | d                                        S NFr5  r  r  )rT   r  r	  r  r  s    rm   r   zGroupBy.mean.<locals>.<lambda>  s.    fQU33388!-f 9   ro   r  r  r  re   r  )	rW   pandas.core._numba.kernelsr  rt  r=   float_dtype_mappingr  r)  r   )rl   r  r  r  rg  r  r   s    ``    rm   r  zGroupBy.mean  s    d 6"" 	C??????**, +    --     * .  F &&tx	&BBBro   c                x    |                      dfd          }|                    | j        d          S )a.	  
        Compute median of groups, excluding missing values.

        For multiple groupings, the result index will be a MultiIndex

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

            .. versionchanged:: 2.0.0

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

        skipna : bool, default True
            Exclude NA/null values. If an entire group is NA, the result will be NA.

            .. versionadded:: 3.0.0

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

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

        Examples
        --------
        For SeriesGroupBy:

        >>> lst = ["a", "a", "a", "b", "b", "b"]
        >>> ser = pd.Series([7, 2, 8, 4, 3, 3], index=lst)
        >>> ser
        a     7
        a     2
        a     8
        b     4
        b     3
        b     3
        dtype: int64
        >>> ser.groupby(level=0).median()
        a    7.0
        b    3.0
        dtype: float64

        For DataFrameGroupBy:

        >>> data = {"a": [1, 3, 5, 7, 7, 8, 3], "b": [1, 4, 8, 4, 4, 2, 1]}
        >>> df = pd.DataFrame(
        ...     data, index=["dog", "dog", "dog", "mouse", "mouse", "mouse", "mouse"]
        ... )
        >>> df
                 a  b
          dog    1  1
          dog    3  4
          dog    5  8
        mouse    7  4
        mouse    7  4
        mouse    8  2
        mouse    3  1
        >>> df.groupby(level=0).median()
                 a    b
        dog    3.0  4.0
        mouse  7.0  3.0

        For Resampler:

        >>> ser = pd.Series(
        ...     [1, 2, 3, 3, 4, 5],
        ...     index=pd.DatetimeIndex(
        ...         [
        ...             "2023-01-01",
        ...             "2023-01-10",
        ...             "2023-01-15",
        ...             "2023-02-01",
        ...             "2023-02-10",
        ...             "2023-02-15",
        ...         ]
        ...     ),
        ... )
        >>> ser.resample("MS").median()
        2023-01-01    2.0
        2023-02-01    4.0
        Freq: MS, dtype: float64
        medianc                P    t          | d                                        S r  )rT   r  r  s    rm   r   z GroupBy.median.<locals>.<lambda>S	  s.    &///66)& 7   ro   r  re   r  r  )rl   r  r  r   s    `` rm   r  zGroupBy.median  sb    t ))     & * 
 
 ""48I">>>ro   r   ddofc           
         t          |          r=ddlm} t          j        |                     |t          j        |d                    S |                     dfd|          S )a
  
        Compute standard deviation of groups, excluding missing values.

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

        Parameters
        ----------
        ddof : int, default 1
            Delta Degrees of Freedom. The divisor used in calculations is ``N - ddof``,
            where ``N`` represents the number of elements.

        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``

        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}}``

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

            .. versionchanged:: 2.0.0

                numeric_only now defaults to ``False``.

        skipna : bool, default True
            Exclude NA/null values. If an entire group is NA, the result will be NA.

            .. versionadded:: 3.0.0

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

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

        Examples
        --------
        For SeriesGroupBy:

        >>> lst = ["a", "a", "a", "b", "b", "b"]
        >>> ser = pd.Series([7, 2, 8, 4, 3, 3], index=lst)
        >>> ser
        a     7
        a     2
        a     8
        b     4
        b     3
        b     3
        dtype: int64
        >>> ser.groupby(level=0).std()
        a    3.21455
        b    0.57735
        dtype: float64

        For DataFrameGroupBy:

        >>> data = {"a": [1, 3, 5, 7, 7, 8, 3], "b": [1, 4, 8, 4, 4, 2, 1]}
        >>> df = pd.DataFrame(
        ...     data, index=["dog", "dog", "dog", "mouse", "mouse", "mouse", "mouse"]
        ... )
        >>> df
                 a  b
          dog    1  1
          dog    3  4
          dog    5  8
        mouse    7  4
        mouse    7  4
        mouse    8  2
        mouse    3  1
        >>> df.groupby(level=0).std()
                      a         b
        dog    2.000000  3.511885
        mouse  2.217356  1.500000
        r   grouped_varr  r  r  r  c                P    t          | d                                        S NFr5  )r  r  )rT   r  r	  r  r  s    rm   r   zGroupBy.std.<locals>.<lambda>	  '    fQU33377T&7QQ ro   r  r  r  r  )	rW   r  r   r   sqrtrt  r=   r  r  rl   r  r  rg  r  r  r   s    `   ` rm   r  zGroupBy.std[	  s    | 6"" 	>>>>>>7''0! !! (  	 	 	 ++QQQQQ) ,   ro   c                    t          |          r+ddlm} |                     |t          j        |d          S |                     dfd|          S )aD
  
        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``

        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}}``

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

            .. versionchanged:: 2.0.0

                numeric_only now defaults to ``False``.

        skipna : bool, default True
            Exclude NA/null values. If an entire group is NA, the result will be NA.

            .. versionadded:: 3.0.0

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

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

        Examples
        --------
        For SeriesGroupBy:

        >>> lst = ["a", "a", "a", "b", "b", "b"]
        >>> ser = pd.Series([7, 2, 8, 4, 3, 3], index=lst)
        >>> ser
        a     7
        a     2
        a     8
        b     4
        b     3
        b     3
        dtype: int64
        >>> ser.groupby(level=0).var()
        a    10.333333
        b     0.333333
        dtype: float64

        For DataFrameGroupBy:

        >>> data = {"a": [1, 3, 5, 7, 7, 8, 3], "b": [1, 4, 8, 4, 4, 2, 1]}
        >>> df = pd.DataFrame(
        ...     data, index=["dog", "dog", "dog", "mouse", "mouse", "mouse", "mouse"]
        ... )
        >>> df
                 a  b
          dog    1  1
          dog    3  4
          dog    5  8
        mouse    7  4
        mouse    7  4
        mouse    8  2
        mouse    3  1
        >>> df.groupby(level=0).var()
                      a          b
        dog    4.000000  12.333333
        mouse  4.916667   2.250000
        r   r  r!  varc                P    t          | d                                        S r#  )rT   r*  r$  s    rm   r   zGroupBy.var.<locals>.<lambda>:
  r%  ro   r&  )rW   r  r   rt  r=   r  r  r(  s    `   ` rm   r*  zGroupBy.var	  s    z 6"" 	>>>>>>**, +    ++QQQQQ) ,   ro   subsetSequence[Hashable] | None	normalizec                   |rdnd}| j         }| j        d | j        j        D             t	          t
                    rj        }|v rg ng}	nt          j                  }
|Qt          |          t                    z  }|rt          d| d          |
z
  }|rt          d| d          n|
fdt          j                  D             }	t          | j        j                  }|	D ]1}t          ||d	d	|
          \  }}}|t          |j                  z  }2|                    |d	| j        | j                  }t!          t
          |                                          }||_        |r|                    |d          }| j        r{|j        j        }t-          t/          |                    |j        _        t-          t/          | j        j                            }|                    |d	          }||j        _        |rt          t-          t/          | j        j                  |j        j                            }|                    |j                            |          | j        | j        d	                              d          }||z  }|                    d          }| j        r|}n|j        }t=          j        |j                  }||v rt          d| d          ||_        |                     t-          t/          |                              |_        |!                                }| j        j        d         j         j        j"        }tG          ||          $                    t/          |          |          }||_        |}|%                    | j         d          S )z
        Shared implementation of value_counts for SeriesGroupBy and DataFrameGroupBy.

        SeriesGroupBy additionally supports a bins argument. See the docstring of
        DataFrameGroupBy.value_counts for a description of arguments.
        
proportionr  c                *    h | ]}|j         	|j        S r   )in_axisrz   )r   groupings     rm   	<setcomp>z(GroupBy._value_counts.<locals>.<setcomp>T
  s2     
 
 
&XEU
M
 
 
ro   NzKeys z0 in subset cannot be in the groupby column keys.z) in subset do not exist in the DataFrame.c              3  P   K   | ] \  }}|v	|v j         d d |f         V  !d S rj   )r   )r   idx_namein_axis_namesr   	subsetteds      rm   r   z(GroupBy._value_counts.<locals>.<genexpr>l
  sY         C--%92D2D C 2D2D2D2D	 ro   F)r   r   r   r   )r   r   r   stable)r  kind)r   sort_remaining)r   r   r   sumg        zColumn label 'z' is duplicate of result columnr   r  value_countsr  )&r   r   r   rB  r   rT   rz   setrH  r   rE  r   rM   re   r   r   r   sizesort_valuesr   r  r  ranger   r:  nlevels	droplevel	transformfillnar   r   fill_missing_names	set_namesreset_indexr  rP   rC  r)  ) rl   r,  r.  r   r  r   rz   rq  r7  r   unique_colsclashingdoesnt_existrB  r   r   r2  gbresult_seriesr  index_levelr  indexed_group_sizer   r  rH  result_frame
orig_dtypecolsr8  r   r9  s                                 @@@rm   _value_countszGroupBy._value_counts@
  sE     )5||gX'
 
*.-*A
 
 
 c6"" 	HE+0M+A+ARRuDDck**K!KK	$s='9'99 $3 3 3 3    );6 $WWWW  
 (	      #,CK"8"8  D 011	 	1 	1C'  MGQ g/000II ZZ];	  
 
 VRWWYY//! 	)55#( 6  M 9 		.!'-E(-c%jj(9(9M%DM$; < <==K)44!% 5  M ).M% 	6 c$-122M4G4OPP F "/!6!6#--f55Y{ "7 " " i  //M *0055M = 	""FF "'E,U[99Gw !W$!W!W!WXXX!%M"'//%G2E2E"F"FM(4466L037?EJ
333::3w<<NND#'L !F""48N"CCCro   c                    |r\| j         j        dk    rLt          | j         j                  s3t	          t          |           j         d| d| j         j                   |                     dfd|          S )ar	  
        Compute standard error of the mean of groups, excluding missing values.

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

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

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

            .. versionchanged:: 2.0.0

                numeric_only now defaults to ``False``.

        skipna : bool, default True
            Exclude NA/null values. If an entire group is NA, the result will be NA.

            .. versionadded:: 3.0.0

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

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

        Examples
        --------
        For SeriesGroupBy:

        >>> lst = ["a", "a", "b", "b"]
        >>> ser = pd.Series([5, 10, 8, 14], index=lst)
        >>> ser
        a     5
        a    10
        b     8
        b    14
        dtype: int64
        >>> ser.groupby(level=0).sem()
        a    2.5
        b    3.0
        dtype: float64

        For DataFrameGroupBy:

        >>> data = [[1, 12, 11], [1, 15, 2], [2, 5, 8], [2, 6, 12]]
        >>> df = pd.DataFrame(
        ...     data,
        ...     columns=["a", "b", "c"],
        ...     index=["tuna", "salmon", "catfish", "goldfish"],
        ... )
        >>> df
                   a   b   c
            tuna   1  12  11
          salmon   1  15   2
         catfish   2   5   8
        goldfish   2   6  12
        >>> df.groupby("a").sem()
              b  c
        a
        1    1.5  4.5
        2    0.5  2.0

        For Resampler:

        >>> ser = pd.Series(
        ...     [1, 3, 2, 4, 3, 8],
        ...     index=pd.DatetimeIndex(
        ...         [
        ...             "2023-01-01",
        ...             "2023-01-10",
        ...             "2023-01-15",
        ...             "2023-02-01",
        ...             "2023-02-10",
        ...             "2023-02-15",
        ...         ]
        ...     ),
        ... )
        >>> ser.resample("MS").sem()
        2023-01-01    0.577350
        2023-02-01    1.527525
        Freq: MS, dtype: float64
        r   z.sem called with numeric_only=z and dtype r  c                P    t          | d                                        S r#  )rT   r  r$  s    rm   r   zGroupBy.sem.<locals>.<lambda>!  s'    &///33f3MM ro   r&  )r   r(  r2   r  r  r   rv   r  )rl   r  r  r  s    ` `rm   r  zGroupBy.sem
  s    z  	DHMQ..7G7W7W.::& J J ,J J9=J J   ''MMMMM% ( 
 
 	
ro   c                   | j                                         }d}t          | j        t                    rt          | j        j        t                    rJt          | j        j        t                    r(| j        j        j        j	        t          j        u rd}n'd}n$d}n!t          | j        j        t                    rd}t          | j        t                    r"|                     || j        j                  }n|                     |          }||                    dddd|          }| j        s'|                    d                                          }|S )a  
        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.

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

        Examples
        --------

        For SeriesGroupBy:

        >>> lst = ["a", "a", "b"]
        >>> ser = pd.Series([1, 2, 3], index=lst)
        >>> ser
        a     1
        a     2
        b     3
        dtype: int64
        >>> ser.groupby(level=0).size()
        a    2
        b    1
        dtype: int64

        >>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]]
        >>> df = pd.DataFrame(
        ...     data, columns=["a", "b", "c"], index=["owl", "toucan", "eagle"]
        ... )
        >>> df
                a  b  c
        owl     1  2  3
        toucan  1  5  6
        eagle   7  8  9
        >>> df.groupby("a").size()
        a
        1    2
        7    1
        dtype: int64

        For Resampler:

        >>> ser = pd.Series(
        ...     [1, 2, 3],
        ...     index=pd.DatetimeIndex(["2023-01-01", "2023-01-15", "2023-02-01"]),
        ... )
        >>> ser
        2023-01-01    1
        2023-01-15    2
        2023-02-01    3
        dtype: int64
        >>> ser.resample("MS").size()
        2023-01-01    2
        2023-02-01    1
        Freq: MS, dtype: int64
        Nnumpy_nullablepyarrow)rz   F)infer_objectsconvert_stringconvert_booleanconvert_floatingdtype_backendr@  )r   r@  r   r   rT   r  r>   rE   r  na_valuer   r   r?   r  rz   convert_dtypesr   renamerI  )rl   r   r^  s      rm   r@  zGroupBy.size'  sJ   @ ##%%EIdh'' 
	1$(.*=>> 	1dhn.>?? .x~+4>>(,(8$-MMDHNO<< 1 0 dh'' 	6--f48=-IIFF--f55F$**#$ %!&+ +  F } 	9]]6**6688Fro   r   c                   t          |          r*ddlm} |                     |t          j        |||          S t          j        | dd          5  |                     ||dt          j
        |          }ddd           n# 1 swxY w Y   |S )	a  
        Compute sum of group values.

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

            .. versionchanged:: 2.0.0

                numeric_only no longer accepts ``None``.

        min_count : int, default 0
            The required number of valid values to perform the operation. If fewer
            than ``min_count`` non-NA values are present the result will be NA.

        skipna : bool, default True
            Exclude NA/null values. If the entire group is NA and ``skipna`` is
            ``True``, the result will be NA.

            .. versionchanged:: 3.0.0

        engine : str, default None None
            * ``'cython'`` : Runs rolling apply through C-extensions from cython.
            * ``'numba'`` : Runs rolling apply through JIT compiled code from numba.
                Only available when ``raw`` is set to ``True``.
            * ``None`` : Defaults to ``'cython'`` or globally setting
                ``compute.use_numba``

        engine_kwargs : dict, default None 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 both the ``func`` and the ``apply`` groupby aggregation.

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

        See Also
        --------
        SeriesGroupBy.min : Return the min of the group values.
        DataFrameGroupBy.min : Return the min of the group values.
        SeriesGroupBy.max : Return the max of the group values.
        DataFrameGroupBy.max : Return the max of the group values.
        SeriesGroupBy.sum : Return the sum of the group values.
        DataFrameGroupBy.sum : Return the sum of the group values.

        Examples
        --------
        For SeriesGroupBy:

        >>> lst = ["a", "a", "b", "b"]
        >>> ser = pd.Series([1, 2, 3, 4], index=lst)
        >>> ser
        a    1
        a    2
        b    3
        b    4
        dtype: int64
        >>> ser.groupby(level=0).sum()
        a    3
        b    7
        dtype: int64

        For DataFrameGroupBy:

        >>> data = [[1, 8, 2], [1, 2, 5], [2, 5, 8], [2, 6, 9]]
        >>> df = pd.DataFrame(
        ...     data,
        ...     columns=["a", "b", "c"],
        ...     index=["tiger", "leopard", "cheetah", "lion"],
        ... )
        >>> df
                  a  b  c
          tiger   1  8  2
        leopard   1  2  5
        cheetah   2  5  8
           lion   2  6  9
        >>> df.groupby("a").sum()
             b   c
        a
        1   10   7
        2   11  17
        r   )grouped_sumr  r   Tr=  r  r  r  r  r  N)rW   r  rc  rt  r=   default_dtype_mappingr   r  r  r   r=  )rl   r  r  r  r  rg  rc  r   s           rm   r=  zGroupBy.sum  s    B 6"" 	>>>>>>**.% +    !$
D99  **!-'6! +                 Ms   %BBBc                J    |                      |||dt          j                  S )a  
        Compute prod of group values.

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

            .. versionchanged:: 2.0.0

                numeric_only no longer accepts ``None``.

        min_count : int, default 0
            The required number of valid values to perform the operation. If fewer
            than ``min_count`` non-NA values are present the result will be NA.

        skipna : bool, default True
            Exclude NA/null values. If an entire group is NA, the result will be NA.

            .. versionadded:: 3.0.0

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

        See Also
        --------
        Series.prod : Return the product of the values over the requested axis.
        DataFrame.prod : Return the product of the values over the requested axis.

        Examples
        --------
        For SeriesGroupBy:

        >>> lst = ["a", "a", "b", "b"]
        >>> ser = pd.Series([1, 2, 3, 4], index=lst)
        >>> ser
        a    1
        a    2
        b    3
        b    4
        dtype: int64
        >>> ser.groupby(level=0).prod()
        a    2
        b   12
        dtype: int64

        For DataFrameGroupBy:

        >>> data = [[1, 8, 2], [1, 2, 5], [2, 5, 8], [2, 6, 9]]
        >>> df = pd.DataFrame(
        ...     data,
        ...     columns=["a", "b", "c"],
        ...     index=["tiger", "leopard", "cheetah", "lion"],
        ... )
        >>> df
                  a  b  c
          tiger   1  8  2
        leopard   1  2  5
        cheetah   2  5  8
           lion   2  6  9
        >>> df.groupby("a").prod()
             b    c
        a
        1   16   10
        2   30   72
        prodr  r  r  r  r  )r  r   rg  )rl   r  r  r  s       rm   rg  zGroupBy.prod  s3    P   %7 ! 
 
 	
ro   c                    t          |          r+ddlm} |                     |t          j        ||d|          S |                     |||dt          j                  S )a  
        Compute min of group values.

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

            .. versionchanged:: 2.0.0

                numeric_only no longer accepts ``None``.

        min_count : int, default -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.

        skipna : bool, default True
            Exclude NA/null values. If the entire group is NA and ``skipna`` is
            ``True``, the result will be NA.

            .. versionchanged:: 3.0.0

        engine : str, default None None
            * ``'cython'`` : Runs rolling apply through C-extensions from cython.
            * ``'numba'`` : Runs rolling apply through JIT compiled code from numba.
                Only available when ``raw`` is set to ``True``.
            * ``None`` : Defaults to ``'cython'`` or globally setting
                ``compute.use_numba``

        engine_kwargs : dict, default None 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 both the ``func`` and the ``apply`` groupby aggregation.

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

        See Also
        --------
        SeriesGroupBy.min : Return the min of the group values.
        DataFrameGroupBy.min : Return the min of the group values.
        SeriesGroupBy.max : Return the max of the group values.
        DataFrameGroupBy.max : Return the max of the group values.
        SeriesGroupBy.sum : Return the sum of the group values.
        DataFrameGroupBy.sum : Return the sum of the group values.

        Examples
        --------
        For SeriesGroupBy:

        >>> lst = ["a", "a", "b", "b"]
        >>> ser = pd.Series([1, 2, 3, 4], index=lst)
        >>> ser
        a    1
        a    2
        b    3
        b    4
        dtype: int64
        >>> ser.groupby(level=0).min()
        a    1
        b    3
        dtype: int64

        For DataFrameGroupBy:

        >>> data = [[1, 8, 2], [1, 2, 5], [2, 5, 8], [2, 6, 9]]
        >>> df = pd.DataFrame(
        ...     data,
        ...     columns=["a", "b", "c"],
        ...     index=["tiger", "leopard", "cheetah", "lion"],
        ... )
        >>> df
                  a  b  c
          tiger   1  8  2
        leopard   1  2  5
        cheetah   2  5  8
           lion   2  6  9
        >>> df.groupby("a").min()
            b  c
        a
        1   2  2
        2   5  8
        r   grouped_min_maxFr  is_maxr  minrh  )	rW   r  rk  rt  r=   identity_dtype_mappingr  r   rn  rl   r  r  r  r  rg  rk  s          rm   rn  zGroupBy.minS  s    B 6"" 	BBBBBB**/% +    $$)#v %   ro   c                    t          |          r+ddlm} |                     |t          j        ||d|          S |                     |||dt          j                  S )a  
        Compute max of group values.

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

            .. versionchanged:: 2.0.0

                numeric_only no longer accepts ``None``.

        min_count : int, default -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.

        skipna : bool, default True
            Exclude NA/null values. If the entire group is NA and ``skipna`` is
            ``True``, the result will be NA.

            .. versionchanged:: 3.0.0

        engine : str, default None None
            * ``'cython'`` : Runs rolling apply through C-extensions from cython.
            * ``'numba'`` : Runs rolling apply through JIT compiled code from numba.
                Only available when ``raw`` is set to ``True``.
            * ``None`` : Defaults to ``'cython'`` or globally setting
                ``compute.use_numba``

        engine_kwargs : dict, default None 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 both the ``func`` and the ``apply`` groupby aggregation.

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

        See Also
        --------
        SeriesGroupBy.min : Return the min of the group values.
        DataFrameGroupBy.min : Return the min of the group values.
        SeriesGroupBy.max : Return the max of the group values.
        DataFrameGroupBy.max : Return the max of the group values.
        SeriesGroupBy.sum : Return the sum of the group values.
        DataFrameGroupBy.sum : Return the sum of the group values.

        Examples
        --------
        For SeriesGroupBy:

        >>> lst = ["a", "a", "b", "b"]
        >>> ser = pd.Series([1, 2, 3, 4], index=lst)
        >>> ser
        a    1
        a    2
        b    3
        b    4
        dtype: int64
        >>> ser.groupby(level=0).max()
        a    2
        b    4
        dtype: int64

        For DataFrameGroupBy:

        >>> data = [[1, 8, 2], [1, 2, 5], [2, 5, 8], [2, 6, 9]]
        >>> df = pd.DataFrame(
        ...     data,
        ...     columns=["a", "b", "c"],
        ...     index=["tiger", "leopard", "cheetah", "lion"],
        ... )
        >>> df
                  a  b  c
          tiger   1  8  2
        leopard   1  2  5
        cheetah   2  5  8
           lion   2  6  9
        >>> df.groupby("a").max()
            b  c
        a
        1   8  5
        2   6  9
        r   rj  Trl  maxrh  )	rW   r  rk  rt  r=   ro  r  r   rr  rp  s          rm   rr  zGroupBy.max  s    B 6"" 	BBBBBB**/% +    $$)#v %   ro   c                >    dd}|                      ||d||          S )a  
        Compute the first entry of each column within each group.

        Defaults to skipping NA elements.

        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`` valid values are present the result will be NA.
        skipna : bool, default True
            Exclude NA/null values. If an entire group is NA, the result will be NA.

            .. versionadded:: 2.2.1

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

        See Also
        --------
        DataFrame.groupby : Apply a function groupby to each row or column of a
            DataFrame.
        core.groupby.DataFrameGroupBy.last : Compute the last non-null entry
            of each column.
        core.groupby.DataFrameGroupBy.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   r   c                    dd}t          | t                    r|                     |          S t          | t                    r ||           S t	          t          |                     )Nr	  rT   c                    | j         t          | j                            }t          |          s| j         j        j        S |d         S )z-Helper function for first item that isn't NA.r   r  r:   r   r  r_  r	  arrs     rm   firstz2GroupBy.first.<locals>.first_compat.<locals>.first|  s:    geAGnn-3xx 27=111vro   r	  rT   r   rH   rm  rT   r  r   )r   ry  s     rm   first_compatz#GroupBy.first.<locals>.first_compat{  sp        #y)) +yy'''C(( +uSzz!S		***ro   ry  rd  r   r   r  )rl   r  r  r  r|  s        rm   ry  zGroupBy.first=  sE    |	+ 	+ 	+ 	+   % ! 
 
 	
ro   c                >    dd}|                      ||d||          S )a4  
        Compute the last entry of each column within each group.

        Defaults to skipping NA elements.

        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`` valid values are present the result will be NA.
        skipna : bool, default True
            Exclude NA/null values. If an entire group is NA, the result will be NA.

            .. versionadded:: 2.2.1

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

        See Also
        --------
        DataFrame.groupby : Apply a function groupby to each row or column of a
            DataFrame.
        core.groupby.DataFrameGroupBy.first : Compute the first non-null entry
            of each column.
        core.groupby.DataFrameGroupBy.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   r   c                    dd}t          | t                    r|                     |          S t          | t                    r ||           S t	          t          |                     )Nr	  rT   c                    | j         t          | j                            }t          |          s| j         j        j        S |d         S )z,Helper function for last item that isn't NA.r  rv  rw  s     rm   lastz/GroupBy.last.<locals>.last_compat.<locals>.last  s:    geAGnn-3xx 27=112wro   rz  r{  )r   r  s     rm   last_compatz!GroupBy.last.<locals>.last_compat  sn        #y)) +yy&C(( +tCyy S		***ro   r  rd  r}  r~  )rl   r  r  r  r  s        rm   r  zGroupBy.last  sE    Z	+ 	+ 	+ 	+   % ! 
 
 	
ro   c                L   | j         j        dk    r}| j        }t          |j                  }|st          d          | j                            d|j        ddd          }g d}| j         	                    || j        j
        |	          }|S |                     d
           }|S )aX
  
        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.

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

        Examples
        --------

        For SeriesGroupBy:

        >>> lst = [
        ...     "SPX",
        ...     "CAC",
        ...     "SPX",
        ...     "CAC",
        ...     "SPX",
        ...     "CAC",
        ...     "SPX",
        ...     "CAC",
        ... ]
        >>> ser = pd.Series([3.4, 9.0, 7.2, 5.2, 8.8, 9.4, 0.1, 0.5], index=lst)
        >>> ser
        SPX     3.4
        CAC     9.0
        SPX     7.2
        CAC     5.2
        SPX     8.8
        CAC     9.4
        SPX     0.1
        CAC     0.5
        dtype: float64
        >>> ser.groupby(level=0).ohlc()
             open  high  low  close
        CAC   9.0   9.4  0.5    0.5
        SPX   3.4   8.8  0.1    0.1

        For DataFrameGroupBy:

        >>> data = {
        ...     2022: [1.2, 2.3, 8.9, 4.5, 4.4, 3, 2, 1],
        ...     2023: [3.4, 9.0, 7.2, 5.2, 8.8, 9.4, 8.2, 1.0],
        ... }
        >>> df = pd.DataFrame(
        ...     data, index=["SPX", "CAC", "SPX", "CAC", "SPX", "CAC", "SPX", "CAC"]
        ... )
        >>> df
             2022  2023
        SPX   1.2   3.4
        CAC   2.3   9.0
        SPX   8.9   7.2
        CAC   4.5   5.2
        SPX   4.4   8.8
        CAC   3.0   9.4
        SPX   2.0   8.2
        CAC   1.0   1.0
        >>> df.groupby(level=0).ohlc()
            2022                 2023
            open high  low close open high  low close
        CAC  2.3  4.5  1.0   1.0  9.0  9.4  1.0   1.0
        SPX  1.2  8.9  1.2   2.0  3.4  8.8  3.4   8.2

        For Resampler:

        >>> ser = pd.Series(
        ...     [1, 3, 2, 4, 3, 5],
        ...     index=pd.DatetimeIndex(
        ...         [
        ...             "2023-01-01",
        ...             "2023-01-10",
        ...             "2023-01-15",
        ...             "2023-02-01",
        ...             "2023-02-10",
        ...             "2023-02-15",
        ...         ]
        ...     ),
        ... )
        >>> ser.resample("MS").ohlc()
                    open  high  low  close
        2023-01-01     1     3    1      2
        2023-02-01     4     5    3      5
        r   zNo numeric types to aggregater  ohlcr   r  r  )openhighlowclose)r  rH  c                *    |                                  S rj   )r  )sgbs    rm   r   zGroupBy.ohlc.<locals>.<lambda>E  s    CHHJJ ro   )r   r(  rx   r2   r  r%   r   r  r$  _constructor_expanddimr  _apply_to_column_groupbys)rl   r   
is_numericr  	agg_namesr   s         rm   r  zGroupBy.ohlc  s    | 8=A$C)#)44J A ?@@@88S[&qB 9  J 988IX44$-"<i 5  F M//0F0FGGro   c                8   | j         }t          |          dk    r`|                              }|j        dk    r|}n|                                }|                                j        j        dd         S t          j	        | dd          5  | 
                    fd|d          }ddd           n# 1 swxY w Y   |                                }| j        s6|                     |          }t          t          |                    |_        |S )	a!  
        Generate descriptive statistics.

        Descriptive statistics include those that summarize the central
        tendency, dispersion and shape of a
        dataset's distribution, excluding ``NaN`` values.

        Analyzes both numeric and object series, as well
        as ``DataFrame`` column sets of mixed data types. The output
        will vary depending on what is provided. Refer to the notes
        below for more detail.

        Parameters
        ----------
        percentiles : list-like of numbers, optional
            The percentiles to include in the output. All should
            fall between 0 and 1. The default, ``None``, will automatically
            return the 25th, 50th, and 75th percentiles.
        include : 'all', list-like of dtypes or None (default), optional
            A white list of data types to include in the result. Ignored
            for ``Series``. Here are the options:

            - 'all' : All columns of the input will be included in the output.
            - A list-like of dtypes : Limits the results to the
              provided data types.
              To limit the result to numeric types submit
              ``numpy.number``. To limit it instead to object columns submit
              the ``numpy.object`` data type. Strings
              can also be used in the style of
              ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To
              select pandas categorical columns, use ``'category'``
            - None (default) : The result will include all numeric columns.
        exclude : list-like of dtypes or None (default), optional,
            A black list of data types to omit from the result. Ignored
            for ``Series``. Here are the options:

            - A list-like of dtypes : Excludes the provided data types
              from the result. To exclude numeric types submit
              ``numpy.number``. To exclude object columns submit the data
              type ``numpy.object``. Strings can also be used in the style of
              ``select_dtypes`` (e.g. ``df.describe(exclude=['O'])``). To
              exclude pandas categorical columns, use ``'category'``
            - None (default) : The result will exclude nothing.

        Returns
        -------
        Series or DataFrame
            Summary statistics of the Series or Dataframe provided.

        See Also
        --------
        DataFrame.count: Count number of non-NA/null observations.
        DataFrame.max: Maximum of the values in the object.
        DataFrame.min: Minimum of the values in the object.
        DataFrame.mean: Mean of the values.
        DataFrame.std: Standard deviation of the observations.
        DataFrame.select_dtypes: Subset of a DataFrame including/excluding
            columns based on their dtype.

        Notes
        -----
        For numeric data, the result's index will include ``count``,
        ``mean``, ``std``, ``min``, ``max`` as well as lower, ``50`` and
        upper percentiles. By default the lower percentile is ``25`` and the
        upper percentile is ``75``. The ``50`` percentile is the
        same as the median.

        For object data (e.g. strings), the result's index
        will include ``count``, ``unique``, ``top``, and ``freq``. The ``top``
        is the most common value. The ``freq`` is the most common value's
        frequency.

        If multiple object values have the highest count, then the
        ``count`` and ``top`` results will be arbitrarily chosen from
        among those with the highest count.

        For mixed data types provided via a ``DataFrame``, the default is to
        return only an analysis of numeric columns. If the DataFrame consists
        only of object and categorical data without any numeric columns, the
        default is to return an analysis of both the object and categorical
        columns. If ``include='all'`` is provided as an option, the result
        will include a union of attributes of each type.

        The `include` and `exclude` parameters can be used to limit
        which columns in a ``DataFrame`` are analyzed for the output.
        The parameters are ignored when analyzing a ``Series``.

        Examples
        --------
        Describing a numeric ``Series``.

        >>> s = pd.Series([1, 2, 3])
        >>> s.describe()
        count    3.0
        mean     2.0
        std      1.0
        min      1.0
        25%      1.5
        50%      2.0
        75%      2.5
        max      3.0
        dtype: float64

        Describing a categorical ``Series``.

        >>> s = pd.Series(["a", "a", "b", "c"])
        >>> s.describe()
        count     4
        unique    3
        top       a
        freq      2
        dtype: object

        Describing a timestamp ``Series``.

        >>> s = pd.Series(
        ...     [
        ...         np.datetime64("2000-01-01"),
        ...         np.datetime64("2010-01-01"),
        ...         np.datetime64("2010-01-01"),
        ...     ]
        ... )
        >>> s.describe()
        count                      3
        mean     2006-09-01 08:00:00
        min      2000-01-01 00:00:00
        25%      2004-12-31 12:00:00
        50%      2010-01-01 00:00:00
        75%      2010-01-01 00:00:00
        max      2010-01-01 00:00:00
        dtype: object

        Describing a ``DataFrame``. By default only numeric fields
        are returned.

        >>> df = pd.DataFrame(
        ...     {
        ...         "categorical": pd.Categorical(["d", "e", "f"]),
        ...         "numeric": [1, 2, 3],
        ...         "object": ["a", "b", "c"],
        ...     }
        ... )
        >>> df.describe()
               numeric
        count      3.0
        mean       2.0
        std        1.0
        min        1.0
        25%        1.5
        50%        2.0
        75%        2.5
        max        3.0

        Describing all columns of a ``DataFrame`` regardless of data type.

        >>> df.describe(include="all")  # doctest: +SKIP
               categorical  numeric object
        count            3      3.0      3
        unique           3      NaN      3
        top              f      NaN      a
        freq             1      NaN      1
        mean           NaN      2.0    NaN
        std            NaN      1.0    NaN
        min            NaN      1.0    NaN
        25%            NaN      1.5    NaN
        50%            NaN      2.0    NaN
        75%            NaN      2.5    NaN
        max            NaN      3.0    NaN

        Describing a column from a ``DataFrame`` by accessing it as
        an attribute.

        >>> df.numeric.describe()
        count    3.0
        mean     2.0
        std      1.0
        min      1.0
        25%      1.5
        50%      2.0
        75%      2.5
        max      3.0
        Name: numeric, dtype: float64

        Including only numeric columns in a ``DataFrame`` description.

        >>> df.describe(include=[np.number])
               numeric
        count      3.0
        mean       2.0
        std        1.0
        min        1.0
        25%        1.5
        50%        2.0
        75%        2.5
        max        3.0

        Including only string columns in a ``DataFrame`` description.

        >>> df.describe(include=[object])  # doctest: +SKIP
               object
        count       3
        unique      3
        top         a
        freq        1

        Including only categorical columns from a ``DataFrame`` description.

        >>> df.describe(include=["category"])
               categorical
        count            3
        unique           3
        top              d
        freq             1

        Excluding numeric columns from a ``DataFrame`` description.

        >>> df.describe(exclude=[np.number])  # doctest: +SKIP
               categorical object
        count            3      3
        unique           3      3
        top              f      a
        freq             1      1

        Excluding object columns from a ``DataFrame`` description.

        >>> df.describe(exclude=[object])  # doctest: +SKIP
               categorical  numeric
        count            3      3.0
        unique           3      NaN
        top              f      NaN
        freq             1      NaN
        mean           NaN      2.0
        std            NaN      1.0
        min            NaN      1.0
        25%            NaN      1.5
        50%            NaN      2.0
        75%            NaN      2.5
        max            NaN      3.0
        r   percentilesincludeexcluder   Nr   Tc                4    |                                S )Nr  )describe)r	  r  r  r  s    rm   r   z"GroupBy.describe.<locals>.<lambda>K  s!    !** +Wg %   ro   )r  )r   r   r  r(  unstackrA  r]   r   r   r  rw   r   rL  rR   r  )rl   r  r  r  r   	describedr   s    ```   rm   r  zGroupBy.describeH  st   j 's88q=='' %  I x1}}""**,,??$$&+BQB//dJ55 	 	//      !% 0  F	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 !!} 	60088F(V55FLs   B>>CCr_   c               J    ddl m} |rt          d           || |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
            Possible arguments are `how`, `fill_method`, `limit`, `kind` and
            `on`, and other arguments of `TimeGrouper`.
        include_groups : bool, default True
            When True, will attempt to include the groupings in the operation in
            the case that they are columns of the DataFrame. If this raises a
            TypeError, the result will be computed with the groupings excluded.
            When False, the groupings will be excluded when applying ``func``.

            .. versionadded:: 2.2.0

            .. versionchanged:: 3.0

               The default was changed to False, and True is no longer allowed.

        **kwargs
            Possible arguments are `how`, `fill_method`, `limit`, `kind` and
            `on`, and other arguments of `TimeGrouper`.

        Returns
        -------
        DatetimeIndexResampler, PeriodIndexResampler or TimdeltaResampler
            Resampler object for the type of the index.

        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="min")
        >>> 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("3min").sum()
                                 b
        a
        0   2000-01-01 00:00:00  2
            2000-01-01 00:03:00  1
        5   2000-01-01 00:00:00  1

        Upsample the series into 30 second bins.

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

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

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

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

        >>> (df.groupby("a").resample("3min", closed="right").sum())
                                 b
        a
        0   1999-12-31 23:57:00  1
            2000-01-01 00:00:00  2
        5   2000-01-01 00:00:00  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("3min", closed="right", label="right").sum())
                                 b
        a
        0   2000-01-01 00:00:00  1
            2000-01-01 00:03:00  2
        5   2000-01-01 00:03:00  1
        r   )get_resampler_for_groupingr  )pandas.core.resampler  r   )rl   ruler  rs   rt   r  s         rm   resamplezGroupBy.resampleZ  sS    b 	DCCCCC 	JHIII))$FtFFFvFFFro   singlewindow9int | datetime.timedelta | str | BaseOffset | BaseIndexerr  
int | Nonecenterwin_type
str | NoneonclosedIntervalClosedType | Noner  rb   c                V    ddl m}  || j        |||||||| j        | j        
  
        S )a?  
        Return a rolling grouper, providing rolling functionality per group.

        Parameters
        ----------
        window : int, timedelta, str, offset, or BaseIndexer subclass
            Interval of the moving window.

            If an integer, the delta between the start and end of each window.
            The number of points in the window depends on the ``closed`` argument.

            If a timedelta, str, or offset, the time period of each window. Each
            window will be a variable sized based on the observations included in
            the time-period. This is only valid for datetimelike indexes.
            To learn more about the offsets & frequency strings, please see
            :ref:`this link<timeseries.offset_aliases>`.

            If a BaseIndexer subclass, the window boundaries
            based on the defined ``get_window_bounds`` method. Additional rolling
            keyword arguments, namely ``min_periods``, ``center``, ``closed`` and
            ``step`` will be passed to ``get_window_bounds``.

        min_periods : int, default None
            Minimum number of observations in window required to have a value;
            otherwise, result is ``np.nan``.

            For a window that is specified by an offset,
            ``min_periods`` will default to 1.

            For a window that is specified by an integer, ``min_periods`` will default
            to the size of the window.

        center : bool, default False
            If False, set the window labels as the right edge of the window index.

            If True, set the window labels as the center of the window index.

        win_type : str, default None
            If ``None``, all points are evenly weighted.

            If a string, it must be a valid `scipy.signal window function
            <https://docs.scipy.org/doc/scipy/reference/signal.windows.html#module-scipy.signal.windows>`__.

            Certain Scipy window types require additional parameters to be passed
            in the aggregation function. The additional parameters must match
            the keywords specified in the Scipy window type method signature.

        on : str, optional
            For a DataFrame, a column label or Index level on which
            to calculate the rolling window, rather than the DataFrame's index.

            Provided integer column is ignored and excluded from result since
            an integer index is not used to calculate the rolling window.

        closed : str, default None
            Determines the inclusivity of points in the window

            If ``'right'``, uses the window (first, last] meaning the last point
            is included in the calculations.

            If ``'left'``, uses the window [first, last) meaning the first point
            is included in the calculations.

            If ``'both'``, uses the window [first, last] meaning all points in
            the window are included in the calculations.

            If ``'neither'``, uses the window (first, last) meaning the first
            and last points in the window are excluded from calculations.

            () and [] are referencing open and closed set
            notation respetively.

            Default ``None`` (``'right'``).

        method : str {'single', 'table'}, default 'single'
            Execute the rolling operation per single column or row (``'single'``)
            or over the entire object (``'table'``).

            This argument is only implemented when specifying ``engine='numba'``
            in the method call.

        Returns
        -------
        pandas.api.typing.RollingGroupby
            Return a new grouper with our rolling appended.

        See Also
        --------
        Series.rolling : Calling object with Series data.
        DataFrame.rolling : Calling object with DataFrames.
        Series.groupby : Apply a function groupby to a Series.
        DataFrame.groupby : Apply a function groupby.

        Examples
        --------
        >>> df = pd.DataFrame(
        ...     {
        ...         "A": [1, 1, 2, 2],
        ...         "B": [1, 2, 3, 4],
        ...         "C": [0.362, 0.227, 1.267, -0.562],
        ...     }
        ... )
        >>> df
              A  B      C
        0     1  1  0.362
        1     1  2  0.227
        2     2  3  1.267
        3     2  4 -0.562

        >>> df.groupby("A").rolling(2).sum()
            B      C
        A
        1 0  NaN    NaN
          1  3.0  0.589
        2 2  NaN    NaN
          3  7.0  0.705

        >>> df.groupby("A").rolling(2, min_periods=1).sum()
            B      C
        A
        1 0  1.0  0.362
          1  3.0  0.589
        2 2  3.0  1.267
          3  7.0  0.705

        >>> df.groupby("A").rolling(2, on="B").sum()
            B      C
        A
        1 0  1    NaN
          1  2  0.589
        2 2  3    NaN
          3  4  0.705
        r   )rb   )	r  r  r  r  r  r  r  r   	_as_index)pandas.core.windowrb   rx   r   r   )	rl   r  r  r  r  r  r  r  rb   s	            rm   rollingzGroupBy.rolling  sU    ` 	655555~#]m
 
 
 	
ro   r`   c                @    ddl m}  || j        ||| j                  S )a  
        Return an expanding grouper, providing expanding functionality per group.

        Parameters
        ----------
        min_periods : int, default 1
            Minimum number of observations in window required to have a value;
            otherwise, result is ``np.nan``.

        method : str {'single', 'table'}, default 'single'
            Execute the expanding operation per single column or row (``'single'``)
            or over the entire object (``'table'``).

            This argument is only implemented when specifying ``engine='numba'``
            in the method call.

        Returns
        -------
        pandas.api.typing.ExpandingGroupby
            An object that supports expanding transformations over each group.

        See Also
        --------
        Series.expanding : Expanding transformations for Series.
        DataFrame.expanding : Expanding transformations for DataFrames.
        Series.groupby : Apply a function groupby to a Series.
        DataFrame.groupby : Apply a function groupby.

        Examples
        --------
        >>> df = pd.DataFrame(
        ...     {
        ...         "Class": ["A", "A", "A", "B", "B", "B"],
        ...         "Value": [10, 20, 30, 40, 50, 60],
        ...     }
        ... )
        >>> df
        Class  Value
        0     A     10
        1     A     20
        2     A     30
        3     B     40
        4     B     50
        5     B     60

        >>> df.groupby("Class").expanding().mean()
                Value
        Class
        A     0   10.0
              1   15.0
              2   20.0
        B     3   40.0
              4   45.0
              5   50.0
        r   )r`   )r  r  r   )r  r`   rx   r   )rl   r  r  r`   s       rm   	expandingzGroupBy.expandingq  sB    z 	877777#]	
 
 
 	
ro   r   float | Nonespanhalflifefloat | str | Timedelta | Nonealphaadjust	ignore_natimesnp.ndarray | Series | Nonera   c
                N    ddl m}
  |
| j        |||||||||	| j                  S )a	  
        Return an ewm grouper, providing ewm functionality per group.

        Parameters
        ----------
        com : float, optional
            Specify decay in terms of center of mass.
            Alternative to ``span``, ``halflife``, and ``alpha``.

        span : float, optional
            Specify decay in terms of span.

        halflife : float, str, or Timedelta, optional
            Specify decay in terms of half-life.

        alpha : float, optional
            Specify smoothing factor directly.

        min_periods : int, default 0
            Minimum number of observations in the window required to have a value;
            otherwise, result is ``np.nan``.

        adjust : bool, default True
            Divide by decaying adjustment factor to account for imbalance in
            relative weights.

        ignore_na : bool, default False
            Ignore missing values when calculating weights.

        times : str or array-like of datetime64, optional
            Times corresponding to the observations.

        method : {'single', 'table'}, default 'single'
            Execute the operation per group independently (``'single'``) or over the
            entire object before regrouping (``'table'``). Only applicable to
            ``mean()``, and only when using ``engine='numba'``.

        Returns
        -------
        pandas.api.typing.ExponentialMovingWindowGroupby
            An object that supports exponentially weighted moving transformations over
            each group.

        See Also
        --------
        Series.ewm : EWM transformations for Series.
        DataFrame.ewm : EWM transformations for DataFrames.
        Series.groupby : Apply a function groupby to a Series.
        DataFrame.groupby : Apply a function groupby.

        Examples
        --------
        >>> df = pd.DataFrame(
        ...     {
        ...         "Class": ["A", "A", "A", "B", "B", "B"],
        ...         "Value": [10, 20, 30, 40, 50, 60],
        ...     }
        ... )
        >>> df
        Class  Value
        0     A     10
        1     A     20
        2     A     30
        3     B     40
        4     B     50
        5     B     60

        >>> df.groupby("Class").ewm(com=0.5).mean()
                     Value
        Class
        A     0  10.000000
              1  17.500000
              2  26.153846
        B     3  40.000000
              4  47.500000
              5  56.153846
        r   )ra   )
r   r  r  r  r  r  r  r  r  r   )r  ra   rx   r   )rl   r   r  r  r  r  r  r  r  r  ra   s              rm   ewmzGroupBy.ewm  sX    t 	FEEEEE--#]
 
 
 	
ro   	directionLiteral['ffill', 'bfill']limitc                2   	 |d} j         j        } j         j        }t          t          j        |||dk    |          	d		 fd}                                 }|                    |          }                     |          } j	        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  ffill)r.  r  compute_ffillr   r*  r   rg   c                   t          |           }| j        dk    rGt          j        | j        t          j                  } ||           t          j        | |          S t          | t          j	                  rC| j
        }j        j        rt          | j
                  }t          j        | j        |          }n.t          |                               | j        | j
                  }t!          |           D ]_\  }}t          j        | j        d         t          j                  } |||                    t          j        ||          ||d d f<   `|S )Nr   r  )r  r/  )r8   r(  r   r  r  r  r;   r  r   ndarrayr  r   r  r*   r   _emptyrE  )	r*  r/  r1  r  r  ivalue_elementcol_funcrl   s	          rm   blk_funczGroupBy._fill.<locals>.blk_funcH  sJ   <<D{a(6<rw???W40000!)&':::
 fbj11 P"LE}3 G 8 F F(6<u===CC v,,--fl&,-OOC(1&(9(9 K K$A} hv|AbgFFFGHtAw7777 * 2=' J JC111II
ro   r  )r   r  r   r
   
libgroupbygroup_fillna_indexerr  rm  r  r   r  )
rl   r  r  r  r   r  mgrrs  r  r  s
   `        @rm   _fillzGroupBy._fill!  s    2 =Em-'+$/
 
 
	 	 	 	 	 	 	< ))++))H%%**733ro   c                0    |                      d|          S )a3	  
        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.

        Examples
        --------

        For SeriesGroupBy:

        >>> key = [0, 0, 1, 1]
        >>> ser = pd.Series([np.nan, 2, 3, np.nan], index=key)
        >>> ser
        0    NaN
        0    2.0
        1    3.0
        1    NaN
        dtype: float64
        >>> ser.groupby(level=0).ffill()
        0    NaN
        0    2.0
        1    3.0
        1    3.0
        dtype: float64

        For DataFrameGroupBy:

        >>> df = pd.DataFrame(
        ...     {
        ...         "key": [0, 0, 1, 1, 1],
        ...         "A": [np.nan, 2, np.nan, 3, np.nan],
        ...         "B": [2, 3, np.nan, np.nan, np.nan],
        ...         "C": [np.nan, np.nan, 2, np.nan, np.nan],
        ...     }
        ... )
        >>> df
           key    A    B   C
        0    0  NaN  2.0 NaN
        1    0  2.0  3.0 NaN
        2    1  NaN  NaN 2.0
        3    1  3.0  NaN NaN
        4    1  NaN  NaN NaN

        Propagate non-null values forward or backward within each group along columns.

        >>> df.groupby("key").ffill()
             A    B   C
        0  NaN  2.0 NaN
        1  2.0  3.0 NaN
        2  NaN  NaN 2.0
        3  3.0  NaN 2.0
        4  3.0  NaN 2.0

        Propagate non-null values forward or backward within each group along rows.

        >>> df.T.groupby(np.array([0, 0, 1, 1])).ffill().T
           key    A    B    C
        0  0.0  0.0  2.0  2.0
        1  0.0  2.0  3.0  3.0
        2  1.0  1.0  NaN  2.0
        3  1.0  3.0  NaN  NaN
        4  1.0  1.0  NaN  NaN

        Only replace the first NaN element within a group along columns.

        >>> df.groupby("key").ffill(limit=1)
             A    B    C
        0  NaN  2.0  NaN
        1  2.0  3.0  NaN
        2  NaN  NaN  2.0
        3  3.0  NaN  2.0
        4  3.0  NaN  NaN
        r  r  r  rl   r  s     rm   r  zGroupBy.ffillm  s    t zz'z///ro   c                0    |                      d|          S )a  
        Backward fill the values.

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

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

        See Also
        --------
        Series.bfill :  Backward fill the missing values in the dataset.
        DataFrame.bfill:  Backward fill the missing values in the dataset.
        Series.fillna: Fill NaN values of a Series.
        DataFrame.fillna: Fill NaN values of a DataFrame.

        Examples
        --------

        With Series:

        >>> index = ["Falcon", "Falcon", "Parrot", "Parrot", "Parrot"]
        >>> s = pd.Series([None, 1, None, None, 3], index=index)
        >>> s
        Falcon    NaN
        Falcon    1.0
        Parrot    NaN
        Parrot    NaN
        Parrot    3.0
        dtype: float64
        >>> s.groupby(level=0).bfill()
        Falcon    1.0
        Falcon    1.0
        Parrot    3.0
        Parrot    3.0
        Parrot    3.0
        dtype: float64
        >>> s.groupby(level=0).bfill(limit=1)
        Falcon    1.0
        Falcon    1.0
        Parrot    NaN
        Parrot    3.0
        Parrot    3.0
        dtype: float64

        With DataFrame:

        >>> df = pd.DataFrame(
        ...     {"A": [1, None, None, None, 4], "B": [None, None, 5, None, 7]},
        ...     index=index,
        ... )
        >>> df
                  A	    B
        Falcon	1.0	  NaN
        Falcon	NaN	  NaN
        Parrot	NaN	  5.0
        Parrot	NaN	  NaN
        Parrot	4.0	  7.0
        >>> df.groupby(level=0).bfill()
                  A	    B
        Falcon	1.0	  NaN
        Falcon	NaN	  NaN
        Parrot	4.0	  5.0
        Parrot	4.0	  7.0
        Parrot	4.0	  7.0
        >>> df.groupby(level=0).bfill(limit=1)
                  A	    B
        Falcon	1.0	  NaN
        Falcon	NaN	  NaN
        Parrot	NaN	  5.0
        Parrot	4.0	  7.0
        Parrot	4.0	  7.0
        bfillr  r  r  s     rm   r  zGroupBy.bfill  s    ^ zz'z///ro   rO   c                     t          |           S )a  
        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.

        Returns
        -------
        Series or DataFrame
            N-th value within each group.

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

        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)
           A   B
        0  1 NaN
        2  2 3.0
        >>> g.nth(1)
           A   B
        1  1 2.0
        4  2 5.0
        >>> g.nth(-1)
           A   B
        3  1 4.0
        4  2 5.0
        >>> g.nth([0, 1])
           A   B
        0  1 NaN
        1  1 2.0
        2  2 3.0
        4  2 5.0
        >>> g.nth(slice(None, -1))
           A   B
        0  1 NaN
        1  1 2.0
        2  2 3.0

        Index notation may also be used

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

        Specifying `dropna` allows ignoring ``NaN`` values

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

        When the specified ``n`` is larger than any of the groups, an
        empty DataFrame is returned

        >>> g.nth(3, dropna="any")
        Empty DataFrame
        Columns: [A, B]
        Index: []
        )rO   r   s    rm   nthzGroupBy.nth  s    f "$'''ro   r   PositionalIndexer | tupleLiteral['any', 'all'] | Nonec                   |sA|                      |          }| j        j        }||dk    z  }|                     |          }|S t	          |          st          d          |dvrt          d| d          t          t          |          }| j        	                    |d          }t          |          t          | j                  k    r| j        }nu| j        j        }| j        j        |                    |j                           }| j        j        r3|dk    }	t!          j        |	t$          |          }
t'          |
dd	
          }|                    || j        | j                  }|                    |          S )Nr  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).r   )r  r  Int64F)r  r6  )r   r   )"_make_mask_from_positional_indexerr   r  _mask_selected_objr/   r   r   r   rx   r   r   r  
codes_infoisinr  r  r   r  r   rP   re   r   r   r  )rl   r   r   r/  r  r  droppedr   r  nullsr*  grbs               rm   _nthzGroupBy._ntho  s   
  		::1==D-#C 3"9%D))$//CJ !}} 	USTTT''*%* * *   aLL$++Q+?? w<<3t12222mGG
 =%Dm.tyy/G/GHG}+ C2 %W55gEBBBoogDIoNNwwqzzro         ?linearqfloat | AnyArrayLikeinterpolation;Literal['linear', 'lower', 'higher', 'nearest', 'midpoint']c                   |                      |d          }|                     |          }| j                            |          }|j        }t          j        |j        |j                  \  }}	dddfdt          |          r$t          j        |gt          j                  }
d}n"t          j        |t          j                  }
|
}| j        j        }| j        j        | j        r||dk             }t!          |
          t#          t$          j        ||
||	          dfd}|j                            |          }|                     |          }|                     ||          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 False
            Include only `float`, `int` or `boolean` data.

            .. versionchanged:: 2.0.0

                numeric_only now defaults to ``False``.

        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  valsr   rg   "tuple[np.ndarray, DtypeObj | None]c                V   t          | j        t                    st          | j                  rt	          d| j         d          d }t          | t
                    rCt          | j                  r/|                     t          t          j
                  }| j        }nt          | j                  r^t          | t                    r'|                     t          t          j
                  }n| }t          j        t          j                  }nt          | j                  r<t          | t                    r'|                     t          t          j
                  }nt          | j                  rt	          d          t          | j                  r| j        }| |fS t          | t                    rYt!          | j                  rEt          j        t          j                  }|                     t          t          j
                  }nt          j        |           }||fS )Nzdtype 'z'' does not support operation 'quantile')r  r_  z#Cannot use quantile with bool dtype)r   r  rD   r3   r  r?   r2   rX  floatr   r   r0   r@   r  r,   r6   r-   r  asarray)r  	inferencer  s      rm   pre_processorz'GroupBy.quantile.<locals>.pre_processor  s   $*k22 odj6Q6Q QdjQQQ   *.I$00 '5Edj5Q5Q 'mm%"&mAA J		!$*-- 'dN33 --ebf-EECCCHRX..		tz** 'z$/O/O 'mm%"&mAAtz** ' EFFF$TZ00 ' J	 Y&D.11 'nTZ6P6P 'HRZ00	mm%"&mAAj&&	>!ro   r  r  DtypeObj | Noneresult_masknp.ndarray | None	orig_valsc                   |rNt          |t                    r|J dv rt          |          st          | |          S t	          j                    5  t	          j        dt                      t          |          | 	                    |j
                  |          cd d d            S # 1 swxY w Y   nt          |          rdv st          |          rG| 	                    d                              |j        j                  } |                    |           S t          |t"          j                  sJ | 	                    |          S | S )N>   r  midpointignore)categoryi8)r   r?   r-   rA   r   catch_warningsfilterwarningsRuntimeWarningr   r  numpy_dtyper0   r6   view_ndarrayr  _from_backing_datar   )r  r  r  r  r  s       rm   post_processorz(GroupBy.quantile.<locals>.post_processor  s     (2i99 &2&222$(>>>~!H H>  -T;???
 &466  $3H~VVVV#24	?? $$-$9!" !" !,	$ $                 %Y//2%)???*955 
  ${{40055%.4   
  );;      &i:::::;;y111Ks   AB--B14B1r  Nr   )r.  r=  r  rb  rc  r*  c                   | }t          | t                    r*| j        }t          j        ft          j                  }nt          |           }d }t          | j                  } |           \  }}d}|j	        dk    r|j
        d         }t          j        |ft          j                  }|r|                    d          }|j	        dk    r 
|d         ||||           n4t          |          D ]$}	 
||	         ||	         ||	         d |           %|j	        dk    r-|                    d          }||                    d          }n|                    |z            } ||||          S )Nr  r   rj  r   r  )r*  r/  r  is_datetimelikeK)r   r?   _maskr   r  r  r8   r6   r  r(  r  r  r  r  rB  r{  r  )r*  r  r/  r  r  r  r  ncolsr  r  r   r   nqsr  r  s             rm   r  z"GroupBy.quantile.<locals>.blk_funcL  s   I&/22 #| h~RXFFFF||"1&,??O+mF33OD)EyA~~
1(E7C0
CCCC 'yyyA~~F +$3     u  ADA#Aw!!W$((7     yA~~iinn*"-"3"3C"8"8Kkk%377!>#y+yIIIro   rN  )r  r   rg   r  )
r  r  r  r  r  r  r  r   rg   r   r  )r  r  r   _get_splitter_sorted_datar   r[  _slabelsr   r4   r   r  r  r  r  r   r   r
   r  group_quantilerl  r  rQ  )rl   r  r  r  r  r   splittersdatarb  rc  r=  pass_qsr  r  rs  r  r   r   r  r  r  s     `             @@@@@rm   r  zGroupBy.quantile  s   ` ))|*)UU&&s++=..s33%*8+<h>NOO$	" $	" $	" $	"L0	 0	 0	 0	 0	 0	d Q<< 	1#RZ000B)-GGARZ000BGm-'; 	 cQh-C"gg%'
 
 
0	J 0	J 0	J 0	J 0	J 0	J 0	J 0	J 0	J 0	Jd *++H55&&w//++CG+<<<ro   c                   | j         }|j        }| j        j        }| j        j        r1t          j        |dk    t
          j        |          }t
          j        }nt
          j	        }t          d | j        j        D                       rt          |d          dz
  }|                     |||          }|s| j        dz
  |z
  }|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.

        Groups with missing keys (where `pd.isna()` is True) will be labeled with `NaN`
        and will be skipped from the count.

        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({"color": ["red", None, "red", "blue", "blue", "red"]})
        >>> df
          color
        0   red
        1   NaN
        2   red
        3  blue
        4  blue
        5   red
        >>> df.groupby("color").ngroup()
        0    1.0
        1    NaN
        2    1.0
        3    0.0
        4    0.0
        5    1.0
        dtype: float64
        >>> df.groupby("color", dropna=False).ngroup()
        0    1
        1    2
        2    1
        3    0
        4    0
        5    1
        dtype: int64
        >>> df.groupby("color", dropna=False).ngroup(ascending=False)
        0    1
        1    0
        2    1
        3    2
        4    2
        5    1
        dtype: int64
        r  c              3  $   K   | ]}|j         V  d S rj   _passed_categoricalr   pings     rm   r   z!GroupBy.ngroup.<locals>.<genexpr>  s%      LLDt'LLLLLLro   dense)ties_methodr   r  )r   r  r   r  r  r   r  r   r  r  r  rB  r   r  r   )rl   r  r   r  comp_idsr  r   s          rm   ngroupzGroupBy.ngroup  s    ~ '	=$ =' 	xBAAHJEEHELLDM4KLLLLL 	BxW===AH))(E)GG 	/\A%.Fro   c                r    | j         j        }|                     |          }|                     ||          S )ae  
        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  )r   r  r  r  )rl   r  r  	cumcountss       rm   cumcountzGroupBy.cumcount  s<    j )/((9(==	''	5999ro   averagekeep	na_optionpctc                Z    |dvrd}t          |          ||||d} | j        	 dddi|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.

        Returns
        -------
        DataFrame
            The ranking of values within each group.

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

        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')r  r  r  r  rankr  F)r  )r   r  )rl   r  r  r  r  r   rt   s          rm   r  zGroupBy.rank  so    R 555GCS//! """	
 
 &t%
 

 
 
 	
ro   c                P    t          j        d||dg            | j        d|fi |S )aN  
        Cumulative product for each group.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns.
        *args : tuple
            Positional arguments to be passed to `func`.
        **kwargs : dict
            Additional/specific keyword arguments to be passed to the function,
            such as `numeric_only` and `skipna`.

        Returns
        -------
        Series or DataFrame
            Cumulative product for each group. Same object type as the caller.

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

        Examples
        --------
        For SeriesGroupBy:

        >>> lst = ["a", "a", "b"]
        >>> ser = pd.Series([6, 2, 0], index=lst)
        >>> ser
        a    6
        a    2
        b    0
        dtype: int64
        >>> ser.groupby(level=0).cumprod()
        a    6
        a   12
        b    0
        dtype: int64

        For DataFrameGroupBy:

        >>> data = [[1, 8, 2], [1, 2, 5], [2, 6, 9]]
        >>> df = pd.DataFrame(
        ...     data, columns=["a", "b", "c"], index=["cow", "horse", "bull"]
        ... )
        >>> df
                a   b   c
        cow     1   8   2
        horse   1   2   5
        bull    2   6   9
        >>> df.groupby("a").groups
        {1: ['cow', 'horse'], 2: ['bull']}
        >>> df.groupby("a").cumprod()
                b   c
        cow     8   2
        horse  16  10
        bull    6   9
        cumprodr  nvvalidate_groupby_funcr  rl   r  rs   rt   s       rm   r!  zGroupBy.cumprodi  s;    z 	 D&8*EEE%t%iHHHHHro   c                P    t          j        d||dg            | j        d|fi |S )aT  
        Cumulative sum for each group.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns.
        *args : tuple
            Positional arguments to be passed to `func`.
        **kwargs : dict
            Additional/specific keyword arguments to be passed to the function,
            such as `numeric_only` and `skipna`.

        Returns
        -------
        Series or DataFrame
            Cumulative sum for each group. Same object type as the caller.

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

        Examples
        --------
        For SeriesGroupBy:

        >>> lst = ["a", "a", "b"]
        >>> ser = pd.Series([6, 2, 0], index=lst)
        >>> ser
        a    6
        a    2
        b    0
        dtype: int64
        >>> ser.groupby(level=0).cumsum()
        a    6
        a    8
        b    0
        dtype: int64

        For DataFrameGroupBy:

        >>> data = [[1, 8, 2], [1, 2, 5], [2, 6, 9]]
        >>> df = pd.DataFrame(
        ...     data, columns=["a", "b", "c"], index=["fox", "gorilla", "lion"]
        ... )
        >>> df
                  a   b   c
        fox       1   8   2
        gorilla   1   2   5
        lion      2   6   9
        >>> df.groupby("a").groups
        {1: ['fox', 'gorilla'], 2: ['lion']}
        >>> df.groupby("a").cumsum()
                  b   c
        fox       8   2
        gorilla  10   7
        lion      6   9
        r  r  r"  r%  s       rm   r  zGroupBy.cumsum  s;    z 	 4(DDD%t%hGGGGGro   c                ^    |                     dd          }|                     d||          S )a  
        Cumulative min for each group.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only `float`, `int` or `boolean` data.
        **kwargs : dict, optional
            Additional keyword arguments to be passed to the function, such as `skipna`,
            to control whether NA/null values are ignored.

        Returns
        -------
        Series or DataFrame
            Cumulative min for each group. Same object type as the caller.

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

        Examples
        --------
        For SeriesGroupBy:

        >>> lst = ["a", "a", "a", "b", "b", "b"]
        >>> ser = pd.Series([1, 6, 2, 3, 0, 4], index=lst)
        >>> ser
        a    1
        a    6
        a    2
        b    3
        b    0
        b    4
        dtype: int64
        >>> ser.groupby(level=0).cummin()
        a    1
        a    1
        a    1
        b    3
        b    0
        b    0
        dtype: int64

        For DataFrameGroupBy:

        >>> data = [[1, 0, 2], [1, 1, 5], [6, 6, 9]]
        >>> df = pd.DataFrame(
        ...     data, columns=["a", "b", "c"], index=["snake", "rabbit", "turtle"]
        ... )
        >>> df
                a   b   c
        snake   1   0   2
        rabbit  1   1   5
        turtle  6   6   9
        >>> df.groupby("a").groups
        {1: ['snake', 'rabbit'], 6: ['turtle']}
        >>> df.groupby("a").cummin()
                b   c
        snake   0   2
        rabbit  0   2
        turtle  6   9
        r  Tcumminr  r   r  rl   r  rt   r  s       rm   r(  zGroupBy.cummin  s<    J Hd++%%< & 
 
 	
ro   c                ^    |                     dd          }|                     d||          S )ao  
        Cumulative max for each group.

        Returns the cumulative maximum of values within each group. The result
        has the same size as the input, with each element representing the
        maximum of all preceding elements (including itself) within its group.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only `float`, `int` or `boolean` data.
        **kwargs : dict, optional
            Additional keyword arguments to be passed to the function, such as `skipna`,
            to control whether NA/null values are ignored.

        Returns
        -------
        Series or DataFrame
            Cumulative max for each group. Same object type as the caller.

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

        Examples
        --------
        For SeriesGroupBy:

        >>> lst = ["a", "a", "a", "b", "b", "b"]
        >>> ser = pd.Series([1, 6, 2, 3, 1, 4], index=lst)
        >>> ser
        a    1
        a    6
        a    2
        b    3
        b    1
        b    4
        dtype: int64
        >>> ser.groupby(level=0).cummax()
        a    1
        a    6
        a    6
        b    3
        b    3
        b    4
        dtype: int64

        For DataFrameGroupBy:

        >>> data = [[1, 8, 2], [1, 1, 0], [2, 6, 9]]
        >>> df = pd.DataFrame(
        ...     data, columns=["a", "b", "c"], index=["cow", "horse", "bull"]
        ... )
        >>> df
                a   b   c
        cow     1   8   2
        horse   1   1   0
        bull    2   6   9
        >>> df.groupby("a").groups
        {1: ['cow', 'horse'], 2: ['bull']}
        >>> df.groupby("a").cummax()
                b   c
        cow     8   2
        horse   8   2
        bull    6   9
        r  Tcummaxr  r)  r*  s       rm   r,  zGroupBy.cummax3  s<    R Hd++%%< & 
 
 	
ro   periodsint | Sequence[int]suffixc           	        t          |          r@t          t          |          }t          |          dk    rt	          d          ddlm} d}n[t          |          s#t          d| dt          |           d          |rt	          d          t          t          |          g}d	}g }|D ]t                    s#t          d dt                     d          t          t                    %fd}|                     || j        d          }	nt          j        u rd
| j        j        }
| j        j        }t%          j        t          |
          t$          j                  }t+          j        ||
|           | j        }|                    d|j        |fid          }	|r]t5          |	t6                    r't          t8          |	                                          }	|	                    |r| d nd           }	|                    t          t@          t6          tB          f         |	                     t          |          dk    r|d         n ||dd	          S )a  
        Shift each group by periods observations.

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

        Parameters
        ----------
        periods : int | Sequence[int], default 1
            Number of periods to shift. If a list of values, shift each group by
            each period.
        freq : str, optional
            Frequency string.
        fill_value : optional
            The scalar value to use for newly introduced missing values.

            .. versionchanged:: 2.1.0
                Will raise a ``ValueError`` if ``freq`` is provided too.

        suffix : str, optional
            A string to add to each shifted column if there are multiple periods.
            Ignored otherwise.

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

        See Also
        --------
        Index.shift : Shift values of Index.

        Examples
        --------

        For SeriesGroupBy:

        >>> lst = ["a", "a", "b", "b"]
        >>> ser = pd.Series([1, 2, 3, 4], index=lst)
        >>> ser
        a    1
        a    2
        b    3
        b    4
        dtype: int64
        >>> ser.groupby(level=0).shift(1)
        a    NaN
        a    1.0
        b    NaN
        b    3.0
        dtype: float64

        For DataFrameGroupBy:

        >>> data = [[1, 2, 3], [1, 5, 6], [2, 5, 8], [2, 6, 9]]
        >>> df = pd.DataFrame(
        ...     data,
        ...     columns=["a", "b", "c"],
        ...     index=["tuna", "salmon", "catfish", "goldfish"],
        ... )
        >>> df
                   a  b  c
            tuna   1  2  3
          salmon   1  5  6
         catfish   2  5  8
        goldfish   2  6  9
        >>> df.groupby("a").shift(1)
                      b    c
            tuna    NaN  NaN
          salmon    2.0  3.0
         catfish    NaN  NaN
        goldfish    5.0  8.0
        r   z0If `periods` is an iterable, it cannot be empty.r  TzPeriods must be integer, but z is .z/Cannot specify `suffix` if `periods` is an int.FNc                4    |                      d          S )Nr   )shift)r	  
fill_valuefreqperiods    rm   r   zGroupBy.shift.<locals>.<lambda>  s!    agg	  ro   r  r  )r4  r  r2  r   )r  r   )"r1   r   r	   r   r   r  r  r/   r  r   r   rw   rx   r   
no_defaultr   r  r   r   r  r  r  group_shift_indexerr   r  r  r   rT   r   rA  
add_suffixappendr   rH   )rl   r-  r5  r4  r/  r  r:  shifted_dataframesru   shiftedr  r   res_indexerr   r6  s     ``          @rm   r3  zGroupBy.shift  s   `    	8W--G7||q   !STTT999999JJg&& QGQQgQQQ    T !RSSSC))*GJ '	O '	OFf%% OFOOVOOO   #v&&F      44t) 5   //!%Jm'-/ hs3xxrx@@@.{C&QQQ/44K01)# 5    gv.. A"8W-=-=-?-?@@G!,,,2Dv(((((F  %%d51B+CW&M&MNNNN %&&!++ q!!*???	
ro   c                N   | j         }|                     |          }ddg|j        dk    r|j        v r|                    d          }nUfd|j                                        D             }|r.|                    t                              |d                    }||z
  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.

        Returns
        -------
        Series or DataFrame
            First differences.

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

        Examples
        --------
        For SeriesGroupBy:

        >>> lst = ["a", "a", "a", "b", "b", "b"]
        >>> ser = pd.Series([7, 2, 8, 4, 3, 3], index=lst)
        >>> ser
        a     7
        a     2
        a     8
        b     4
        b     3
        b     3
        dtype: int64
        >>> ser.groupby(level=0).diff()
        a    NaN
        a   -5.0
        a    6.0
        b    NaN
        b   -1.0
        b    0.0
        dtype: float64

        For DataFrameGroupBy:

        >>> data = {"a": [1, 3, 5, 7, 7, 8, 3], "b": [1, 4, 8, 4, 4, 2, 1]}
        >>> df = pd.DataFrame(
        ...     data, index=["dog", "dog", "dog", "mouse", "mouse", "mouse", "mouse"]
        ... )
        >>> df
                 a  b
          dog    1  1
          dog    3  4
          dog    5  8
        mouse    7  4
        mouse    7  4
        mouse    8  2
        mouse    3  1
        >>> df.groupby(level=0).diff()
                 a    b
          dog  NaN  NaN
          dog  2.0  3.0
          dog  2.0  4.0
        mouse  NaN  NaN
        mouse  0.0  0.0
        mouse  1.0 -2.0
        mouse -5.0 -1.0
        )r-  int8int16r   float32c                "    g | ]\  }}|v 	|S r   r   )r   cr  dtypes_to_f32s      rm   
<listcomp>z GroupBy.diff.<locals>.<listcomp>f  s'    XXXxq%-AWAWAWAWAWro   )	r   r3  r(  r  r  dtypesitemsdictfromkeys)rl   r-  r   r=  	to_coercerE  s        @rm   r  zGroupBy.diff  s    T '**W*--  )8q==yM))!..33XXXX3:+;+;+=+=XXXI N!..y))L)LMMW}ro   fill_methodc                F   |t          d|d          #fd}|                     || j        d          S |d}n|} t          | |          d	          }|                    | j        j        | j        
          }|                              }||z  dz
  S )a  
        Calculate pct_change of each value to previous entry in group.

        Parameters
        ----------
        periods : int, default 1
            Periods to shift for calculating percentage change. Comparing with
            a period of 1 means adjacent elements are compared, whereas a period
            of 2 compares every other element.

        fill_method : None
            Must be None. This argument will be removed in a future version of pandas.

        freq : str, pandas offset object, or None, default None
            The frequency increment for time series data (e.g., 'M' for month-end).
            If None, the frequency is inferred from the index. Relevant for time
            series data only.

        Returns
        -------
        Series or DataFrame
            Percentage changes within each group.

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

        Examples
        --------

        For SeriesGroupBy:

        >>> lst = ["a", "a", "b", "b"]
        >>> ser = pd.Series([1, 2, 3, 4], index=lst)
        >>> ser
        a    1
        a    2
        b    3
        b    4
        dtype: int64
        >>> ser.groupby(level=0).pct_change()
        a         NaN
        a    1.000000
        b         NaN
        b    0.333333
        dtype: float64

        For DataFrameGroupBy:

        >>> data = [[1, 2, 3], [1, 5, 6], [2, 5, 8], [2, 6, 9]]
        >>> df = pd.DataFrame(
        ...     data,
        ...     columns=["a", "b", "c"],
        ...     index=["tuna", "salmon", "catfish", "goldfish"],
        ... )
        >>> df
                   a  b  c
            tuna   1  2  3
          salmon   1  5  6
         catfish   2  5  8
        goldfish   2  6  9
        >>> df.groupby("a").pct_change()
                    b  c
            tuna    NaN    NaN
          salmon    1.5  1.000
         catfish    NaN    NaN
        goldfish    0.2  0.125
        Nz*fill_method must be None; got fill_method=r1  c                4    |                      d          S )Nr   )r-  r5  r  )
pct_change)r	  r5  r-  s    rm   r   z$GroupBy.pct_change.<locals>.<lambda>  s#    !,, '   ro   Tr7  r  r   r  )r   )r-  r5  r   )	r   rw   rx   r   re   r   codesr   r3  )	rl   r-  rL  r5  ru   opfilledfill_grpr=  s	    ` `     rm   rO  zGroupBy.pct_changel  s    \ "MkMMMNNN     A
 --a1CRV-WWWBBB"r""+++>>$-"5$/>RR..t.<< A%%ro      c                r    |                      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
        --------
        Series.head : Apply function head to a Series.
        DataFrame.head : Apply function head to each row or column of a DataFrame.

        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  slicer  rl   r   r/  s      rm   headzGroupBy.head  s4    J 66uT1~~FF&&t,,,ro   c                    |r%|                      t          | d                    }n|                      g           }|                     |          S )aI  
        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
        --------
        Series.tail : Apply function tail to a Series.
        DataFrame.tail : Apply function tail to each row or column of a DataFrame.

        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
        NrV  rX  s      rm   tailzGroupBy.tail  sS    P  	?::5!T??KKDD::2>>D&&t,,,ro   r/  npt.NDArray[np.bool_]c                F    | j         j        }||dk    z  }| j        |         S )a  
        Return _selected_obj with mask applied.

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

        Returns
        -------
        Series or DataFrame
            Filtered _selected_obj.
        r  )r   r  rx   )rl   r/  r  s      rm   r  zGroupBy._mask_selected_obj'  s*     msby!!$''ro   fracreplaceweightsSequence | Series | Nonerandom_stateRandomState | Nonec                T   | j         j        r| j         S t          j        |||          }|t          j        | j         |d          }t          j        |          }| j                            | j                   }g }	|D ]z\  }
}| j	        |
         }t          |          }||}n|J t          ||z            }t          j        ||||dn||         |          }|	                    ||                    {t          j        |	          }	| j                             |	d          S )a  
        Return a random sample of items from each group.

        You can use `random_state` for reproducibility.

        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.
            Default ``None`` results in sampling with the current state of np.random.

        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.
        Series.sample: Generate random samples from a Series 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`  rb  )rx   r  r<   process_sampling_sizepreprocess_weightsr   rb  r   r   r   r   roundr;  r   r  r&  )rl   r   r^  r_  r`  rb  r@  weights_arrgroup_iteratorsampled_indicesr.  r   grp_indices
group_sizesample_size
grp_samples                   rm   r<   zGroupBy.sample:  sP   x # 	&%%+AtW== 3D4FVWXXXK'5533D4FGG) 	< 	<KFC,v.K[))J"'''#D:$566  '[5M)  J "";z#:;;;;.99!&&Q&???ro   Literal['idxmax', 'idxmin']ignore_unobservedc                   | j         st          d | j        j        D                       rt	          | j        j                  }| j                                        }||dk             j        d         }||k    sJ ||k     }| o|}	| j        }
|	rCt          |
t                    r.|r|
                                }
t	          |
j                  dk    }	|	rt          d| d          nA|s?| j                                                            d          rt          | d          |                     |d||	          }|S )
a  Compute idxmax/idxmin.

        Parameters
        ----------
        how : {'idxmin', 'idxmax'}
            Whether to compute idxmin or idxmax.
        numeric_only : bool, default False
            Include only float, int, boolean columns.
        skipna : bool, default True
            Exclude NA/null values. If an entire group is NA, the result will be NA.
        ignore_unobserved : bool, default False
            When True and an unobserved group is encountered, do not raise. This used
            for transform where unobserved groups do not play an impact on the result.

        Returns
        -------
        Series or DataFrame
            idxmax or idxmin for the groupby operation.
        c              3  $   K   | ]}|j         V  d S rj   r  r  s     rm   r   z)GroupBy._idxmax_idxmin.<locals>.<genexpr>  s6       %
 %
)-D$%
 %
 %
 %
 %
 %
ro   r   z
Can't get zZ of an empty group due to unobserved categories. Specify observed=True in groupby instead.Nr  z+ with skipna=False encountered an NA value.r   )r  r  r  r  )r   r  r   rB  r   r  r@  r  r   r   rH   _get_numeric_datarH  r   r8   r  )rl   r  rp  r  r  expected_lengroup_sizes
result_lenhas_unobserved	raise_errrT  r   s               rm   r  zGroupBy._idxmax_idxmin  s   4 } 	R %
 %
151H%
 %
 %
 "
 "
 	R t}9::L-,,..K$[1_5;A>J----',6N->)>)Q>I ,D 2Zi88 2 41133D--1	  @ @ @ @  
  	RD5::<<@@d@KK 	RPPPQQQ""%	 # 
 
 ro   r  c                "   | j         j        }|j        dk    r|                    |j                  }n[|r;|                    d                              d           rt          | d          t          |t                    r|
                                }|j        }t          |t          j                  sJ t          |j        d          }t          |t                    r>|                    |j                            |d|          |j        |j                  }nii }t)          |j                  D ]%\  }	}
|j                            |
d|          ||	<   &| j                             ||j        	          }|j        |_        |S )
Nr   r  z7 with skipna=True encountered all NA values in a group.F)compatT)
allow_fillr4  r  )r  )r   r  r@  r  r  ltr  r   r   rQ   to_flat_indexr$  r   r  r9   rT   r|  r  r&  rz   rE  r]   rH  )rl   r  r  r  r  r   r*  r_  rT  kcolumn_valuess              rm   r  zGroupBy._wrap_idxmax_idxmin  s    8q==ZZ,,FF 	-q		400 	-OOO   %,, .++--[Ffbj11111)%+eDDDH#v&& -))K$$V$RR) *   (1&((;(;  $A}#k..%$8 /  DGG ..t39.EE!$ro   )
NNNNNTTTFT)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rg   rh   )r   r{   r   )FF)r  r   r  r   )r   r   rg   r   rj   )r   r<  r=  r>  rg   rH   )r   r<  r=  r>  )r*  r   r  r   r  r   )rT  rH   )r   r   re  rf  rg  rh  )r  r   rg   r   )NFF)ru   r   rT  r   r  r  r  r   r  r   rg   r   )Fr  )r  r   r  r   r  r{   r  r  )
r  r{   r*  r   r(  r   r  r   rg   r   )NFr  )r  r{   r  r  r  r   r  r   )F)r  r{   r  r   )r   r   rg   r   )T)r  r   rg   r  )rg   r   )r  r   rg   r   )rg   r   )FTNN)r  r   r  r   r  r  rg  rh  )FT)r  r   r  r   rg   r   )r   NNFT)
r  r   r  r  rg  rh  r  r   r  r   )NFTFT)r,  r-  r.  r   r   r   r  r   r   r   rg   r   )r   FT)r  r   r  r   r  r   rg   r   r   )Fr   TNN)
r  r   r  r   r  r   r  r  rg  rh  )Fr   T)r  r   r  r   r  r   rg   r   )Fr  TNN)Fr  T)rg   rH   )NNN)r  r   rg   r_   )NFNNNr  )r  r  r  r  r  r   r  r  r  r  r  r  r  r{   rg   rb   )r   r  )r  r   r  r{   rg   r`   )	NNNNr   TFNr  )r   r  r  r  r  r  r  r  r  r  r  r   r  r   r  r  r  r{   rg   ra   )r  r  r  r  )r  r  )rg   rO   )r   r  r   r  rg   r   )r  r  F)r  r  r  r  r  r   )r  r   )r  Tr  F)
r  r{   r  r   r  r{   r  r   rg   r   )r  r   rg   r   )r-  r.  r/  r  )r   )r-  r   rg   r   )r   NN)r-  r   rL  rh   )rT  )r   r   rg   r   )r/  r\  rg   r   )NNFNN)
r   r  r^  r  r_  r   r`  ra  rb  rc  )FTF)
r  ro  rp  r   r  r   r  r   rg   r   )r  r   r  ro  r  r   rg   r   )Mrv   r   r   r   r   r   rn   r   r  r3  r  rL  rQ  rU  rd  rt  r  r  rm  rw   r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r*  rT  r  r@  r=  rg  rn  rr  ry  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r!  r  r(  r,  r   r8  r3  r  rO  rY  r[  r  r<   r  r  r   ro   rm   rf   rf     s        @ @D NNN
 %)#'*.15'+&O &O &O &O U&OP
 
 
 
    UB  "'"	>? >? >? >? U>?@    U2 OS& & & & U&P  .2" " " " U"P "'"( ( ( ( ( 
 
 
 U
4) ) ) )V ?C %G %G %G %G U%GN ?C % % % % U%T 9> cH cH cH cH cH cHJ 
 )-"+
 +
 +
 +
 U+
Z  #? #'? ? ? ? ? U?$-9 -9 -9 -9^   $"1 1 1 1 U1f( ( ( ( ( -1     U< "&d8 8 8 8 U8*    U6   U  $ $ $ $ U$P % % % X U% 9
 9
 9
 9
 U9
v :
 :
 :
 :
 U:
x e e e UeN  #4804dC dC dC dC UdCL a? a? a? a? Ua?F  4804"q q q q Uqf  4804"n n n n Un`  -1zD zD zD zD UzDx HLg
 g
 g
 g
 Ug
R _ _ _ U_B  #4804w w w w Uwr MQM
 M
 M
 M
 UM
^  #4804r r r r Urh  #4804r r r r Urh NRR
 R
 R
 R
 UR
h NRA
 A
 A
 A
 UA
F o o o Uof 	P P P P Pd 27uG uG uG uG uG UuGn  #'#,0\
 \
 \
 \
 U\
|  C
 C
 C
 C
 UC
J  !!37""#,0g
 g
 g
 g
 Ug
R I I I I UIV Y0 Y0 Y0 Y0 UY0v N0 N0 N0 N0 UN0` Q( Q( Q( X UQ(l 045 5 5 5 5n  #& "Z= Z= Z= Z= UZ=x P P P P UPd 6: 6: 6: 6: U6:p   W
 W
 W
 W
 UW
r =I =I =I =I U=I~ =H =H =H =H U=H~  #G
 G
 G
 G
 UG
R  #K
 K
 K
 K
 UK
Z  ()>!N
 N
 N
 N
 UN
`  W W W W UWr   	a& a& a& a& Ua&F %- %- %- %- U%-N ,- ,- ,- ,- U,-\ ( ( ( U($  !,0+/z@ z@ z@ z@ Uz@~ #("< < < < <|     ro   rf   Tr   rI   byr   r   r   r   r   rg   c                    t          | t                    rddlm}  || |||          S t          | t                    rddlm}  || |||          S t          d|            )r   r   )SeriesGroupBy)r   r   r   r   )DataFrameGroupByzinvalid type: )r   rT   pandas.core.groupby.genericr  rH   r  r  )r   r  r   r   r  r  s         rm   get_groupbyr    s    N #v 0======}!	
 
 
 	
 
C	#	# 
0@@@@@@!	
 
 
 	
 ...///ro   r6  rP   r=  npt.NDArray[np.float64]rQ   c                v  	 t          |          	t          |d                                          \  }}t          ||          }| j        rst          t          |           } g | j        |}	fd| j        D             t          j
        |t          |                     gz   }t          ||g | j        d          }nxt          |           }t          t          j        |          |           }| |g}t          j        |	          t          j
        ||          g}t          ||| j        d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
    Fr5  c                :    g | ]}t          j        |          S r   )r   rI  )r   r	  r  s     rm   rF  z*_insert_quantile_level.<locals>.<listcomp>  s%    666q1c""666ro   N)r  rP  r  )r   rP   	factorizer)   	_is_multir   rQ   r  rP  r   rD  r  r  rI  rz   )
r6  r=  	lev_codesrK  r  rP  minidx	idx_codesr  s
            @rm   rP  rP  t  s2    b''C2E***4466NIs$Y44I
} 
L:s###3:#s#6666CI666"')SQTXX:V:V9WWvU:LCI:Lt:LMMM3xx(4#>>	s9c**BGIt,D,DEvU38T:JKKKIro   )NNT)
r   rI   r  r   r   r   r   r   rg   rf   )r6  rP   r=  r  rg   rQ   )r   
__future__r   collections.abcr   r   r   r   r   r	   r   	functoolsr
   r   typingr   r   r   r   r   r   r   r   r   r   r   numpyr   pandas._libsr   r   pandas._libs.algosr   pandas._libs.groupby_libsre   r  pandas._libs.missingr   pandas._typingr   r   r   r   r   r   r    r!   r"   pandas.compat.numpyr#   r#  pandas.errorsr$   r%   r&   pandas.util._decoratorsr'   pandas.util._exceptionsr(   pandas.core.dtypes.castr)   r*   pandas.core.dtypes.commonr+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   pandas.core.dtypes.missingr8   r9   r:   pandas.corer;   r<   pandas.core._numbar=   pandas.core.arraysr>   r?   r@   rA   rB   rC   pandas.core.arrays.string_rD   pandas.core.arrays.string_arrowrE   pandas.core.baserF   rG   pandas.core.commoncorecommonr   pandas.core.framerH   pandas.core.genericrI   pandas.core.groupbyrJ   rK   rL   pandas.core.groupby.grouperrM   pandas.core.groupby.indexingrN   rO   pandas.core.indexes.apirP   rQ   rR   pandas.core.internals.blocksrS   pandas.core.seriesrT   pandas.core.sortingrU   pandas.core.util.numba_rV   rW   rX   pandas._libs.tslibsrY   pandas._libs.tslibs.timedeltasrZ   r[   r\   r]   pandas.core.indexers.objectsr^   r  r_   r  r`   ra   rb   #_groupby_agg_method_engine_template*_groupby_agg_method_skipna_engine_template_pipe_template_transform_templaterd   r   r   r   r   r   rf   r  rP  r   ro   rm   <module>r     s     # " " " " "                                                           ' & & & & & ) ) ) ) ) ) ) ) ) # # # # # #
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 / . . . . .         
 3 2 2 2 2 2 4 4 4 4 4 4                                                     ( ' ' ' ' '                3 2 2 2 2 2 < < < < < <        !                 ' ' ' ' ' ' ' ' ' ' ' '         
 4 3 3 3 3 3                
 < ; ; ; ; ; % % % % % % 6 6 6 6 6 6           ......888888          988888......         0' #d6. *p6p[ |     ,   4 
8nz8#$% 8XJ()*+ h !	"     ` ` ` ` `,x 8:N ` ` `H g37CCC nP nP nP nP nPk(# nP nP nPfa #&*	Z0 Z0 Z0 Z0 Z0z     ro   