
    dڶ                       d dl mZ d dlZd dlmZ d dlmZ d dlmZ d dl	Z	d dl
mZmZmZmZmZmZmZmZmZmZmZmZ d dlZd dl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% d d
l&m'Z' d dl(m)Z) d dl*m+Z+ d dl,m-Z-m.Z.m/Z/m0Z0 d dl1m2Z2m3Z3m4Z4 d dl5m6Z6 d dl7m8Z8 d dl9m:c m;Z< d dl=m>Z> erd dl?m@Z@mAZAmBZB d dlCmDZD d dlEmFZF d dlGmHZH eeIef         ZJ	 	 	 	 	 dPdQd#ZK G d$ d%ejL        &          ZM G d' d(eM          ZN G d) d"eN          ZO G d* d+eO          ZP G d, d-eO          ZQ G d. d/eN          ZR G d0 d1eM          ZS G d2 d3eM          ZTdRd6ZUdSd7ZVdTd;ZWdUd>ZXdVdGZYdWdJZZdXdMZ[dYdOZ\dS )Z    )annotationsN)defaultdict)nullcontext)partial)TYPE_CHECKINGAnyCallableContextManagerDefaultDictDictHashableIterableIteratorListSequencecast)option_context)lib)AggFuncTypeAggFuncTypeBaseAggFuncTypeDict
AggObjTypeAxisAxisIntNDFrameTnpt)SpecificationError)cache_readonly)is_nested_object)is_dict_likeis_extension_array_dtypeis_list_likeis_sequence)ABCDataFrame
ABCNDFrame	ABCSeries)	safe_sort)SelectionMixin)ensure_wrapped_if_datetimelike)	DataFrameIndexSeries)GroupBy)	Resampler)
BaseWindowFobjr*   funcr   axisr   rawboolresult_type
str | Nonereturn
FrameApplyc                    |                      |          }|dk    rt          }n|dk    rt          } || |||||          S )z=construct and return a row or column based frame apply objectr      r3   r5   argskwargs)_get_axis_numberFrameRowApplyFrameColumnApply)r0   r1   r2   r3   r5   r<   r=   klasss           M/var/www/html/t/fyr/venv311/lib/python3.11/site-packages/pandas/core/apply.pyframe_applyrC   I   s`     %%Dqyy	 5       c                      e Zd ZU ded<   ddZej        d d            Zd!dZd dZ	d Z
d dZd dZd dZd dZd dZd"dZd#dZdS )$Applyr   r2   r0   r   r3   r4   r5   r6   r7   Nonec                   || _         || _        pd| _        pi | _        |dvrt	          d          || _        sr8t          t          j        t          f          st                    sfd}n}| _        || _        d S )N )Nreduce	broadcastexpandzUinvalid value for result_type, must be one of {None, 'reduce', 'broadcast', 'expand'}c                     | gR i S NrI   )xr<   r1   r=   s    rB   fzApply.__init__.<locals>.f   s#    tA///////rD   )r0   r3   r<   r=   
ValueErrorr5   
isinstancenpufuncstrr"   orig_frP   )selfr0   r1   r3   r5   r<   r=   rP   s     `  `` rB   __init__zApply.__init__g   s     JB	lEEE=  
 ' 
	
	tbh_55
	 !&&
	0 0 0 0 0 0 0 0 A#'rD   DataFrame | Seriesc                    d S rN   rI   rW   s    rB   applyzApply.apply   s    rD   DataFrame | Series | Nonec                   | j         }| j        }| j        }| j        }t	          |t
                    r|                                 S t          |          r|                                 S t          |          r| 
                                S t          |          r2t          j        |          }|r|s|s t          ||                      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)r0   rP   r<   r=   rR   rU   	apply_strr    agg_dict_liker"   agg_list_likecallablecomget_cython_funcgetattrrW   r0   argr<   r=   rP   s         rB   aggz	Apply.agg   s     hfyc3 	$>>### 	(%%'''# 	(%%'''C== 	)#C((A ) )f )&wsA((( trD   c                   | j         }| j        | j        }| j        }| j        }|j        dk    }|                    |          dk    r |rJ  |j        j        dg|R i |j        S t                    rLt                    s=t          t          t                             |rd D             nfd|D             t                    r*t          t                    |                               S t          t                    	 |                               }n,# t"          $ r  t$          $ r}t'          d          |d}~ww xY wt)          |t*          t,          f          r|j        r|j        st'          d          t)          |t*          t,          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 rI   rc   get_callable_name.0vs     rB   
