
    Pi                   f   U d dl mZ d dlZd dlmZ d dlmZ d dlZd dlmZ d dl	Z	d dl
mZmZmZmZmZ d dl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 d d	lmZ d d
lm Z  d dl!m"Z"m#Z# d dl$m%Z% d dl&m'Z'm(Z(m)Z)m*Z*m+Z+ d dl,m-Z- d dl.m/Z/m0Z0m1Z1 d dl2m3Z3 d dl4m5c m6Z7 d dl8m9Z9 d dl:m;Z;m<Z< er*d dlm=Z=m>Z>m?Z?m@Z@mAZA d dlBmCZCmDZDmEZE d dlFmGZG d dlHmIZI d dlJmKZK eLeMef         ZNdeOd<    e#d           G d dejP                              ZQ	 	 	 	 	 	 	 	 dedfd2ZR G d3 d4ejS        5          ZT G d6 d7eT          ZU G d8 d1eU          ZV G d9 d:eV          ZW G d; d<eV          ZX G d= d>eU          ZY G d? d@eT          ZZ G dA dBeZ          Z[dgdEZ\dhdFZ]didJZ^djdMZ_dkdVZ`dldWZadmdZZbdnd]Zcdod_ZddpddZedS )q    )annotationsN)defaultdict)Callable)partial)TYPE_CHECKINGAnyLiteral	TypeAliascast)BlockValuesRefs)AggFuncTypeAggFuncTypeBaseAggFuncTypeDict
AggObjTypeAxisAxisIntNDFrameTnpt)import_optional_dependency)SpecificationError)cache_readonly
set_module)is_nested_object)is_dict_likeis_extension_array_dtypeis_list_likeis_numeric_dtypeis_sequence)ExtensionDtype)ABCDataFrame
ABCNDFrame	ABCSeries)generate_apply_looper)ensure_wrapped_if_datetimelike)get_jit_argumentsprepare_function_arguments)	GeneratorHashableIterableMutableMappingSequence)	DataFrameIndexSeries)GroupBy)	Resampler)
BaseWindowr
   ResTypezpandas.api.executorsc                  v    e Zd ZdZeej        dd                        Zeej        dd                        ZdS )BaseExecutionEnginea  
    Base class for execution engines for map and apply methods.

    An execution engine receives all the parameters of a call to
    ``apply`` or ``map``, such as the data container, the function,
    etc. and takes care of running the execution.

    Supporting different engines allows functions to be JIT compiled,
    run in parallel, and others. Besides the default executor which
    simply runs the code with the Python interpreter and pandas.
    dataSeries | DataFrame | np.ndarrayfuncr   argstuplekwargsdict[str, Any]	decoratorCallable | Noneskip_naboolc                    dS )a  
        Executor method to run functions elementwise.

        In general, pandas uses ``map`` for running functions elementwise,
        but ``Series.apply`` with the default ``by_row='compat'`` will also
        call this executor function.

        Parameters
        ----------
        data : Series, DataFrame or NumPy ndarray
            The object to use for the data. Some methods implement a ``raw``
            parameter which will convert the original pandas object to a
            NumPy array, which will then be passed here to the executor.
        func : function or NumPy ufunc
            The function to execute.
        args : tuple
            Positional arguments to be passed to ``func``.
        kwargs : dict
            Keyword arguments to be passed to ``func``.
        decorator : function, optional
            For JIT compilers and other engines that need to decorate the
            function ``func``, this is the decorator to use. While the
            executor may already know which is the decorator to use, this
            is useful as for a single executor the user can specify for
            example ``numba.jit`` or ``numba.njit(nogil=True)``, and this
            decorator parameter will contain the exact decorator from the
            executor the user wants to use.
        skip_na : bool
            Whether the function should be called for missing values or not.
            This is specified by the pandas user as ``map(na_action=None)``
            or ``map(na_action='ignore')``.
        N )r5   r7   r8   r:   r<   r>   s         e/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/pandas/core/apply.pymapzBaseExecutionEngine.map_             r   axisr   c                    dS )a_  
        Executor method to run functions by an axis.

        While we can see ``map`` as executing the function for each cell
        in a ``DataFrame`` (or ``Series``), ``apply`` will execute the
        function for each column (or row).

        Parameters
        ----------
        data : Series, DataFrame or NumPy ndarray
            The object to use for the data. Some methods implement a ``raw``
            parameter which will convert the original pandas object to a
            NumPy array, which will then be passed here to the executor.
        func : function or NumPy ufunc
            The function to execute.
        args : tuple
            Positional arguments to be passed to ``func``.
        kwargs : dict
            Keyword arguments to be passed to ``func``.
        decorator : function, optional
            For JIT compilers and other engines that need to decorate the
            function ``func``, this is the decorator to use. While the
            executor may already know which is the decorator to use, this
            is useful as for a single executor the user can specify for
            example ``numba.jit`` or ``numba.njit(nogil=True)``, and this
            decorator parameter will contain the exact decorator from the
            executor the user wants to use.
        axis : {0 or 'index', 1 or 'columns'}
            0 or 'index' should execute the function passing each column as
            parameter. 1 or 'columns' should execute the function passing
            each row as parameter. The default executor engine passes rows
            as pandas ``Series``. Other executor engines should probably
            expect functions to be implemented this way for compatibility.
            But passing rows as other data structures is technically possible
            as far as the function ``func`` is implemented accordingly.
        NrA   )r5   r7   r8   r:   r<   rF   s         rB   applyzBaseExecutionEngine.apply   rD   rE   N)r5   r6   r7   r   r8   r9   r:   r;   r<   r=   r>   r?   )r5   r6   r7   r   r8   r9   r:   r;   r<   r   rF   r   )	__name__
__module____qualname____doc__staticmethodabcabstractmethodrC   rH   rA   rE   rB   r4   r4   Q   s{        
 
 ' ' '  \'R + + +  \+ + +rE   r4   Fcompatpythonobjr,   r7   r   rF   r   rawr?   result_type
str | Noneby_rowLiteral[False, 'compat']enginestrengine_kwargsdict[str, bool] | Nonereturn
FrameApplyc
                    t          |fi |	\  }
}}}
|                     |          }|dk    rt          }n"|dk    r|rt          d|d          t          } || ||||||||		  	        S )z=construct and return a row or column based frame apply objectr      z-Named aggregation is not supported when axis=.)rS   rT   rV   rX   rZ   r8   r:   )reconstruct_func_get_axis_numberFrameRowApplyNotImplementedErrorFrameColumnApply)rR   r7   rF   rS   rT   rV   rX   rZ   r8   r:   _columnsklasss                rB   frame_applyri      s     +4::6::AtWa%%Dqyy	 	%C4CCC   !5#
 
 
 
rE   c                     e Zd ZU ded<   ddddd@dZej        dAd            Zej        dBd            Zej        dBd            Z	dCdZ
dAd ZdDd"ZdAd#ZdAd$ZdEd*ZdFd/ZdAd0ZdGd4ZdHd9ZdAd:ZdAd;ZdId>ZdJd?ZdS )KApplyr   rF   rP   rQ   NrV   rX   rZ   rR   r   r7   r   rS   r?   rT   rU   rV   #Literal[False, 'compat', '_compat']rX   rY   rZ   r[   r\   Nonec                   || _         || _        |du s|dv sJ || _        |pd| _        |	pi | _        || _        |i n|| _        |dvrt          d          || _        || _	        d S )NF)rP   _compatrA   )Nreduce	broadcastexpandzUinvalid value for result_type, must be one of {None, 'reduce', 'broadcast', 'expand'})
rR   rS   rV   r8   r:   rX   rZ   
ValueErrorrT   r7   )
selfrR   r7   rS   rT   rV   rX   rZ   r8   r:   s
             rB   __init__zApply.__init__   s     &,A"A"A"AAJB	l#0#8RRmEEE=  
 '			rE   DataFrame | Seriesc                    d S NrA   ru   s    rB   rH   zApply.apply      rE   op_nameLiteral['agg', 'apply']c                    d S ry   rA   ru   r|   s     rB   agg_or_apply_list_likezApply.agg_or_apply_list_like  	     	rE   c                    d S ry   rA   r   s     rB   agg_or_apply_dict_likezApply.agg_or_apply_dict_like  r   rE   DataFrame | Series | Nonec                    | j         }t          |t                    r|                                 S t	          |          r|                                 S t          |          r|                                 S dS )z
        Provide an implementation for the aggregators.

        Returns
        -------
        Result of aggregation, or None if agg cannot be performed by
        this method.
        N)r7   
