
    Owg&%                        d dl mZ d dlmZ d dlmZmZmZ d dlZ	d dl
mZmZ d dlmZmZ erd dlmZ d dlmZmZ d d	lmZ  G d
 d      Z eej0                         G d d             Z G d d      Zy)    )annotations)Iterable)TYPE_CHECKINGLiteralcastN)cache_readonlydoc)
is_integeris_list_like)PositionalIndexer)	DataFrameSeries)groupbyc                  v    e Zd ZdZedd       Z	 	 	 	 ddZddZddZddZ	ddZ
edd       Zedd	       Zy
)GroupByIndexingMixinz<
    Mixin for adding ._positional_selector to GroupBy.
    c                r    t         r%t        t        j                  |       }t	        |      S | }t	        |      S )a
  
        Return positional selection for each group.

        ``groupby._positional_selector[i:j]`` is similar to
        ``groupby.apply(lambda x: x.iloc[i:j])``
        but much faster and preserves the original index and order.

        ``_positional_selector[]`` is compatible with and extends :meth:`~GroupBy.head`
        and :meth:`~GroupBy.tail`. For example:

        - ``head(5)``
        - ``_positional_selector[5:-5]``
        - ``tail(5)``

        together return all the rows.

        Allowed inputs for the index are:

        - An integer valued iterable, e.g. ``range(2, 4)``.
        - A comma separated list of integers and slices, e.g. ``5``, ``2, 4``, ``2:4``.

        The output format is the same as :meth:`~GroupBy.head` and
        :meth:`~GroupBy.tail`, namely
        a subset of the ``DataFrame`` or ``Series`` with the index and order preserved.

        Returns
        -------
        Series
            The filtered subset of the original Series.
        DataFrame
            The filtered subset of the original DataFrame.

        See Also
        --------
        DataFrame.iloc : Purely integer-location based indexing for selection by
            position.
        GroupBy.head : Return first n rows of each group.
        GroupBy.tail : Return last n rows of each group.
        GroupBy.nth : Take the nth row from each group if n is an int, or a
            subset of rows, if n is a list of ints.

        Notes
        -----
        - The slice step cannot be negative.
        - If the index specification results in overlaps, the item is not duplicated.
        - If the index specification changes the order of items, then
          they are returned in their original order.
          By contrast, ``DataFrame.iloc`` can change the row order.
        - ``groupby()`` parameters such as as_index and dropna are ignored.

        The differences between ``_positional_selector[]`` and :meth:`~GroupBy.nth`
        with ``as_index=False`` are:

        - Input to ``_positional_selector`` can include
          one or more slices whereas ``nth``
          just handles an integer or a list of integers.
        - ``_positional_selector`` can  accept a slice relative to the
          last row of each group.
        - ``_positional_selector`` does not have an equivalent to the
          ``nth()`` ``dropna`` parameter.

        Examples
        --------
        >>> df = pd.DataFrame([["a", 1], ["a", 2], ["a", 3], ["b", 4], ["b", 5]],
        ...                   columns=["A", "B"])
        >>> df.groupby("A")._positional_selector[1:2]
           A  B
        1  a  2
        4  b  5

        >>> df.groupby("A")._positional_selector[1, -1]
           A  B
        1  a  2
        2  a  3
        4  b  5
        )r   r   r   GroupByGroupByPositionalSelectorselfgroupby_selfs     S/var/www/horilla/myenv/lib/python3.12/site-packages/pandas/core/groupby/indexing.py_positional_selectorz)GroupByIndexingMixin._positional_selector%   s7    \ 6L )66  L(66    c                F   t        |      rgt        d t        t        |      D              r'| j	                  t        t        t
           |            }n| j                  t        t        |            }net        |t              r| j                  |      }nCt        |      r | j                  t        t
        |            }nt        dt        |       d      t        |t              r!|r| j                   dk\  }n| j                   dk  }t        t"        j$                  |      S )Nc              3  2   K   | ]  }t        |        y wN)r
   ).0is     r   	<genexpr>zJGroupByIndexingMixin._make_mask_from_positional_indexer.<locals>.<genexpr>   s     >Q:a=>s   zInvalid index zE. Must be integer, list-like, slice or a tuple of integers and slicesr   )r   allr   r   _make_mask_from_listint_make_mask_from_tupletuple
isinstanceslice_make_mask_from_slicer
   _make_mask_from_int	TypeErrortypebool_ascending_countnpndarrayr   argmasks      r   "_make_mask_from_positional_indexerz7GroupByIndexingMixin._make_mask_from_positional_indexer{   s     >$x*=>>00hsmS1IJ11$uc2BCU#--c2D_++DcN;D c ,& &  dD!,,1,,q0BJJ%%r   c                P    |dk\  r| j                   |k(  S | j                  | dz
  k(  S )Nr      )r-   _descending_count)r   r1   s     r   r)   z(GroupByIndexingMixin._make_mask_from_int   s1    !8((C//))sdQh77r   c                   |D cg c]
  }|dk\  s	| }}|D cg c]  }|dk  s	| dz
   }}d}|r#|t        j                  | j                  |      z  }|r#|t        j                  | j                  |      z  }|S c c}w c c}w )Nr   r5   F)r.   isinr-   r6   )r   argsr1   positivenegativer2   s         r   r"   z)GroupByIndexingMixin._make_mask_from_list   s    #'4C3!8C44(,8aSD1H88"'BGGD118<<DBGGD22H==D 58s   