<dictcomp>z#Apply.transform.<locals>.<dictcomp>   s*    GGGQ-a005AqGGGrD   c                    i | ]}|S rI   rI   )rn   colr1   s     rB   rp   z#Apply.transform.<locals>.<dictcomp>   s    111cT111rD   zTransform function failedNzFunction did not transform)r0   rV   r2   r<   r=   ndimr>   T	transformr"   r    r   r   r   r   transform_dict_liketransform_str_or_callable	TypeError	ExceptionrQ   rR   r&   r$   emptyindexequals)	rW   r0   r2   r<   r=   	is_seriesresulterrr1   s	           @rB   ru   zApply.transform   s!    h{yyHM	%%**    "35?4<T<<<V<<>> 	2l4&8&8 	2_-t44D 2GG$GGG1111S111 	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   D) )E=EE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 providedru   r:   rs   r2   )pandas.core.reshape.concatr   r0   r<   r=   rR   r%   lenrQ   normalize_dictlike_argitems_gotitemru   )
rW   r1   r   r0   r<   r=   resultsnamehowcolgs
             rB   rv   zApply.transform_dict_like   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&&&&rD   c                8   | j         }| j        }| j        }t          |t                    r | j        ||g|R i |S |s0|s.t          j        |          }|r t          ||                      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
        r<   )r0   r<   r=   rR   rU   _try_aggregate_string_functionrc   rd   re   r\   ry   )rW   r1   r0   r<   r=   rP   s         rB   rw   zApply.transform_str_or_callable  s     hydC   	S646sDR4RRR6RRR 	)F 	)#D))A )&wsA(((	.39T777777 	. 	. 	.4-d---f-----	.s   0B   BBc           	        ddl m}m} ddlm} | j        }t          t          t                   | j	                  }t          |dd          dk    rt          d          t          |t                    s|}n|j        j        dk    r|j        }n|j        }g }g }t          |||f          }	|	rt#          j        |dd          }
nt'                      }
|
5  |j        dk    r|D ]}|                    |j        d|	          }t          |t,          t.          f          r" |j        || j        g| j        R i | j        }n |j        |g| j        R i | j        }|                    |           t#          j        |          p|}|                    |           ng }t=          |          D ]\  }}|                    |d|j        d
d
|f         	          }t          |t,          t.          f          r" |j        || j        g| j        R i | j        }n |j        |g| j        R i | j        }|                    |           |                    |           |j         !                    |          }d
d
d
           n# 1 swxY w Y   	  |||dd          S # tD          $ rD}ddl#m$}  ||||j                  }tK          |          rtM          d          ||cY d
}~S d
}~ww xY w)z
        Compute aggregation in the case of a list-like argument.

        Returns
        -------
        Result of aggregation.
        r   DataFrameGroupBySeriesGroupByr   r2   r:   "axis other than 0 is not supportedas_indexT)rs   subsetNF)keysr2   sortr,   )r{   r   z3cannot combine transform and aggregation operations)'pandas.core.groupby.genericr   r   r   r   r0   r   r   r   rP   re   NotImplementedErrorrR   r(   _selected_objrs   _obj_with_exclusionsrc   temp_setattrr   r   r   r&   r$   	aggregater2   r<   r=   appendrl   	enumerateiloccolumnstakerx   pandasr,   r   rQ   )rW   r   r   r   r0   rg   selected_objr   r   
is_groupbycontext_managerar   new_resr   indicesr{   rr   r   r,   r~   s                        rB   ra   zApply.agg_list_like!  s   	
 	
 	
 	
 	
 	
 	
 	
 	655555h4($&113""a''%&JKKK#~.. 	4LL#q((,LL3L&6%FGG
 	, ".sJEEOO)mmO 	: 	: A%% & &A<<(9,<WWD!$L(ABB O"0$.ty#+/9# # #8<# # #1$."NTY"N"N"N$+"N"NNN7+++ 0338qDKK%%%%& "+L"9"9 	* 	*JE3<<!L<MaaaQVh<W<XXD!$L(ABB Q"0$.#-1Y# # #:>+# # #1$."Pty"P"P"PDK"P"PNN7+++NN5))))#+0099;	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	:>	6'15AAAA 
	 
	 
	 &%%%%%VG4ch???F''  I  MMMMMM
	s1   F#JJJJ 
K-)9K("K-(K-c                   ddl m} ddlm}m} ddlm} | j        t          t          | j
                  }t          dd          dk    rt          d          t          t                    s}d}nj        }j        }|                     d	||          }t          ||f          }|rt%          j        d
d          }	nt)                      }	|	5  |j        dk    r8                    |d          fd|                                D             n fd|                                D             ddd           n# 1 swxY w Y   t1          |                                          }
d                                 D             }t7          |          rfd|
D             }|g k    r|n|
}|j        dk    r, ||          }|                    |j        j                   |}t          t>                    rdnd} |fd|D             ||          }nVtA          |          rtC          d          ddl m"} j        dk    rt          d          j#        }nd} ||          }|S )z
        Compute aggregation in the case of a dict-like argument.

        Returns
        -------
        Result of aggregation.
        r   r+   r   r   r2   r:   r   Nrh   r   Tr   c                B    i | ]\  }}|                     |          S rI   )rh   )rn   keyr   r   s      rB   rp   z'Apply.agg_dict_like.<locals>.<dictcomp>  s)    JJJ(#s3JJJrD   c                l    i | ]0\  }}|                     |d                               |          1S )r:   r   )r   rh   )rn   r   r   r0   s      rB   rp   z'Apply.agg_dict_like.<locals>.<dictcomp>  sJ       @HSCc2266s;;  rD   c                8    g | ]}t          |t                    S rI   )rR   r%   )rn   rs     rB   