isinstancerY   	apply_strr   agg_dict_liker   agg_list_like)ru   r7   s     rB   aggz	Apply.agg  sx     ydC   	$>>### 	(%%'''$ 	(%%''' trE   c                   | j         }| j        }| j        }| j        }| j        }|j        dk    }|                    |          dk    r |rJ  |j        j        |dg|R i |j        S t          |          rYt          |          sJt          t          t                   |          }|rd |D             }nt                              ||          }t          |          r*t          t           |          }|                     |          S t          t          |          }	 |                     |          }n,# t&          $ r  t(          $ r}t+          d          |d}~ww xY wt-          |t.          t0          f          r|j        r|j        st+          d          t-          |t.          t0          f          r|j                            |j                  st+          d          |S )aI  
        Transform a DataFrame or Series.

        Returns
        -------
        DataFrame or Series
            Result of applying ``func`` along the given axis of the
            Series or DataFrame.

        Raises
        ------
        ValueError
            If the transform function fails or does not transform.
        r_   r   c                <    i | ]}t          j        |          p||S rA   comget_callable_name.0vs     rB   
<dictcomp>z#Apply.transform.<locals>.<dictcomp>M  s*    GGGQ-a005AqGGGrE   zTransform function failedNzFunction did not transform)rR   r7   rF   r8   r:   ndimrb   T	transformr   r   r   listr   dictfromkeysr   transform_dict_liketransform_str_or_callable	TypeError	Exceptionrt   r   r"   r    emptyindexequals)	ru   rR   r7   rF   r8   r:   	is_seriesresulterrs	            rB   r   zApply.transform.  s    hyyyHM	%%**   ="35?4<T<<<V<<>> 	0l4&8&8 	0_-t44D 0GG$GGG}}S$// 	2..D++D111 OT**	C33D99FF 	 	 	 	C 	C 	C899sB	C v	<899	:	: I	:
 8999&9l";<< 	;FLDWDWIE
 E
 	; 9:::s   D5 5E	EEr,   c                   ddl m} | j        }| j        }| j        }t          |t                    sJ t          |          dk    rt          d          | 	                    d||          }i }|
                                D ]1\  }}|                    |d          }	 |	j        |dg|R i |||<   2 ||d          S )zC
        Compute transform in the case of a dict-like func
        r   concatz$No transform functions were providedr   r_   r   rF   )pandas.core.reshape.concatr   rR   r8   r:   r   r!   lenrt   normalize_dictlike_argitems_gotitemr   )
ru   r7   r   rR   r8   r:   resultsnamehowcolgs
             rB   r   zApply.transform_dict_likem  s     	655555hy #z*****t99>>CDDD**;TBB68 	D 	DID#<<1<--D*DN3CDCCCFCCGDMMvgA&&&&rE   c                    | j         }| j        }| j        }t          |t                    r | j        ||g|R i |S 	  |j        |fd|i|S # t          $ r  ||g|R i |cY S w xY w)zL
        Compute transform in the case of a string or callable func
        r8   )rR   r8   r:   r   rY   
_apply_strrH   r   )ru   r7   rR   r8   r:   s        rB   r   zApply.transform_str_or_callable  s     hydC   	?"4?3>t>>>v>>>	.39T777777 	. 	. 	.4-d---f-----	.s   A A'&A'c                .    |                      d          S )z
        Compute aggregation in the case of a list-like argument.

        Returns
        -------
        Result of aggregation.
        r   r|   )r   rz   s    rB   r   zApply.agg_list_like       **5*999rE   selected_objSeries | DataFramer:   r;   (tuple[list[Hashable] | Index, list[Any]]c                J   t          t          t                   | j                  }| j        }g }g }|j        dk    r|D ]}|                    |j        d|          }	t          ||	          r| j	        g| j
        n| j
        }
 t          |	|          |g|
R i |}|                    |           t          j        |          p|}|                    |           ng }t          |          D ]\  }}|                    |d|j        dd|f                   }	t          ||	          r| j	        g| j
        n| j
        }
 t          |	|          |g|
R i |}|                    |           |                    |           |j                            |          }||fS )aF  
        Compute agg/apply results for like-like input.

        Parameters
        ----------
        op_name : {"agg", "apply"}
            Operation being performed.
        selected_obj : Series or DataFrame
            Data to perform operation on.
        kwargs : dict
            Keyword arguments to pass to the functions.

        Returns
        -------
        keys : list[Hashable] or Index
            Index labels for result.
        results : list
            Data for result. When aggregating with a Series, this can contain any
            Python objects.
        r_   r   subsetN)r   r   r   r7   rR   r   r   r   include_axisrF   r8   getattrappendr   r   	enumerateilocrg   take)ru   r|   r   r:   r7   rR   r   keysar   r8   new_resr   indicesr   cols                   rB   compute_list_likezApply.compute_list_like  s   4 D)4955h !! " "||L$5Al|SS $GT22#TY+++ 
 1'$00DTDDDVDDw''' ,Q//41D!!!!" G'55 	& 	&
s||Ca8I!!!U(8S|TT $GT22#TY+++ 
 1'$00GGGGGGw'''u%%%%  ',,W55DW}rE   r   Iterable[Hashable]r   list[Series | DataFrame]c                    ddl m} | j        }	  |||dd          S # t          $ rD}ddlm}  ||||j                  }t          |          rt          d          ||cY d }~S d }~ww xY w)	Nr   r   r_   F)r   rF   sortr.   r   r   z3cannot combine transform and aggregation operations)	r   r   rR   r   pandasr.   r   r   rt   )ru   r   r   r   rR   r   r.   r   s           rB   wrap_results_list_likezApply.wrap_results_list_like  s     	655555h	6'15AAAA 
	 
	 
	 &%%%%%VG4ch???F''  I  MMMMMM
	s    
A,9A'!A,'A,c                .    |                      d          S )z
        Compute aggregation in the case of a dict-like argument.

        Returns
        -------
        Result of aggregation.
        r   r   )r   rz   s    rB   r   zApply.agg_dict_like  r   rE   	selectionHashable | Sequence[Hashable] tuple[list[Hashable], list[Any]]c           	     <   ddl m}m} | j        t	          ||f          }t          t          | j                  }|                     |          }j	        dk    o.j
                                        t          j
                  k     }	j	        dk    r\                    |d          fd|                                D             }
t          |                                          }n |s|	rg }
g }|                                D ]\  }j
                            |g          }j
                            |          }t'          t                    }t)          ||d          D ] \  }}||                             |           !fd	|                                D             }||gt          |          z  z  }|
|z  }
nB|r}g g }}
|                                D ]\  }||         }|j	        dk    rX                    |d|
          }|
                     t-          |          fi            |                    |           p|                                D ]\\  }}                    |d|
          }|
                     t-          |          fi            |                    |           ]nCfd|                                D             }
t          |                                          }||
fS )a  
        Compute agg/apply results for dict-like input.

        Parameters
        ----------
        op_name : {"agg", "apply"}
            Operation being performed.
        selected_obj : Series or DataFrame
            Data to perform operation on.
        selection : hashable or sequence of hashables
            Used by GroupBy, Window, and Resample if selection is applied to the object.
        kwargs : dict
            Keyword arguments to pass to the functions.

        Returns
        -------
        keys : list[hashable]
            Index labels for result.
        results : list
            Data for result. When aggregating with a Series, this can contain any
            Python object.
        r   DataFrameGroupBySeriesGroupBy   r_   r   c                D    g | ]\  }} t                    |fi S rA   )r   )r   rf   r   r   r:   r|   s      rB   
<listcomp>z+Apply.compute_dict_like.<locals>.<listcomp>0  s:    XXXC-wtW--c<<V<<XXXrE   Tstrictc           
     x    g | ]6\  }}|D ].} t                              |d                     fi /7S )r_   r   )r   _ixs)r   labelr   indicer   r:   r|   r   s       rB   r   z+Apply.compute_dict_like.<locals>.<listcomp>>  st       &w")   HGL--f1-==wGGVVvVV   rE   r   c           	     n    g | ]1\  }} t                              |d                     |fi 2S )r_   r   )r   r   )r   keyr   r:   rR   r|   s      rB   r   z+Apply.compute_dict_like.<locals>.<listcomp>X  sY       C <Sq117;;CJJ6JJ  rE   )pandas.core.groupby.genericr   r   rR   r   r   r   r7   r   r   rg   nuniquer   r   r   r   r   get_indexer_forr   r   zipr   r   )ru   r|   r   r   r:   r   r   