A=A=
BBc                    d}|D ]l  }t        |      r#|| j                  t        t        |            z  }1t	        |t
              r|| j                  |      z  }Vt        dt        |       d       |S )NFzInvalid argument z. Should be int or slice.)	r
   r)   r   r#   r&   r'   r(   
ValueErrorr+   )r   r9   r2   r1   s       r   r$   z*GroupByIndexingMixin._make_mask_from_tuple   s|    "' 	C#00c3@@C'22377 'S	{2KL 	 r   c                l   |j                   }|j                  }|j                  }||dk  rt        d| d      d}|d}||dkD  r|| j                  |z  dk(  z  }n|dk\  r0|| j                  |k\  z  }|dkD  r|| j                  |z
  |z  dk(  z  }ns|| j
                  | k  z  }| j
                  |z   dz   }| j                  | j
                  z   |dz   z   dk  }t        j                  || j                  |      }|||z  dk(  z  }|,|dk\  r|| j                  |k  z  }|S || j
                  | k\  z  }|S )Nr   zInvalid step z. Must be non-negativeTr5   )startstopstepr=   r-   r6   r.   where)r   r1   r?   r@   rA   r2   offset_arraylimit_arrays           r   r(   z*GroupByIndexingMixin._make_mask_from_slice   s   		xxxxq}TF2HIJJ"&<D=ax--499aZD))U22Dax..6$>!CC D**eV33D11E9A=L%%(>(>>%!)LK 88K1F1FULL4'1,,Dqy--44  ..4%77r   c                    t         r*t        t        j                  |       }|j	                         S | }|j	                         S r   r   r   r   r   _cumcount_arrayr   s     r   r-   z%GroupByIndexingMixin._ascending_count   s<    6L ++--  L++--r   c                l    t         rt        t        j                  |       }n| }|j	                  d      S )NF)	ascendingrF   r   s     r   r6   z&GroupByIndexingMixin._descending_count   s.    6LL++e+<<r   N)returnr   )r1   PositionalIndexer | tuplerJ   
np.ndarray)r1   r#   rJ   rL   )r9   zIterable[int]rJ   bool | np.ndarray)r9   r%   rJ   rM   )r1   r'   rJ   rM   )rJ   rL   )__name__
__module____qualname____doc__r   r   r3   r)   r"   r$   r(   r-   r6    r   r   r   r       sr     S7 S7j&&& 
&:8(T . . = =r   r   c                      e Zd ZddZddZy)r   c                    || _         y r   groupby_objectr   rV   s     r   __init__z"GroupByPositionalSelector.__init__   
    ,r   c                n    | j                   j                  |      }| j                   j                  |      S )a  
        Select by positional index per group.

        Implements GroupBy._positional_selector

        Parameters
        ----------
        arg : PositionalIndexer | tuple
            Allowed values are:
            - int
            - int valued iterable such as list or range
            - slice with step either None or positive
            - tuple of integers and slices

        Returns
        -------
        Series
            The filtered subset of the original groupby Series.
        DataFrame
            The filtered subset of the original groupby DataFrame.

        See Also
        --------
        DataFrame.iloc : Integer-location based indexing for selection by position.
        GroupBy.head : Return first n rows of each group.
        GroupBy.tail : Return last n rows of each group.
        GroupBy._positional_selector : Return positional selection for each group.
        GroupBy.nth : Take the nth row from each group if n is an int, or a
            subset of rows, if n is a list of ints.
        )rV   r3   _mask_selected_objr0   s      r   __getitem__z%GroupByPositionalSelector.__getitem__   s1    > ""EEcJ""55d;;r   NrV   zgroupby.GroupByrJ   None)r1   rK   rJ   DataFrame | Series)rN   rO   rP   rX   r\   rR   r   r   r   r      s    - <r   r   c                  6    e Zd ZdZddZ	 d	 	 	 	 	 ddZd	dZy)
GroupByNthSelectorzO
    Dynamically substituted for GroupBy.nth to enable both call and index
    c                    || _         y r   rU   rW   s     r   rX   zGroupByNthSelector.__init__%  rY   r   Nc                :    | j                   j                  ||      S r   rV   _nth)r   ndropnas      r   __call__zGroupByNthSelector.__call__(  s    
 ""''622r   c                8    | j                   j                  |      S r   rd   )r   rf   s     r   r\   zGroupByNthSelector.__getitem__/  s    ""''**r   r]   r   )rf   rK   rg   zLiteral['any', 'all', None]rJ   r_   )rf   rK   rJ   r_   )rN   rO   rP   rQ   rX   rh   r\   rR   r   r   ra   ra      s7    - /33$3 ,3 
	3+r   ra   )
__future__r   collections.abcr   typingr   r   r   numpyr.   pandas.util._decoratorsr   r	   pandas.core.dtypes.commonr
   r   pandas._typingr   pandasr   r   pandas.core.groupbyr   r   r   r   ra   rR   r   r   <module>rs      ss    " $  

 0 ,U= U=p ../$< $< 0$<N+ +r   