<listcomp>z'Apply.agg_dict_like.<locals>.<listcomp>  s"    JJJAjJ//JJJrD   c                .    g | ]}|         j         |S rI   )rz   rn   kr   s     rB   r   z'Apply.agg_dict_like.<locals>.<listcomp>  s%    CCC'!*2BC1CCCrD      c                "    i | ]}||         S rI   rI   r   s     rB   rp   z'Apply.agg_dict_like.<locals>.<dictcomp>  s    4441GAJ444rD   )r2   r   zLcannot perform both aggregation and transformation operations simultaneouslyr   r,   )r   )$r   r+   r   r   r   r   r   r0   r   r   rP   re   r   rR   r(   r   
_selectionr   rc   r   r   rs   r   r   listr   valuesall
_set_namesr   namesr&   anyrQ   r,   r   )rW   r+   r   r   r   rg   r   	selectionr   r   r   
is_ndframekeys_to_usektur2   r~   r,   r   r   r0   r   s                     @@@rB   r`   zApply.agg_dict_likev  s^    	!     	
 	
 	
 	
 	
 	
 	
 	
 	655555h?DF++3""a''%&JKKK#~.. 	'LII,LI))%sCC&6%FGG
 	, ".sJEEOO)mmO 		 		 A%%||IA|66JJJJciikkJJJ   LOIIKK  		 		 		 		 		 		 		 		 		 		 		 		 		 		 		 CHHJJ KJ9I9IJJJ
 z?? #	0CCCCdCCCK)4):):++K A%%eK((|39:::!!+C!;!;BAADV4444444   FF
 __ 	0!   &%%%%% x1}}8S))xVG$///Fs   A$EEEc                x   t          t          | j                  }| j        }t	          ||d          }t          |          r^t          j        |          }g |j        |j	        R }| j
        dk    rd|vs|dv rt          d| d          d|v r| j
        | j        d<    | j        ||g| j        R i | j        S )zy
        Compute apply in case of a string.

        Returns
        -------
        result: Series or DataFrame
        Nr   r2   )corrwithskewz
Operation z does not support axis=1)r   rU   rP   r0   re   rb   inspectgetfullargspecr<   
kwonlyargsr2   rQ   r=   r   )rW   rP   r0   r1   sig	arg_namess         rB   r_   zApply.apply_str  s     dfh
 sAt$$D>> 	0(..C4#(4S^44IyA~~i''10D+D+D !Ia!I!I!IJJJ""&*iF#2t23UDIUUUUUUrD   c                X     | j         j        | j        | j        g| j        R i | j        S )z
        Compute apply in case of a list-like or dict-like.

        Returns
        -------
        result: Series, DataFrame, or None
            Result when self.f is a list-like or dict-like, None otherwise.
        )r0   r   rP   r2   r<   r=   r[   s    rB   apply_multiplezApply.apply_multiple  s3     "tx!$&$)OdiOOO4;OOOrD   r   rU   r1   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    rt          |                                          t          |j                  z
  }t          |          dk    r<t          t          t          |                              }t          d| 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.
        )r\   rh   ru   rh   c              3  :   K   | ]\  }}t          |          V  d S rN   )r"   rn   _ro   s      rB   	<genexpr>z/Apply.normalize_dictlike_arg.<locals>.<genexpr>  s,      ==1LOO======rD   c              3  :   K   | ]\  }}t          |          V  d S rN   )r    r   s      rB   r   z/Apply.normalize_dictlike_arg.<locals>.<genexpr>  s,      ;;da,q//;;;;;;rD   znested renamer is not supportedr:   r   z
Column(s) z do not existc              3  >   K   | ]\  }}t          |          V  d S rN   )rR   )rn   r   rO   aggregator_typess      rB   r   z/Apply.normalize_dictlike_arg.<locals>.<genexpr>  s2      HH41az!-..HHHHHHrD   )rR   r&   r   r   r   rs   setr   r   r   r   r'   KeyErrortupledict)
rW   r   r0   r1   colscols_sortednew_funcr   ro   r   s
            @rB   r   zApply.normalize_dictlike_arg  s    33333 5LL3	** ==

=====  ;;djjll;;;;; 
 %%FGGG8q==tyy{{##c#+&6&66D4yy1}}"9T$ZZ#8#899FKFFFGGG %. HHHH4::<<HHHHH 	(*H

 $ $1!!%566 $#$#HQKK"#HQKKDrD   rg   c                   t          |t                    sJ t          ||d          }|Mt          |          r ||i |S t	          |          dk    sJ t	          d |D                       dk    sJ |S t          t
          |d          }|t          |d          r ||g|R i |S t          d| dt          |          j	         d          )z
        if arg is a string, then try to operate on it:
        - try to find a function (or attribute) on ourselves
        - try to find a numpy function
        - raise
        Nr   c                    g | ]}|d v|	S )r   rI   )rn   kwargs     rB   r   z8Apply._try_aggregate_string_function.<locals>.<listcomp>:  s"    KKK%U(5J5J5J5J5JrD   	__array__'z' is not a valid function for 'z' object)
rR   rU   re   rb   r   rS   hasattrAttributeErrortype__name__rf   s         rB   r   z$Apply._try_aggregate_string_function)  s    #s#####Cd##={{ *q$)&))) t99>>>>KK6KKKLLPQQQQQHBT""=WS+66=1S*4***6***PPPDII4FPPP
 
 	
rD   N)r0   r   r3   r4   r5   r6   r7   rG   r7   rY   )r7   r]   )r   rU   r0   rY   r1   r   r7   r   )rg   rU   )r   
__module____qualname____annotations__rX   abcabstractmethodr\   rh   ru   rv   rw   ra   r`   r_   r   r   r   rI   rD   rB   rF   rF   d   s3        MMM$  $  $  $ L 	      >A A A AF' ' '0. . . .,S S S Sj^ ^ ^ ^@V V V V8	P 	P 	P 	P* * * *X
 
 
 
 
 