is_groupbyr7   is_non_unique_colr   r   r   r   labelslabel_to_indicesr   r   key_datadfcolsseriesrf   r   r   r   rR   s    `` `                   @@@rB   compute_dict_likezApply.compute_dict_like  s   :	
 	
 	
 	
 	
 	
 	
 	

 h&6%FGG
OTY//**7L$GG " K$,,..\5I1J1JJ 	
 !!<<	<22DXXXXXX4::<<XXXG		$$DD *	% 1 *	% GD JJLL $ $S&.>>uEE%-227;;#.t#4#4 $'$E$E$E : :LE5$U+2259999      *:*@*@*B*B   H--8#$  	% BTG JJLL ) )S#w9>> \\#Ad\CCFNN#;767#;#;C#J#J6#J#JKKKKK$$$$"&**,, ) )3!$c#!F!F'?wvw'?'?'N'Nv'N'NOOOC(((())      $

  G 		$$DW}rE   result_indexlist[Hashable]result_datar   c                4   ddl m} ddlm} | j        }d |D             }t          |          rd |D             }d t          ||d          D             }	|	g k    r|}	|}|j        d	k    r, ||	          }
|
                    |j	        j
                   |
}	t          |t                    rdnd
} ||||	d          }nWt          |          rt          d          ddl m} |j        d
k    rt!          d|          }|j        }nd } ||||          }|S )Nr   r-   r   c                8    g | ]}t          |t                    S rA   )r   r!   )r   rs     rB   r   z0Apply.wrap_results_dict_like.<locals>.<listcomp>l  s"    EEEAjJ//EEErE   c                     g | ]}|j         	|S rA   r   )r   r   s     rB   r   z0Apply.wrap_results_dict_like.<locals>.<listcomp>o  s    LLL&v|LvLLLrE   c                &    g | ]\  }}|j         |S rA   r   )r   kr   s      rB   r   z0Apply.wrap_results_dict_like.<locals>.<listcomp>q  s5       aQRQX  rE   Tr   r   r_   F)rF   r   r   zLcannot perform both aggregation and transformation operations simultaneouslyr   r.   r   )r   r-   r   r   rR   allr   r   
_set_namesrg   namesr   r"   anyrt   r.   r   r   )ru   r   r   r   r-   r   rR   
is_ndframer   keys_to_usekturF   r   r.   r   s                  rB   wrap_results_dict_likezApply.wrap_results_dict_like`  s    	!     555555h FEEEE
z?? *	HLLKLLLG !,DIII  K b  *% A%%eK((|39:::!!+C!;!;BAADV 	  FF __ 	H!   &%%%%% x1}}8S))xVK|$GGGFrE   c                   t          t          | j                  }| j        }ddlm}m} t          ||d          }t          |          rpt          j
        |          }g |j        |j        R }| j        dk    rd|vs|dv rt          d| d          d|v r!t          |||f          s| j        | j        d<    | j        ||g| j        R i | j        S )zy
        Compute apply in case of a string.

        Returns
        -------
        result: Series or DataFrame
        r   r   NrF   )corrwithskewz
Operation z does not support axis=1)r   rY   r7   rR   r   r   r   r   callableinspectgetfullargspecr8   
kwonlyargsrF   rt   r   r:   r   )ru   r7   rR   r   r   methodsig	arg_namess           rB   r   zApply.apply_str  s%    C##h	
 	
 	
 	
 	
 	
 	
 	
 dD))F 
	0(00C4#(4S^44IyA~~i''43G+G+G !Ld!L!L!LMMM"":m%56, ," '+iF#tsDD49DDDDDDrE   c                   | j         dk    rt          d          | j        dk    rIt          | j        t
                    r/ | j        j        j        | j        dfd| j	        i| j
        j        S | j        }| j
        }t          |          r|                     d          }n|                     d          }t          ||fi |}|S )z
        Compute apply in case of a list-like or dict-like.

        Returns
        -------
        result: Series, DataFrame, or None
            Result when self.func is a list-like or dict-like, None otherwise.
        numbazIThe 'numba' engine doesn't support list-like/dict likes of callables yet.r_   r   r8   rH   r   )rX   rd   rF   r   rR   r    r   rH   r7   r8   r:   r   r   r   reconstruct_and_relabel_result)ru   r7   r:   r   s       rB   apply_list_or_dict_likezApply.apply_list_or_dict_like  s     ;'!!%/  
 9>>j<@@>#48:#DIqPPtyPDKPPRRy 	B000AAFF000AAF/GGGGrE   r   r   c                  	 |dv sJ |dk    r@t          |t                    r+t          d |                                D                       s+t          d |                                D                       rt	          d          |j        dk    r}ddlm}  |t          |	                                                    
                    |j        d	
          }t          |          dk    r t          dt          |           d          t          t          t          f	t          	fd|                                D                       r:i }|                                D ]!\  }}t          |	          s|g||<   |||<   "|}|S )a  
        Handler for dict-like argument.

        Ensures that necessary columns exist if obj is a DataFrame, and
        that a nested renamer is not passed. Also normalizes to all lists
        when values consists of a mix of list and non-lists.
        )rH   r   r   r   c              3  :   K   | ]\  }}t          |          V  d S ry   )r   r   rf   r   s      rB   	<genexpr>z/Apply.normalize_dictlike_arg.<locals>.<genexpr>  s,      ==1LOO======rE   c              3  :   K   | ]\  }}t          |          V  d S ry   )r   r  s      rB   r  z/Apply.normalize_dictlike_arg.<locals>.<genexpr>  s,      ;;da,q//;;;;;;rE   znested renamer is not supportedr_   r   r   T)r   z	Label(s) z do not existc              3  >   K   | ]\  }}t          |          V  d S ry   r   )r   rf   xaggregator_typess      rB   r  z/Apply.normalize_dictlike_arg.<locals>.<genexpr>  s2      HH41az!-..HHHHHHrE   )r   r"   r   r   r   r   r   r-   r   r   
differencerg   r   KeyErrorr9   r   )
ru   r   rR   r7   r-   r   new_funcr   r   r  s
            @rB   r   zApply.normalize_dictlike_arg  s    33333 5LL3	** ==

=====  ;;djjll;;;;; 
 %%FGGG8q==$$$$$$5diikk**++66s{6NND4yy1}}D4::DDDEEE %. HHHH4::<<HHHHH 	(*H

 $ $1!!%566 $#$#HQKK"#HQKKDrE   c                   t          |t                    sJ t          ||          rYt          ||          }t	          |          r ||i |S t          |          dk    sJ t          d |D                       rJ |S t          t          |          r1t          |d          r!t          t          |          } ||g|R i |S d| dt          |          j	         d}t          |          )z
        if arg is a string, then try to operate on it:
        - try to find a function (or attribute) on obj
        - try to find a numpy function
        - raise
        r   c              3  "   K   | ]
}|d k    V  dS )rF   NrA   )r   kwargs     rB   r  z#Apply._apply_str.<locals>.<genexpr>  s&      ??u5F???????rE   	__array__'z' is not a valid function for 'z' object)r   rY   hasattrr   r  r   r   nptyperI   AttributeError)ru   rR   r7   r8   r:   fmsgs          rB   r   zApply._apply_str  s    $$$$$$3 	&T""A{{ *q$)&))) t99>>>>??????????HR 	&73#<#< 	&D!!A1S*4***6***WdWW499;MWWWC %%%rE   )rR   r   r7   r   rS   r?   rT   rU   rV   rm   rX   rY   rZ   r[   r\   rn   r\   rw   r|   r}   r\   rw   )r\   r   )r\   r,   )r|   r}   r   r   r:   r;   r\   r   )r   r   r   r   )
r|   r}   r   r   r   r   r:   r;   r\   r   )r   r   r   r   r   r   )r   rY   rR   rw   r7   r   r\   r   )r7   rY   )rI   rJ   rK   __annotations__rv   rN   rO   rH   r   r   r   r   r   r   r   r   r   r   r   r  r   r  r   r   rA   rE   rB   rk   rk      s        MMM 7?04! ! ! ! ! !F 	    	   
 	   
   .= = = =~' ' ' '0. . . .": : : :@ @ @ @D   *: : : :] ] ] ]~: : : :x!E !E !E !EF   >, , , ,\& & & & & &rE   rk   )	metaclassc                  ^    e Zd ZU dZded<   edd            Zedd            Zdd
ZddZ	dS )NDFrameApplyzg
    Methods shared by FrameApply and SeriesApply but
    not GroupByApply or ResamplerWindowApply
    rw   rR   r\   r-   c                    | j         j        S ry   )rR   r   rz   s    rB   r   zNDFrameApply.index0  s    x~rE   c                @    | j                             | j                  S ry   )rR   _get_agg_axisrF   rz   s    rB   agg_axiszNDFrameApply.agg_axis4  s    x%%di000rE   r|   r}   c                f   | j         }| j        }|dk    rHt          | t                    r| j        }n#t          | t
                    r| j        rdnd}nd}i |d|i}t          |dd          dk    rt          d          |                     |||          \  }}| 	                    ||          }|S )	NrH   rp   FrV   rF   r   r_   "axis other than 0 is not supported)
rR   r:   r   r]   rV   SeriesApplyr   rd   r   r   )ru   r|   rR   r:   rV   r   r   r   s           rB   r   z#NDFrameApply.agg_or_apply_list_like8  s     hg$
++ D+.. &*k<u11&11F3""a''%&JKKK..wVDDg,,T7;;rE   c                $   |dv sJ | j         }i }|dk    r"| j        rdnd}|                    d|i           t          |dd          dk    rt	          d	          d }|                     ||||          \  }}|                     |||          }|S )
Nr   rH   rH   rp   FrV   rF   r   r_   r4  )rR   rV   updater   rd   r   r  )	ru   r|   rR   r:   rV   r   r   r   r   s	            rB   r   z#NDFrameApply.agg_or_apply_dict_likeO  s     *****hg"&+8YY5FMM8V,---3""a''%&JKKK	$($:$:S)V%
 %
!k ,,S,LLrE   Nr\   r-   r*  )
rI   rJ   rK   rL   r+  propertyr   r2  r   r   rA   rE   rB   r.  r.  (  s          
    X 1 1 1 X1   .     rE   r.  c                      e Zd ZU ded<   ddddd5 fdZeej        d6d                        Zeej        d6d                        Z	eej        d7d                        Z
eej        ej        	 d8d9d                                    Zej        d             Zd:d Zej        d;d%            Zed6d&            Zed6d'            Zed(             Zd<d)Z fd*Zd+ Zd=d,Zd>d.Zd/ Zd?d1Zd2 Zd;d3Zd< fd4Z xZ S )@r]   r,   rR   FrQ   Nrl   r   r7   r   rS   r?   rT   rU   rV   rW   rX   rY   rZ   r[   r\   rn   c                   |dur|dk    rt          d| d          t                                          |||||||||		  	         d S )NFrP   zby_row=z not allowed)rV   rX   rZ   r8   r:   )rt   superrv   )ru   rR   r7   rS   rT   rV   rX   rZ   r8   r:   	__class__s             rB   rv   zFrameApply.__init__h  sz     6X#5#5;v;;;<<<' 	 
	
 
	
 
	
 
	
 
	
rE   r-   c                    d S ry   rA   rz   s    rB   r   zFrameApply.result_index  	     	rE   c                    d S ry   rA   rz   s    rB   result_columnszFrameApply.result_columns  r@  rE   Generator[Series]c                    d S ry   rA   rz   s    rB   series_generatorzFrameApply.series_generator  r@  rE   T5Callable[[npt.NDArray, Index, Index], dict[int, Any]]c                    d S ry   rA   )r7   nogilnopythonparallels       rB   generate_numba_apply_funcz$FrameApply.generate_numba_apply_func  s	     	rE   c                    d S ry   rA   rz   s    rB   apply_with_numbazFrameApply.apply_with_numba  r{   rE   c                    | j         j                                        D ]L\  }}t          |          st	          d| d| d          t          |          rt	          d| d          Md S )NzColumn z# must have a numeric dtype. Found 'z	' insteadzM is backed by an extension array, which is not supported by the numba engine.)rR   dtypesr   r   rt   r   )ru   colnamedtypes      rB   validate_values_for_numbaz$FrameApply.validate_values_for_numba  s    "ho3355 
	 
	NGU#E**  /g / /#/ / /   (..  Cg C C C  
	 
	rE   r   r2   	res_indexrw   c                    d S ry   rA   ru   r   rS  s      rB   wrap_results_for_axisz FrameApply.wrap_results_for_axis  r   rE   c                    | j         S ry   )rB  rz   s    rB   res_columnszFrameApply.res_columns  s    ""rE   c                    | j         j        S ry   )rR   rg   rz   s    rB   rg   zFrameApply.columns  s    xrE   c                    | j         j        S ry   )rR   valuesrz   s    rB   r[  zFrameApply.values  s    xrE   c                H   t          | j                  r.| j        dk    rt          d          |                                 S t          | j                  dk    r,t          | j                  dk    r|                                 S t          | j        t                    r.| j        dk    rt          d          |                                 S t          | j        t          j                  r| j        dk    rt          d          t          j        d          5  | j        j                            d| j        	          }d
d
d
           n# 1 swxY w Y   | j                            ||j                  S | j        dk    r4| j        dk    rt          d          |                     | j                  S t-          | j        j                  s|                                 S | j        r!|                     | j        | j                  S |                                 S )zcompute the resultsr  z9the 'numba' engine doesn't support lists of callables yetr   zJthe 'numba' engine doesn't support using a string as the callable functionzOthe 'numba' engine doesn't support using a numpy ufunc as the callable functionignorer   rH   )r7   N)axesrr   z:the 'numba' engine doesn't support result_type='broadcast'rX   rZ   )r   r7   rX   rd   r  r   rg   r   apply_empty_resultr   rY   r   r$  ufuncerrstaterR   _mgrrH   _constructor_from_mgrr_  rT   apply_broadcastr   shaperS   	apply_rawrZ   apply_standardru   r   s     rB   rH   zFrameApply.apply  sw    	"" 	2{g%%)O   //111 t|!!c$*oo&:&:**,,, di%% 	N{g%%)8   >>### 	28,, 		N{g%%)C   *** G G(---gDI-FFG G G G G G G G G G G G G G G 811'1MMM {**{g%%)P   ''111 TX^$$ 	X**,,, X 	X>>DDV>WWW""$$$s   'EEEc                r   | j         }| j        }| j        dk    r| j         n| j         j        | _         d| _        d }	 t                                                      }|| _         || _        n# || _         || _        w xY w|dk    r||j        n|}|% | j         j        | j        |fd| j        i| j        }|S )Nr   r_   r8   )	rR   rF   r   r=  r   rH   r7   r8   r:   )ru   rR   rF   r   r>  s       rB   r   zFrameApply.agg  s    hy  $yA~~48848:		WW[[]]FDHDII DHDI199!'!3VXXF>#TX^DItSS$)St{SSFs    A, ,A<c                   t          | j                  sJ | j        dvr| j                                        S | j        dk    }ddlm} |s	 | j        dk    r1 | j         |g t          j	                  g| j
        R i | j        }n5 | j         || j        t          j	                  g| j
        R i | j        }t          ||           }n# t          $ r Y nw xY w|rrt          | j                  r1 | j         |g t          j	                  g| j
        R i | j        }nt          j        }| j                            || j                  S | j                                        S )z
        we have an empty result; at least 1 axis is 0

        we will try to apply the function to an empty
        series in order to see if this is a reduction function
        )rq   Nrq   r   r   rQ  )r   rQ  r   )r  r7   rT   rR   copyr   r.   rF   r$  float64r8   r:   rg   r   r   r   r2  nan_constructor_sliced)ru   should_reducer.   r   s       rB   ra  zFrameApply.apply_empty_result  s    	""""" #3338==??" (H4!!!!!! 	::9>>!	r4447;y  DHK AA "	T\DDD   + A %/q&$9$9 9    
  	#4=!! DIffRrz:::VTYVVV$+VVF8///GGG8==??"s   A1C 
CCc                   d }|dk    rmt          | j        | j        | j        d          \  }}t	          | j        fi t          |          } || j        | j        g|R  }t          j	        |          }n9t          j
         || j                  | j        | j        g| j        R i | j        }|j        dk    r'| j                            || j        | j                  S | j                            || j                  S )z$apply to the values as a numpy arrayc                      fd}|S )z
            Wrap user supplied function to work around numpy issue.

            see https://github.com/numpy/numpy/issues/8352
            c                 x     | i |}t          |t                    rt          j        |t                    }|S )Nrm  )r   rY   r$  arrayobject)r8   r:   r   r7   s      rB   wrapperz<FrameApply.apply_raw.<locals>.wrap_function.<locals>.wrapperH  sB    t.v..fc** <XfF;;;FrE   rA   )r7   ry  s   ` rB   wrap_functionz+FrameApply.apply_raw.<locals>.wrap_functionA  s#         NrE   r  r_   num_required_argsr   r   rg   rn  )r&   r7   r8   r:   r#   r%   r[  rF   r$  squeezeapply_along_axisr   rR   _constructorr   rg   rr  r2  )ru   rX   rZ   rz  r8   r:   	nb_looperr   s           rB   rh  zFrameApply.apply_raw>  s=   	 	 	 W5		"#	  LD& .	 #M22 I Yt{DI====FZ''FF(di((	 	  
 + F ;!8((tz4<(XXX8//dm/LLLrE   targetc                    t          | j                  sJ t          j        |j                  }|j        d         }t          |j                  D ]\  }} | j        ||         g| j        R i | j	        }t          j
        |          j        }|dk    rt          d          |dk    r"|t          |          k    rt          d          ||d d |f<   | j                            ||j        |j                  }|S )Nr   r_   ztoo many dims to broadcastzcannot broadcast resultr}  )r  r7   r$  
empty_liker[  rg  r   rg   r8   r:   asarrayr   rt   r   rR   r  r   )	ru   r  result_valuesresult_compareir   resaresr   s	            rB   rf  zFrameApply.apply_broadcastq  s   	"""""fm44  a// 	& 	&FAs$)F3KC$)CCCt{CCC:c??'D axx !=>>>qyy!SXX--$%>???"%M!!!Q$ &&v~ ' 
 
 rE   c                    | j         dk    r|                                 \  }}n|                                 \  }}|                     ||          S )NrQ   )rX   apply_series_generatorapply_series_numbawrap_resultsrU  s      rB   ri  zFrameApply.apply_standard  sU    ;(""!%!<!<!>!>GYY!%!8!8!:!:GY   )444rE   tuple[ResType, Index]c                0   t          | j                  sJ | j        }| j        }i }t	          |          D ]]\  }} | j        |g| j        R i | j        ||<   t          ||         t                    r||         	                    d          ||<   ^||fS )NF)deep)