rD   rF   )	metaclassc                  N    e Zd ZU dZded<   ed	d            Zed	d            ZdS )
NDFrameApplyzg
    Methods shared by FrameApply and SeriesApply but
    not GroupByApply or ResamplerWindowApply
    rY   r0   r7   r+   c                    | j         j        S rN   )r0   r{   r[   s    rB   r{   zNDFrameApply.indexO  s    x~rD   c                @    | j                             | j                  S rN   )r0   _get_agg_axisr2   r[   s    rB   agg_axiszNDFrameApply.agg_axisS  s    x%%di000rD   Nr7   r+   )r   r   r   __doc__r   propertyr{   r   rI   rD   rB   r   r   G  sl          
    X 1 1 1 X1 1 1rD   r   c                  ~    e Zd ZU ded<   eej        dd                        Zeej        dd                        Zeej        dd                        Z	ej        d d            Z
edd            Zedd            Zed             Zed!d            Zd"dZ fdZd Zd Zd#dZd Zd$dZd dZd" fdZ xZS )%r8   r*   r0   r7   r+   c                    d S rN   rI   r[   s    rB   result_indexzFrameApply.result_index^  	     	rD   c                    d S rN   rI   r[   s    rB   result_columnszFrameApply.result_columnsc  r   rD   Iterator[Series]c                    d S rN   rI   r[   s    rB   series_generatorzFrameApply.series_generatorh  r   rD   r   ResType	res_indexrY   c                    d S rN   rI   rW   r   r   s      rB   wrap_results_for_axisz FrameApply.wrap_results_for_axism  s	     	rD   c                    | j         S rN   )r   r[   s    rB   res_columnszFrameApply.res_columnsu  s    ""rD   c                    | j         j        S rN   )r0   r   r[   s    rB   r   zFrameApply.columnsy  s    xrD   c                    | j         j        S rN   )r0   r   r[   s    rB   r   zFrameApply.values}      xrD   r,   c                    | j         j        S rN   )r0   dtypesr[   s    rB   r
  zFrameApply.dtypes  r  rD   c                R   t          | j                  r|                                 S t          | j                  dk    r,t          | j                  dk    r|                                 S t          | j        t                    r| 	                                S t          | j        t          j                  rnt          j        d          5  | j        j                            d| j                  }ddd           n# 1 swxY w Y   | j                            |          S | j        dk    r|                     | j                  S t'          | j        j                  s|                                 S | j        r|                                 S |                                 S )	zcompute the resultsr   ignorer   r\   )r1   NdatarK   )r"   rP   r   r   r   r{   apply_empty_resultrR   rU   r_   rS   rT   errstater0   _mgrr\   _constructorr5   apply_broadcastr   shaper3   	apply_rawapply_standard)rW   r   s     rB   r\   zFrameApply.apply  s     	)&&((( t|!!c$*oo&:&:**,,, dfc"" 	7>>### )) 	7*** D D(---gDF-CCD D D D D D D D D D D D D D D 8((g(666 {**''111 TX^$$ 	$**,,, X 	$>>###""$$$s   'DD	D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:   r<   )	r0   r2   rt   superrh   r\   rV   r<   r=   )rW   r0   r2   r~   	__class__s       rB   rh   zFrameApply.agg  s    hy  $yA~~48848:		WW[[]]FDHDII DHDI199!'!3VXXF>#TX^DKUUDIUUUF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    r+|                      |g t          j	                            }n/|                      || j
        t          j	                            }t          ||           }n# t          $ r Y nw xY w|rlt          | j                  r+|                      |g t          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
        )rJ   NrJ   r   r   dtype)r{   r  r{   )rb   rP   r5   r0   copyr   r,   r2   rS   float64r   rR   ry   r   r   nan_constructor_sliced)rW   should_reducer,   r   s       rB   r  zFrameApply.apply_empty_result  sh     #3338==??" (H4!!!!!! 		::9>>vvb