r  r7   rE  r   r   r8   r:   r   r"   ro  )ru   
series_genrS  r   r  r   s         rB   r  z!FrameApply.apply_series_generator  s    	"""""*
%	j)) 	9 	9DAq"1@ty@@@DK@@GAJ'!*i00 9 %QZ__%_88
	!!rE   c                   | j                             dd          rt          d          | j        j        j        r| j        j        st          d          |                                  |                                 }|| j	        fS )NrJ  FzAParallel apply is not supported when raw=False and engine='numba'zBThe index/columns must be unique when raw=False and engine='numba')
rZ   getrd   rR   r   	is_uniquerg   rR  rM  r   rj  s     rB   r  zFrameApply.apply_series_numba  s    !!*e44 	%S   x~' 	t|/E 	%T   	&&((('')))))rE   c                0   ddl m} t          |          dk    r/d|v r+t          |d                   r|                     ||          S | j        j        }t          |          dk    r||u r ||t          j                  }n ||          }||_	        |S )Nr   r   rm  )
r   r.   r   r   rV  rR   rr  r$  rp  r   )ru   r   rS  r.   constructor_slicedr   s         rB   r  zFrameApply.wrap_results  s    !!!!!! w<<!WWQZ1H1H--gyAAA "X9w<<1!3v!=!=''rzBBBFF''00F rE   c                    | j         dk    r5| j        }|j        | j                 }|                    || j                  S t                                                      S )Nsizern  )r7   rR   rg  rF   rr  r2  r=  r   )ru   rR   valuer>  s      rB   r   zFrameApply.apply_str  sX     9(CIdi(E**5*FFFww  """rE   )rR   r   r7   r   rS   r?   rT   rU   rV   rW   rX   rY   rZ   r[   r\   rn   r9  r\   rC  TTFr\   rF  )r\   rn   r   r2   rS  r-   r\   rw   r)  )rQ   Nr  r,   r\   r,   )r\   r  )!rI   rJ   rK   r+  rv   r:  rN   rO   r   rB  rE  rM   	functoolscacherK  rM  rR  rV  rX  rg   r   r[  rH   r   ra  rh  rf  ri  r  r  r  r   __classcell__r>  s   @rB   r]   r]   e  s        NNN ,104
 
 
 
 
 
 
 
<     X     X     X _27     _ \
 	      	    # # # X#       X    ^4% 4% 4% 4%l    .,# ,# ,#\1M 1M 1M 1Mf   85 5 5" " " ""* * *   *# # # # # # # # # #rE   c                      e Zd ZU dZded<   edd            Zeej	        	 ddd
                        Z
ddZedd            Zedd            ZddZdS )rc   r   r   rF   r\   rC  c                ^      fdt          t           j                            D             S )Nc              3  P   K   | ] }j                             |d           V  !dS )r_   r   N)rR   r   )r   r  ru   s     rB   r  z1FrameRowApply.series_generator.<locals>.<genexpr>  s5      KKQaa((KKKKKKrE   )ranger   rg   rz   s   `rB   rE  zFrameRowApply.series_generator  s/    KKKK%DL8I8I2J2JKKKKrE   TFrF  c                    t          d          }ddlm ddlm |j                            |           |                    |||          fd            }|S )Nr  r   r   maybe_cast_strrH  rI  rJ  c           	         i }t          | j        d                   D ]5} | d d |f         | 	||                             } |g|R  ||<   6|S )Nr_   r   )r  rg  )
r[  	col_namesdf_indexr8   r   jserr.   
jitted_udfr  s
          rB   
numba_funcz;FrameRowApply.generate_numba_apply_func.<locals>.numba_func  s    G6<?++ 4 4f111a4L~~iPQl7S7S   (Z3d333

NrE   r   r   r.   pandas.core._numba.extensionsr  	extendingregister_jitablejit	r7   rH  rI  rJ  r  r  r.   r  r  s	         @@@rB   rK  z'FrameRowApply.generate_numba_apply_func  s    
 +733!!!!!! 	A@@@@@_55d;;
 
H	E	E	 	 	 	 	 	 
F	E	 rE   dict[int, Any]c           	        t          t          | j                  }t          || j        | j        d          \  }} | j        |fi t          | j                  }ddl	m
} | j        j        }| j        j        } ||          5 } ||          5 }t           || j        ||g|R            }d d d            n# 1 swxY w Y   d d d            n# 1 swxY w Y   |S Nr_   r{  r   )set_numba_datar   r   r7   r&   r8   r:   rK  r%   rZ   r  r  rR   r   rg   r   r[  	ru   r7   r8   r:   nb_funcr  r   rg   r  s	            rB   rM  zFrameRowApply.apply_with_numba  s   Hdi((1$)T[A
 
 
f 1$0
 
%d&899
 
 	A@@@@@(" ^E"" 	De^^G-D-D 	Dwwt{GUBTBBBCCC	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D
s6   CB:.C:B>	>CB>	CCCr-   c                    | j         S ry   rg   rz   s    rB   r   zFrameRowApply.result_index  
    |rE   c                    | j         S ry   rn  rz   s    rB   rB  zFrameRowApply.result_columns  
    zrE   r   r2   rS  rw   c                   | j         dk    r#| j                            |          }||_        |S | j         Nt	          d |                                D                       r#| j                            |          }||_        |S 	 | j                            |          }nL# t          $ r?}dt          |          v r(| j                            |          }||_        |cY d}~S  d}~ww xY wt          |d         t                    s6t          |j                  t          | j                  k    r| j        |_        t          |j                  t          |          k    r||_        |S )zreturn the results for the rowsrq   Nc              3  @   K   | ]}t          |t                    V  d S ry   )r   r   )r   r  s     rB   r  z6FrameRowApply.wrap_results_for_axis.<locals>.<genexpr>  s=       .
 .
$%Jq$.
 .
 .
 .
 .
 .
rE   r5   z%All arrays must be of the same lengthr   )rT   rR   rr  r   r   r[  r  rt   rY   r   r"   r   rX  rg   )ru   r   rS  r  r   r   s         rB   rV  z#FrameRowApply.wrap_results_for_axis  s|   
 x''(..w77C!CIJ%# .
 .
)0)9)9.
 .
 .
 +
 +
%
 (..w77C!CIJ
	X***88FF 	 	 	6#c((BB h227;;%	





	 '!*i00 	06<  C(8$9$999#/v~#i..00&FNs$   B! !
C*+3C%C*$C%%C*Nr  r  r  r\   r  r9  r  )rI   rJ   rK   rF   r+  r:  rE  rM   r  r  rK  rM  r   rB  rV  rA   rE   rB   rc   rc     s         DL L L XL _27    _ \6   &    X    X' ' ' ' ' 'rE   rc   c                       e Zd ZU dZded<   d fdZedd	            Zee	j
        	 ddd                        ZddZedd            Zedd            ZddZd dZ xZS )!re   r_   r   rF   r  r,   r\   c                ^    t                                          |j                  }|j        S ry   )r=  rf  r   )ru   r  r   r>  s      rB   rf  z FrameColumnApply.apply_broadcast@  s#    ((22xrE   rC  c              #    K   | j         }t          |          }t          |          dk    sJ | j                            dd          }|j        }|j        d         j                                        }t          |j
        t                    rA| j        }t          t          |                    D ]}|                    |d          V  d S t          || j        d          D ]m\  }}||_        |                    |           t                               |d|           |s*t%          |j        d                   |j        d         _        |V  nd S )Nr   r   Tr   _name)r[  r$   r   rR   r   rd  blocksrefshas_referencer   rQ  r   r  r   r   
set_valuesrx  __setattr__r   )	ru   r[  r  mgris_viewrR   r  arrr   s	            rB   rE  z!FrameColumnApply.series_generatorD  s[     /776{{Q hmmAAm&&h*Q-$2244ci00 	 (C3s88__ * *hhqqh))))))* * !DAAA  	Ts###""3666 H *9A)G)GCJqM&				 rE   TFrF  c                    t          d          }ddlm ddlm |j                            |           |                    |||          fd            }|S )Nr  r   r   r  r  c           	         i }t          | j        d                   D ]C} | |                                         | 	||                             } |g|R  ||<   D|S )Nr   r   )r  rg  ro  )
r[  col_names_indexr   r8   r   r  r  r.   r  r  s
          rB   r  z>FrameColumnApply.generate_numba_apply_func.<locals>.numba_funcs  s    G 6<?++ 4 4 f1INN$$)'a11  
 (Z3d333

NrE   r  r  s	         @@@rB   rK  z*FrameColumnApply.generate_numba_apply_funch  s    
 +733!!!!!!@@@@@@_55d;;
	H	E	E	 	 	 	 	 	 
F	E	  rE   r  c           	        t          t          | j                  }t          || j        | j        d          \  }} | j        |fi t          | j                  }ddl	m
}  || j        j                  5 } || j                  5 }t           || j        ||g|R            }d d d            n# 1 swxY w Y   d d d            n# 1 swxY w Y   |S r  r  r  s	            rB   rM  z!FrameColumnApply.apply_with_numba  s   Hdi((1$)T[A
 
 
f 1$0
 
%d&899
 
 	A@@@@@
 N48>**	D.3N4<((	D,3wwt{GUBTBBBCCC		D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 
s6   6CB1%C1B5	5C8B5	9CCCr-   c                    | j         S ry   rn  rz   s    rB   r   zFrameColumnApply.result_index  r  rE   c                    | j         S ry   r  rz   s    rB   rB  zFrameColumnApply.result_columns  r  rE   r   r2   rS  rw   c                    | j         dk    r|                     ||          }nSt          |d         t                    s"| j                            |          }||_        n|                     ||          }|S )z"return the results for the columnsrs   r   )rT   infer_to_same_shaper   r"   rR   rr  r   ru   r   rS  r   s       rB   rV  z&FrameColumnApply.wrap_results_for_axis  s|     x''--gyAAFF GAJ	22 	BX11'::F$FLL --gyAAFrE   c                    | j                             |          }|j        }||_        |                                }|S )z7infer the results to the same shape as the input objectr  )rR   r  r   r   infer_objectsr  s       rB   r  z$FrameColumnApply.infer_to_same_shape  sB    &&G&44 ! %%''rE   r  r  r  r  r  r9  r  )r   r2   rS  r-   r\   r,   )rI   rJ   rK   rF   r+  rf  r:  rE  rM   r  r  rK  rM  r   rB  rV  r  r  r  s   @rB   re   re   =  s!        D      ! ! ! X!F _27    _ \8   *    X    X   *       rE   re   c                  r     e Zd ZU ded<   dZded<   ded<   dd	d fdZddZ fdZddZd Z	ddZ
 xZS )r5  r.   rR   r   r   rF   rm   rV   rP   rV   r7   r   r\   rn   c          	     X    t                                          ||dd |||           d S )NF)rS   rT   rV   r8   r:   )r=  rv   )ru   rR   r7   rV   r8   r:   r>  s         rB   rv   zSeriesApply.__init__  sE     	 	 	
 	
 	
 	
 	
rE   rw   c                p   | j         }t          |          dk    r|                                 S t          | j                  r|                                 S t          | j        t                    r|                                 S | j	        dk    r| 
                                S |                                 S )Nr   rp   )rR   r   ra  r   r7   r  r   rY   r   rV   apply_compatri  ru   rR   s     rB   rH   zSeriesApply.apply  s    hs88q==**,,, 	"" 	2//111di%% 	$>>###;)##$$&&& ""$$$rE   c                    t                                                      }|5| j        }| j        }t	          |          sJ  ||g| j        R i | j        }|S ry   )r=  r   rR   r7   r  r8   r:   )ru   r   rR   r7   r>  s       rB   r   zSeriesApply.agg  s`    >(C9DD>>!!>T#9	999T[99FrE   c                |    | j         }|                    |j        |j                                      |d          S )N)rQ  r   rH   r  )rR   r  rQ  r   __finalize__r  s     rB   ra  zSeriesApply.apply_empty_result  sC    hcisyAANN O 
 
 	
rE   c                P   | j         }| j        }t          |          r;t          j        |          }|r%| j        s| j        s|                    |d          S 	 |                    |d          }n4# t          t          t          f$ r |                    |d          }Y nw xY w|S )zcompat apply method for funcs in listlikes and dictlikes.

         Used for each callable when giving listlikes and dictlikes of callables to
         apply. Needed for compatibility with Pandas < v2.1.

        .. versionadded:: 2.1.0
        Fr  rP   )rR   r7   r  r   get_cython_funcr8   r:   rH   rt   r&  r   )ru   rR   r7   r'  r   s        rB   r  zSeriesApply.apply_compat  s     hyD>> 	5#D))A 5 54; 5yyey444	3YYtHY55FFNI6 	3 	3 	3YYtEY22FFF	3s   A2 2.B#"B#c                    t          t           j                   j        }t	          t
          j                  rDt          j        d          5   |g j        R i  j	        cd d d            S # 1 swxY w Y   n j
        s |g j        R i  j	        S  j        s j	        r fd}n}|                    |          }t          |          rDt	          |d         t                    r)|                    t          |          |j                  S |                    ||j                                      |d          S )	Nr]  r^  c                0     | gj         R i j        S ry   )r8   r:   )r  r7   ru   s    rB   curriedz+SeriesApply.apply_standard.<locals>.curried%  s'    tA9	999T[999rE   )mapperr   rn  rH   r  )r   r   r7   rR   r   r$  rb  rc  r8   r:   rV   _map_valuesr   r"   _constructor_expanddimr   r   r  r  )ru   rR   r  mappedr7   s   `   @rB   ri  zSeriesApply.apply_standard  s   Hdi((hdBH%% 	8*** < <tC;$);;;t{;;< < < < < < < < < < < < < < < < < 	847di7774;7779 	 	: : : : : : : G00v;; 	:fQi;; 	 --d6ll#)-LLL##F#)#<<IIG J   s   A66A:=A:)rR   r.   r7   r   rV   rm   r\   rn   r)  )r\   r.   )rI   rJ   rK   r+  rF   rv   rH   r   ra  r  ri  r  r  s   @rB   r5  r5    s         KKKD//// 7?
 
 
 
 
 
 
 
&% % % %(    
 
 
 
  ,       rE   r5  c                  H     e Zd ZU ded<   d fdZd	 Zd
 ZddZddZ xZ	S )GroupByApplyz GroupBy | Resampler | BaseWindowrR   GroupBy[NDFrameT]r7   r   r\   rn   c                   |                                 }|j                            |                    dd                    | _        t                                          ||dd ||           d S )NrF   r   FrS   rT   r8   r:   )ro  rR   rb   r  rF   r=  rv   ru   rR   r7   r8   r:   r>  s        rB   rv   zGroupByApply.__init__9  st     G,,VZZ-B-BCC	 	 	
 	
 	
 	
 	
rE   c                    t           ry   rd   rz   s    rB   rH   zGroupByApply.applyL      !!rE   c                    t           ry   r  rz   s    rB   r   zGroupByApply.transformO  r  rE   r|   r}   rw   c           	        | j         }| j        }|dk    ri |ddi}t          |dd          dk    rt          d          |j        j        dk    r|j        }n|j        }t          j        |dd	t          |d          
          5  | 
                    |||          \  }}d d d            n# 1 swxY w Y   |                     ||          }|S )NrH   rV   FrF   r   r_   r4  as_indexT	condition)rR   r:   r   rd   _selected_objr   _obj_with_exclusionsr   temp_setattrr#  r   r   )ru   r|   rR   r:   r   r   r   r   s           rB   r   z#GroupByApply.agg_or_apply_list_likeR  sF    hg00%00F3""a''%&JKKK!Q&&,LL3L TWS*-E-E
 
 
 	R 	R !227L&QQMD'	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	R ,,T7;;s   B--B14B1c           	        ddl m}m} |dv sJ | j        }i }|dk    r"| j        rdnd}|                    d|i           t          |dd          d	k    rt          d
          |j        }|j	        }t          |||f          }	|	rN| j                            dd           }