;;;<<AAvvDL
KKKLLA %/q&$9$9 9    
  	#4=!! FF66"BJ77788F8///GGG8==??"s   A%C 
CCc                
   d }t          j         || j                  | j        | 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 )Nr  )rR   rU   rS   arrayobject)r<   r=   r~   r1   s      rB   wrapperz<FrameApply.apply_raw.<locals>.wrap_function.<locals>.wrapper  sB    t.v..fc** <XfF;;;FrD   rI   )r1   r)  s   ` rB   wrap_functionz+FrameApply.apply_raw.<locals>.wrap_function  s#         NrD   r   r{   r   r  )rS   apply_along_axisrP   r2   r   rs   r0   r  r{   r   r"  r   )rW   r*  r~   s      rB   r  zFrameApply.apply_raw  s    	 	 	 $]]46%:%:DIt{SS ;!8((tz4<(XXX8//dm/LLLrD   targetc                   t          | j                  sJ t          j        |j                  }|j        d         }t          |j                  D ]\  }}|                     ||                   }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+  )rb   rP   rS   
empty_liker   r  r   r   asarrayrs   rQ   r   r0   r  r{   )	rW   r-  result_valuesresult_compareirr   resaresr~   s	            rB   r  zFrameApply.apply_broadcast  s    fm44  a// 	& 	&FAs&&%%C:c??'D axx !=>>>qyy!SXX--$%>???"%M!!!Q$ &&v~ ' 
 
 rD   c                \    |                                  \  }}|                     ||          S rN   )apply_series_generatorwrap_resultsr  s      rB   r  zFrameApply.apply_standard  s0    !88::   )444rD   tuple[ResType, Index]c                v   t          | j                  sJ | j        }| j        }i }t	          dd           5  t          |          D ]W\  }}|                     |          ||<   t          ||         t                    r||                             d          ||<   X	 d d d            n# 1 swxY w Y   ||fS )Nzmode.chained_assignmentF)deep)	rb   rP   r   r   r   r   rR   r&   r  )rW   
series_genr   r   r3  ro   s         rB   r7  z!FrameApply.apply_series_generator#  s   *
%	5t<< 	= 	=!*-- = =1!VVAYY
gaj)44 = ")e!<!<GAJ=	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	!!s   A(B,,B03B0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   r  )
r   r,   r   r#   r  r0   r"  rS   r   r{   )rW   r   r   r,   constructor_slicedr~   s         rB   r8  zFrameApply.wrap_results6  s    !!!!!! w<<!WWQZ1H1H--gyAAA "X9w<<1!3v!=!=''rzBBBFF''00F rD   c                    | j         dk    r5| j        }|j        | j                 }|                    || j                  S t                                                      S )Nsizer  )rP   r0   r  r2   r"  r   r  r_   )rW   r0   valuer  s      rB   r_   zFrameApply.apply_strK  sX     6V(CIdi(E**5*FFFww  """rD   r   )r7   r   r   r   r   r+   r7   rY   r7   r,   r   r-  r*   r7   r*   )r7   r9  )r   r   r   r   r   r   r   r   r   r   r  r  r   r   r   r
  r\   rh   r  r  r  r  r7  r8  r_   __classcell__r  s   @rB   r8   r8   X  s        NNN
     X     X     X 	    # # # X#       X    ^    ^!% !% !% !%F    .&# &# &#PM M M4   85 5 5" " " "&   *# # # # # # # # # #rD   c                  l    e Zd ZU dZded<   ed             Zedd            Zedd            ZddZ	dS )r?   r   r   r2   c                ^      fdt          t           j                            D             S )Nc              3  P   K   | ] }j                             |d           V  !dS )r:   r   N)r0   _ixs)rn   r3  rW   s     rB   r   z1FrameRowApply.series_generator.<locals>.<genexpr>[  s5      KKQaa((KKKKKKrD   )ranger   r   r[   s   `rB   r   zFrameRowApply.series_generatorY  s/    KKKK%DL8I8I2J2JKKKKrD   r7   r+   c                    | j         S rN   r   r[   s    rB   r   zFrameRowApply.result_index]  
    |rD   c                    | j         S rN   r  r[   s    rB   r   zFrameRowApply.result_columnsa  
    zrD   r   r   r   rY   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 rowsrJ   Nc              3  @   K   | ]}t          |t                    V  d S rN   )rR   r   )rn   rO   s     rB   r   z6FrameRowApply.wrap_results_for_axis.<locals>.<genexpr>p  s=       .
 .