| j                            dd           }|                    |
|d           t          j        |ddt          |d                    5  |                     ||||          \  }}d d d            n# 1 swxY w Y   |                     |||          }|S )Nr   r   r7  rH   rp   FrV   rF   r_   r4  rX   rZ   r`  r  Tr  )r   r   r   rR   rV   r8  r   rd   r  
_selectionr   r:   r  r   r  r#  r   r  )ru   r|   r   r   rR   r:   rV   r   r   r   rX   rZ   r   r   r   s                  rB   r   z#GroupByApply.agg_or_apply_dict_likel  s   	
 	
 	
 	
 	
 	
 	
 	

 *****h!#g"&+8YY5FMM8V,---3""a''%&JKKK(N	&6%FGG
  	N[__Xt44F KOOOTBBMMMVmLLMMMTWS*-E-E
 
 
 	 	 )-(>(>y&) )%L+	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ,,\<UUs   :D""D&)D&)rR   r  r7   r   r\   rn   r*  )
rI   rJ   rK   r+  rv   rH   r   r   r   r  r  s   @rB   r  r  6  s         ))))
 
 
 
 
 
&" " "" " "   4% % % % % % % %rE   r  c                  F     e Zd ZU dZded<   ded<   d fd
Zd Zd Z xZS )ResamplerWindowApplyr   r   rF   Resampler | BaseWindowrR   r7   r   r\   rn   c               d    t          t          |                               ||dd ||           d S )NFr  )r=  r  rv   r  s        rB   rv   zResamplerWindowApply.__init__  sH     	lD!!** 	+ 	
 	
 	
 	
 	
rE   c                    t           ry   r  rz   s    rB   rH   zResamplerWindowApply.apply  r  rE   c                    t           ry   r  rz   s    rB   r   zResamplerWindowApply.transform  r  rE   )rR   r  r7   r   r\   rn   )	rI   rJ   rK   rF   r+  rv   rH   r   r  r  s   @rB   r  r    sz         D
 
 
 
 
 
"" " "" " " " " " "rE   r  AggFuncType | NoneMtuple[bool, AggFuncType, tuple[str, ...] | None, npt.NDArray[np.intp] | None]c                `  	 ddl m	 | du o8t          di |p,t          	fd|                                D                       }d}d}|sbt          | t                    r<t          |           t          t          |                     k    rt          d          | t          d          |rwi }|                                D ]M\  }}t          |	          r3|j        }|j        s|j        r||j        |j        fd}|j        |f||<   H|||<   Nt!          |          \  } }}| J || ||fS )	a  
    This is the internal function to reconstruct func given if there is relabeling
    or not and also normalize the keyword to get new order of columns.

    If named aggregation is applied, `func` will be None, and kwargs contains the
    column and aggregation function information to be parsed;
    If named aggregation is not applied, `func` is either string (e.g. 'min') or
    Callable, or list of them (e.g. ['min', np.max]), or the dictionary of column name
    and str/Callable/list of them (e.g. {'A': 'min'}, or {'A': [np.min, lambda x: x]})

    If relabeling is True, will return relabeling, reconstructed func, column
    names, and the reconstructed order of columns.
    If relabeling is False, the columns and order will be None.

    Parameters
    ----------
    func: agg function (e.g. 'min' or Callable) or list of agg functions
        (e.g. ['min', np.max]) or dictionary (e.g. {'A': ['min', np.max]}).
    **kwargs: dict, kwargs used in is_multi_agg_with_relabel and
        normalize_keyword_aggregation function for relabelling

    Returns
    -------
    relabelling: bool, if there is relabelling or not
    func: normalized and mangled func
    columns: tuple of column names
    order: array of columns indices

    Examples
    --------
    >>> reconstruct_func(None, **{"foo": ("col", "min")})
    (True, defaultdict(<class 'list'>, {'col': ['min']}), ('foo',), array([0]))

    >>> reconstruct_func("min")
    (False, 'min', None, None)
    r   )NamedAggNc              3  8   K   | ]}t          |          V  d S ry   r  )r   r   r  s     rB   r  z#reconstruct_func.<locals>.<genexpr>  s-      @@1z!X&&@@@@@@rE   zFFunction names must be unique if there is no new column names assignedz4Must provide 'func' or tuples of '(column, aggfunc).c                     || g|R i |S ry   rA   )r  r7   r   kws       rB   <lambda>z"reconstruct_func.<locals>.<lambda>  s7    QUQURR R R!#R R rE   rA   )r   r  is_multi_agg_with_relabelr   r[  r   r   r   setr   r   r   aggfuncr8   r:   columnnormalize_keyword_aggregation)
r7   r:   
relabelingrg   orderconverted_kwargsr   valr  r  s
            @rB   ra   ra     s   N 544444 !++F++ 	A@@@@@@@@@ 
 '+G)-E 	TdD!! 	c$ii#c$ii..&@&@ %X   <RSSS 
  		, 		,HC#x(( ,+8 sz -4SZ   G *-W(= %%(+ %%< 
  
gu tWe++rE   c                 ~    t          d |                                 D                       ot          |           dk    S )ax  
    Check whether kwargs passed to .agg look like multi-agg with relabeling.

    Parameters
    ----------
    **kwargs : dict

    Returns
    -------
    bool

    Examples
    --------
    >>> is_multi_agg_with_relabel(a="max")
    False
    >>> is_multi_agg_with_relabel(a_max=("a", "max"), a_min=("a", "min"))
    True
    >>> is_multi_agg_with_relabel()
    False
    c              3  f   K   | ],}t          |t                    ot          |          d k    V  -dS )r   N)r   r9   r   r   s     rB   r  z,is_multi_agg_with_relabel.<locals>.<genexpr>  s;      MMz!U##3A!MMMMMMrE   r   )r   r[  r   )r:   s    rB   r  r    s=    * MMV]]__MMMMM FarE   r:   r   ]tuple[MutableMapping[Hashable, list[AggFuncTypeBase]], tuple[str, ...], npt.NDArray[np.intp]]c                   ddl m} t          t                    }g }t	          |                                           }|                                 D ]K\  }}||                             |           |                    |t          j	        |          p|f           Lt          |          }d |                                D             }t          |          }	 ||	                              |          }
|||
fS )aR  
    Normalize user-provided "named aggregation" kwargs.
    Transforms from the new ``Mapping[str, NamedAgg]`` style kwargs
    to the old Dict[str, List[scalar]]].

    Parameters
    ----------
    kwargs : dict

    Returns
    -------
    aggspec : dict
        The transformed kwargs.
    columns : tuple[str, ...]
        The user-provided keys.
    col_idx_order : List[int]
        List of columns indices.

    Examples
    --------
    >>> normalize_keyword_aggregation({"output": ("input", "sum")})
    (defaultdict(<class 'list'>, {'input': ['sum']}), ('output',), array([0]))
    r   r   c                N    g | ]"\  }}|D ]}|t          j        |          p|f#S rA   r   )r   r  aggfuncsr  s       rB   r   z1normalize_keyword_aggregation.<locals>.<listcomp>R  sX       FH   