$%Jq$.
 .
 .
 .
 .
 .
rD   r  z%All arrays must be of the same lengthr   )r5   r0   r"  r{   r   r   r  rQ   rU   rR   r&   r   r  r   )rW   r   r   r4  r~   r   s         rB   r  z#FrameRowApply.wrap_results_for_axise  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   rB  )
r   r   r   r2   r   r   r   r   r   r  rI   rD   rB   r?   r?   V  s         DL L XL    X    X' ' ' ' ' 'rD   r?   c                       e Zd ZU dZded<   d fdZed             Zedd
            Zedd            Z	ddZ
ddZ xZS )r@   r:   r   r2   r-  r*   r7   c                ^    t                                          |j                  }|j        S rN   )r  r  rt   )rW   r-  r~   r  s      rB   r  z FrameColumnApply.apply_broadcast  s#    ((22xrD   c              #    K   | j         }t          |          }t          |          dk    sJ | j                            dd          }|j        }t          |j                  rA| j        }t          t          |                    D ]}|                    |d          V  d S t          || j
                  D ]A\  }}||_        |                    |           t                              |d|           |V  Bd S )Nr   r   _name)r   r)   r   r0   rJ  r  r!   r  rK  zipr{   
set_valuesr(  __setattr__)rW   r   sermgrr0   r3  arrr   s           rB   r   z!FrameColumnApply.series_generator  s     /776{{Q hmmAAm&&h#CI.. 	 (C3s88__ * *hhqqh))))))* * !44  	Ts###""3666				 rD   r+   c                    | j         S rN   r  r[   s    rB   r   zFrameColumnApply.result_index  rP  rD   c                    | j         S rN   rM  r[   s    rB   r   zFrameColumnApply.result_columns  rN  rD   r   r   r   rY   c                    | j         dk    r|                     ||          }nSt          |d         t                    s"| j                            |          }||_        n|                     ||          }|S )z"return the results for the columnsrL   r   )r5   infer_to_same_shaperR   r&   r0   r"  r{   rW   r   r   r~   s       rB   r  z&FrameColumnApply.wrap_results_for_axis  s|     x''--gyAAFF GAJ	22 	BX11'::F$FLL --gyAAFrD   c                    | j                             |          }|j        }||_        |                    d          }|S )z7infer the results to the same shape as the input objectr  Fr  )r0   r  rt   r{   infer_objectsra  s       rB   r`  z$FrameColumnApply.infer_to_same_shape  sG    &&G&44 ! %%5%11rD   rD  r   rB  )r   r   r   r+   r7   r*   )r   r   r   r2   r   r  r   r   r   r   r  r`  rE  rF  s   @rB   r@   r@     s         D        X2    X    X   *       rD   r@   c                  \     e Zd ZU ded<   dZded<   d fdZddZ fdZddZddZ	 xZ
S )SeriesApplyr,   r0   r   r   r2   r1   r   convert_dtyper4   r7   rG   c                d    || _         t                                          ||dd ||           d S NFr;   )rg  r  rX   )rW   r0   r1   rg  r<   r=   r  s         rB   rX   zSeriesApply.__init__  sJ     + 	 	
 	
 	
 	
 	
rD   rY   c                2   | j         }t          |          dk    r|                                 S t          | j                  r|                                 S t          | j        t                    r|                                 S | 	                                S )Nr   )
r0   r   r  r"   rP   r   rR   rU   r_   r  rW   r0   s     rB   r\   zSeriesApply.apply  s    hs88q==**,,,  	)&&(((dfc"" 	$>>### ""$$$rD   c                H   t                                                      }|~| j        }| j        }t	          |          sJ |                    dd            	 | j                            |          }n-# t          t          t          f$ r  || j                  }Y nw xY w|S )N_level)r  rh   rP   r=   rb   popr0   r\   rQ   r   rx   )rW   r~   rP   r=   r  s       rB   rh   zSeriesApply.agg  s    >A[F A;; JJx&&&%**	: % % %48% s   A5 5'BBc                |    | j         }|                    |j        |j                                      |d          S )N)r  r{   r\   method)r0   r  r  r{   __finalize__rk  s     rB   r  zSeriesApply.apply_empty_result  sC    hcisyAANN O 
 
 	
rD   c                   t          t          | j                  }| j        }t	          j        d          5  t          |t          j                  r ||          cd d d            S t          |j	                  r0t          |j        d          r|j                            |          }n;|                    t                    j        }t          j        ||| j                  }d d d            n# 1 swxY w Y   t%          |          rDt          |d         t&                    r)|                    t+          |          |j                  S |                    ||j                                      |d          S )	Nr  r  map)convertr   r  r\   rp  )r   r	   rP   r0   rS   r  rR   rT   r!   r  r   _valuesrt  astyper(  r   	map_inferrg  r   r&   _constructor_expanddimr   r{   r  rr  )rW   rP   r0   mappedr   s        rB   r  zSeriesApply.apply_standard%  s   46""h[X&&& 	 	!RX&& qvv	 	 	 	 	 	 	 	
 (	22 	ws{E7R7R 	++F++3 .  	 	 	 	 	 	 	 	 	 	 	 	 	 	 	  v;; 	:fQi;; 	 --d6ll#)-LLL##F#)#<<IIG J   s   %C4)A?C44C8;C8)r0   r,   r1   r   rg  r4   r7   rG   r   rC  )r   r   r   r   r2   rX   r\   rh   r  r  rE  rF  s   @rB   rf  rf    s         KKKD
 
 
 
 
 
&% % % %"    8
 
 
 
       rD   rf  c                  ,     e Zd Zd
 fdZd Zd	 Z xZS )GroupByApplyr0   GroupBy[NDFrameT]r1   r   r7   rG   c                    |                                 }|j                            |                    dd                    | _        t                                          ||dd ||           d S )Nr2   r   Fr;   )r  r0   r>   getr2   r  rX   rW   r0   r1   r<   r=   r  s        rB   rX   zGroupByApply.__init__E  st     G,,VZZ-B-BCC	 	 	
 	
 	
 	
 	
rD   c                    t           rN   r   r[   s    rB   r\   zGroupByApply.applyW      !!rD   c                    t           rN   r  r[   s    rB   ru   zGroupByApply.transformZ  r  rD   )r0   r}  r1   r   r7   rG   )r   r   r   rX   r\   ru   rE  rF  s   @rB   r|  r|  D  s[        
 
 
 
 
 
$" " "" " " " " " "rD   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   r2   Resampler | BaseWindowr0   r1   r   r7   rG   c                V    t                                          ||dd ||           d S ri  )r  rX   r  s        rB   rX   zResamplerWindowApply.__init__b  sB     	 	 	
 	
 	
 	
 	
rD   c                    t           rN   r  r[   s    rB   r\   zResamplerWindowApply.applyr  r  rD   c                    t           rN   r  r[   s    rB   ru   zResamplerWindowApply.transformu  r  rD   )r0   r  r1   r   r7   rG   )	r   r   r   r2   r   rX   r\   ru   rE  rF  s   @rB   r  r  ^  sz         D
 
 
 
 
 
 " " "" " " " " " "rD   r  AggFuncType | NoneNtuple[bool, AggFuncType | None, list[str] | None, npt.NDArray[np.intp] | None]c                (   | du ot          di |}d}d}|sbt          | t                    r<t          |           t          t	          |                     k    rt          d          | t          d          |rt          |          \  } }}|| ||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: list 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)
    NzFFunction names must be unique if there is no new column names assignedz4Must provide 'func' or tuples of '(column, aggfunc).rI   )is_multi_agg_with_relabelrR   r   r   r   r   rx   normalize_keyword_aggregation)r1   r=   
relabelingr   orders        rB   reconstruct_funcr  y  s    N E";"E"Ef"E"EJ $G)-E 
TdD!! 	c$ii#c$ii..&@&@ %   <RSSS E<VDDgutWe++rD   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)rR   r   r   rm   s     rB   r   z,is_multi_agg_with_relabel.<locals>.<genexpr>  s;      MMz!U##3A!MMMMMMrD   r   )r   r   r   )r=   s    rB   r  r    s=    * MMV]]__MMMMM FarD   r=   r   ,tuple[dict, list[str], npt.NDArray[np.intp]]c                   ddl m} t          t                    }g }t          t	          |                                            \  }}|D ]K\  }}||                             |           |                    |t          j        |          p|f           Lt          |          }d |                                D             }	t          |	          }
 ||
          
                    |          }|||fS )aL  
    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 : List[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 rI   rk   )rn   columnaggfuncsaggfuncs       rB   r   z1normalize_keyword_aggregation.<locals>.<listcomp>  sX       FH   