&w//:7;   rE   )pandas.core.indexes.baser-   r   r   r9   r   r[  r   r   r   _make_unique_kwarg_listr   get_indexer)r:   r-   aggspecr  rg   r  r  uniquified_orderaggspec_orderuniquified_aggspeccol_idx_orders              rB   r  r  !  s   < /.....
 $GEFKKMM""G!==?? J Jw'''fc3G<<GHIIII /u55
  '  M
 1?? E,--99:JKKMG]**rE   seqSequence[tuple[Any, Any]]c                :      fdt                     D             S )a  
    Uniquify aggfunc name of the pairs in the order list

    Examples:
    --------
    >>> kwarg_list = [("a", "<lambda>"), ("a", "<lambda>"), ("b", "<lambda>")]
    >>> _make_unique_kwarg_list(kwarg_list)
    [('a', '<lambda>_0'), ('a', '<lambda>_1'), ('b', '<lambda>')]
    c                    g | ]P\  }}                     |          d k    r0|d         |d           dd|                              |           fn|QS )r_   r   rf   N)count)r   r  pairr+  s      rB   r   z+_make_unique_kwarg_list.<locals>.<listcomp>j  sv       At :=419L9LaT!W44s2A2w}}T224455RV  rE   )r   )r+  s   `rB   r$  r$  ^  s4        ~~   rE   r   rw   dict[str, list[Callable | str]]rg   r   r  Iterable[int]dict[Hashable, Series]c                   ddl m} d t          t          ||d          d           D             }i }d}t	          | t
                     ot          | j                  dk    }|                                D ]\  }	}
| |	         	                                }|r^d	 |
D             }
 ||j
        d
                              |
          }|dk    }|                                r|j        ||                  }|j        s|||t          |
          z            |_
        |                    |          ||	<   |t          |
          z   }|S )a  
    Internal function to reorder result if relabelling is True for
    dataframe.agg, and return the reordered result in dict.

    Parameters:
    ----------
    result: Result from aggregation
    func: Dict of (column name, funcs)
    columns: New columns name for relabelling
    order: New order for relabelling

    Examples
    --------
    >>> from pandas.core.apply import relabel_result
    >>> result = pd.DataFrame(
    ...     {"A": [np.nan, 2, np.nan], "C": [6, np.nan, np.nan], "B": [np.nan, 4, 2.5]},
    ...     index=["max", "mean", "min"],
    ... )
    >>> funcs = {"A": ["max"], "C": ["max"], "B": ["mean", "min"]}
    >>> columns = ("foo", "aab", "bar", "dat")
    >>> order = [0, 1, 2, 3]
    >>> result_in_dict = relabel_result(result, funcs, columns, order)
    >>> pd.DataFrame(result_in_dict, index=columns)
           A    C    B
    foo  2.0  NaN  NaN
    aab  NaN  6.0  NaN
    bar  NaN  NaN  4.0
    dat  NaN  NaN  2.5
    r   r   c                    g | ]
}|d          S )r   rA   )r   r0  s     rB   r   z"relabel_result.<locals>.<listcomp>  s)       Q  rE   Tr   c                    | d         S )Nr_   rA   )ts    rB   r  z relabel_result.<locals>.<lambda>  s    STUVSW rE   )r   r_   c                d    g | ]-}t          |t                    st          j        |          n|.S rA   )r   rY   r   r   )r   r'  s     rB   r   z"relabel_result.<locals>.<listcomp>  sD       NO
1c0B0BI%a(((  rE   F)ro  )r#  r-   sortedr   r   r"   r   rg   r   dropnar   r%  r   r   r   reindex)r   r7   rg   r  r-   reordered_indexesreordered_result_in_dictidxreorder_maskr   funsr*  	valid_idxs                 rB   relabel_resultrD  p  s   F /..... "3wd#C#C#CXXX   8:
C!&)444PV^9L9Lq9PLJJLL $ $S3K  ,  	5 SV  C "E!'666BB3GGM%+I}} 5F=34 w 	>'cCHHn(<=AG()		'(:(: %CHHn##rE   c                    ddl m} t          |fi |\  }}}}|r'|J |J t          | |||          } |||          } | S )Nr   )r,   rn  )r   r,   ra   rD  )r   r7   r:   r,   r  rg   r  result_in_dicts           rB   r  r    s          '7'G'G'G'G$Jgu 
: """   'guEE>999MrE   r"  Sequence[Any]c                    t          |           dk    r| S d}g }| D ]N}t          j        |          dk    rt          |          }d| d|_        |dz  }|                    |           O|S )aJ  
    Possibly mangle a list of aggfuncs.

    Parameters
    ----------
    aggfuncs : Sequence

    Returns
    -------
    mangled: list-like
        A new AggSpec sequence, where lambdas have been converted
        to have unique names.

    Notes
    -----
    If just one aggfunc is passed, the name will not be mangled.
    r_   r   z<lambda>z<lambda_>)r   r   r   r   rI   r   )r"  r  mangled_aggfuncsr  s       rB   _managle_lambda_listrK    s    $ 8}}	A ) ) ))Z77g&&G.!GFA((((rE   agg_specr   c                :   t          |           }|st          |           s| S  t          |                       }|rP|                                 D ]:\  }}t          |          rt          |          st	          |          }n|}|||<   ;nt	          |           }|S )aZ  
    Make new lambdas with unique names.

    Parameters
    ----------
    agg_spec : Any
        An argument to GroupBy.agg.
        Non-dict-like `agg_spec` are pass through as is.
        For dict-like `agg_spec` a new spec is returned
        with name-mangled lambdas.

    Returns
    -------
    mangled : Any
        Same type as the input.

    Examples
    --------
    >>> maybe_mangle_lambdas("sum")
    'sum'
    >>> maybe_mangle_lambdas([lambda: 1, lambda: 2])  # doctest: +SKIP
    [<function __main__.<lambda_0>,
     <function pandas...._make_lambda.<locals>.f(*args, **kwargs)>]
    )r   r   r%  r   rK  )rL  is_dictmangled_aggspecr   r"  rJ  s         rB   maybe_mangle_lambdasrP    s    2 8$$G |H-- $d8nn&&O 	9%^^-- 	4 	4MCH%% ,l8.D.D ,#7#A#A  #+ #3OC  	4 /x88rE   0tuple[list[str], list[str | Callable[..., Any]]]c                ^   d}t          |           }g }|                                 D ]o}t          |t                    sCt	          |          s4t          |                    t          |          j                            |	                    |           p|sd}t          |          ||fS )a  
    Validates types of user-provided "named aggregation" kwargs.
    `TypeError` is raised if aggfunc is not `str` or callable.

    Parameters
    ----------
    kwargs : dict

    Returns
    -------
    columns : List[str]
        List of user-provided keys.
    func : List[Union[str, callable[...,Any]]]
        List of user-provided aggfuncs

    Examples
    --------
    >>> validate_func_kwargs({"one": "min", "two": "max"})
    (['one', 'two'], ['min', 'max'])
    z-func is expected but received {} in **kwargs.z2Must provide 'func' or named aggregation **kwargs.)
r   r[  r   rY   r  r   formatr%  rI   r   )r:   tuple_given_messagerg   r7   col_funcno_arg_messages         rB   validate_func_kwargsrW  -  s    . J6llGDMMOO  8S)) 	QXh-?-? 	Q/66tH~~7NOOPPPH (M'''D=rE   r|   r}   r   r   c                b    t          |t                    pt          |t                    o| dk    S )Nr   )r   r    r"   )r|   r   s     rB   r   r   Q  s0    dL)) 4##85(8rE   )r   FNrP   rQ   NNN)rR   r,   r7   r   rF   r   rS   r?   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   )r7   r  r\   r  )r\   r?   )r:   r   r\   r  )r+  r,  r\   r,  )
r   rw   r7   r1  rg   r   r  r2  r\   r3  r)  )r"  rG  r\   rG  )rL  r   r\   r   )r:   r   r\   rQ  )r|   r}   r   r   r\   r?   )f
__future__r   rN   collectionsr   collections.abcr   r  r   r  typingr   r   r	   r
   r   numpyr$  pandas._libs.internalsr   pandas._typingr   r   r   r   r   r   r   r   pandas.compat._optionalr   pandas.errorsr   pandas.util._decoratorsr   r   pandas.core.dtypes.castr   pandas.core.dtypes.commonr   r   r   r   r   pandas.core.dtypes.dtypesr   pandas.core.dtypes.genericr    r!   r"   pandas.core._numba.executorr#   pandas.core.commoncorecommonr   pandas.core.constructionr$   pandas.core.util.numba_r%   r&   r'   r(   r)   r*   r+   r   r,   r-   r.   pandas.core.groupbyr/   pandas.core.resampler0   pandas.core.window.rollingr1   r   intr2   r+  ABCr4   ri   ABCMetark   r.  r]   rc   re   r5  r  r  ra   r  r  r$  rD  r  rK  rP  rW  r   rA   rE   rB   <module>rs     sR   " " " " " " " 



 # # # # # # $ $ $ $ $ $                             2 2 2 2 2 2	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ? > > > > > , , , , , ,       
 5 4 4 4 4 4              5 4 4 4 4 4          > = = = = =                   C C C C C C       
  6                      
 ,+++++......555555#s(^ # # # # "##e e e e e#' e e $#eV "'/,0	$ $ $ $ $ND	& D	& D	& D	& D	&ck D	& D	& D	& D	&N: : : : :5 : : :zl# l# l# l# l# l# l# l#^f f f f fJ f f fRF F F F Fz F F FRm m m m m, m m m`[ [ [ [ [5 [ [ [|" " " " "< " " "8T, T, T, T,n   4:+ :+ :+ :+z   $Q$ Q$ Q$ Q$h   6   D) ) ) )X! ! ! !H     rE   