&w//:7;   rD   )pandas.core.indexes.baser+   r   r   rW  r   r   rc   rl   _make_unique_kwarg_listget_indexer)r=   r+   aggspecr  r   pairsr  r  uniquified_orderaggspec_orderuniquified_aggspeccol_idx_orders               rB   r  r    s   4 /..... 't,,GE#v||~~.//NGU  J Jw'''fc3G<<GHIIII /u55
  '  M
 1?? E,--99:JKKMG]**rD   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   r   N)count)rn   r3  pairr  s      rB   r   z+_make_unique_kwarg_list.<locals>.<listcomp>  sv       At :=419L9LaT!W44s2A2w}}T224455RV  rD   )r   )r  s   `rB   r  r    s4        ~~   rD   r~   rY   dict[str, list[Callable | str]]r   Iterable[Hashable]r  Iterable[int]dict[Hashable, Series]c                :   ddl m} d t          t          ||          d           D             }i }d}t	          | t
                     ot          | j                  dk    }|                                D ]\  }	}
| |	         	                                }|r7d |
D             }
 ||j
                                      |
          }||         }|||t          |
          z            |_
        |                    |d	          ||	<   |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:
    ---------
    >>> result = DataFrame({"A": [np.nan, 2, np.nan],
    ...       "C": [6, np.nan, np.nan], "B": [np.nan, 4, 2.5]})  # doctest: +SKIP
    >>> funcs = {"A": ["max"], "C": ["max"], "B": ["mean", "min"]}
    >>> columns = ("foo", "aab", "bar", "dat")
    >>> order = [0, 1, 2, 3]
    >>> _relabel_result(result, func, columns, order)  # doctest: +SKIP
    dict(A=Series([2.0, NaN, NaN, NaN], index=["foo", "aab", "bar", "dat"]),
         C=Series([NaN, 6.0, NaN, NaN], index=["foo", "aab", "bar", "dat"]),
         B=Series([NaN, NaN, 2.5, 4.0], index=["foo", "aab", "bar", "dat"]))
    r   r   c                    g | ]
}|d          S )r   rI   )rn   r  s     rB   r   z"relabel_result.<locals>.<listcomp><  s)       Q  rD   c                    | d         S )Nr:   rI   )ts    rB   <lambda>z relabel_result.<locals>.<lambda>=  s
    ad rD   )r   r:   c                d    g | ]-}t          |t                    st          j        |          n|.S rI   )rR   rU   rc   rl   )rn   rP   s     rB   r   z"relabel_result.<locals>.<listcomp>[  sD       NO
1c0B0BI%a(((  rD   Frc  )r  r+   sortedrW  rR   r&   r   r   r   dropnar{   r  reindex)r~   r1   r   r  r+   reordered_indexesreordered_result_in_dictidxreorder_maskrr   funsr  s                rB   relabel_resultr    sQ   : /..... "3w#6#6NNKKK   8:
C!&)444PV^9L9Lq9PLJJLL " "S3K  ,  	! SV  C "E!'NN66s;;M- A $C#C.$89()		'	(F(F %CHHn##rD   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   rc   rl   r   r   r   )r  r3  mangled_aggfuncsr  s       rB   _managle_lambda_listr  p  s    $ 8}}	A ) ) ))Z77g&&G.!GFA((((rD   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   r  )r  is_dictmangled_aggspecr   r  r  s         rB   maybe_mangle_lambdasr    s    2 8$$G |H-- $d8nn&&O 	9%^^-- 	4 	4MCH%% ,l8.D.D ,#7#A#A  #+ #3OC  	4 /x88rD   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-provied 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   rR   rU   rb   rx   formatr   r   r   )r=   tuple_given_messager   r1   col_funcno_arg_messages         rB   validate_func_kwargsr    s    . J6llGDMMOO  8S)) 	QXh-?-? 	Q/66tH~~7NOOPPPH (M'''D=rD   )r   FNNN)r0   r*   r1   r   r2   r   r3   r4   r5   r6   r7   r8   )r1   r  r7   r  )r7   r4   )r=   r   r7   r  )r  r  r7   r  )
r~   rY   r1   r  r   r  r  r  r7   r  )r  r  r7   r  )r  r   r7   r   )r=   r   r7   r  )]
__future__r   r   collectionsr   
contextlibr   	functoolsr   r   typingr   r   r	   r
   r   r   r   r   r   r   r   r   numpyrS   pandas._configr   pandas._libsr   pandas._typingr   r   r   r   r   r   r   r   pandas.errorsr   pandas.util._decoratorsr   pandas.core.dtypes.castr   pandas.core.dtypes.commonr    r!   r"   r#   pandas.core.dtypes.genericr$   r%   r&   pandas.core.algorithmsr'   pandas.core.baser(   pandas.core.commoncorecommonrc   pandas.core.constructionr)   r   r*   r+   r,   pandas.core.groupbyr-   pandas.core.resampler.   pandas.core.window.rollingr/   intr   rC   ABCMetarF   r   r8   r?   r@   rf  r|  r  r  r  r  r  r  r  r  r  rI   rD   rB   <module>r     sU   " " " " " " 



 # # # # # # " " " " " "                                       ) ) ) ) ) )      	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 - , , , , , 2 2 2 2 2 2 4 4 4 4 4 4                     - , , , , , + + + + + +                   C C C C C C 6         
 ,+++++......555555 sCx. "	    6`
 `
 `
 `
 `
ck `
 `
 `
 `
F1 1 1 1 15 1 1 1"{# {# {# {# {# {# {# {#|6 6 6 6 6J 6 6 6rI I I I Iz I I IXf f f f f, f f fR" " " " "5 " " "4" " " " "5 " " "6:, :, :, :,z   48+ 8+ 8+ 8+v   $I$ I$ I$ I$f   B) ) ) )X! ! ! ! ! !rD   