o
    ҷh                     @  s  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	m
Z
mZmZmZmZ d dlZd dlZd dlmZ d dlmZ 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& d dl'm(Z(m)Z)m*Z* d dl+m,Z,m-Z- d dl.m/Z/m0Z0m1Z1 d dl2m3  m4Z5 d dl6m7Z7 e	rd dl8m9Z9m:Z:m;Z;m<Z< d dl=m>Z>m?Z?m@Z@ d dlAmBZB d dlCmDZD d dlEmFZF eGeHe
f ZI	 					dkdld&d'ZJG d(d) d)ejKd*ZLG d+d, d,eLZMG d-d% d%eMZNG d.d/ d/eNZOG d0d1 d1eNZPG d2d3 d3eMZQG d4d5 d5eLZRG d6d7 d7eRZSdmd:d;ZTdnd<d=ZUdodAdBZVdpdEdFZWdqdOdPZXdrdQdRZYdsdUdVZZdtdYdZZ[dud\d]Z\dvdbdcZ]dwdidjZ^dS )x    )annotationsN)defaultdict)partial)TYPE_CHECKINGAnyCallableDefaultDictLiteralcast)option_context)lib)AggFuncTypeAggFuncTypeBaseAggFuncTypeDict
AggObjTypeAxisAxisIntNDFrameTnpt)SpecificationError)cache_readonly)find_stack_level)is_nested_object)is_dict_likeis_list_likeis_sequence)CategoricalDtypeExtensionDtype)ABCDataFrame
ABCNDFrame	ABCSeries)ensure_wrapped_if_datetimelike)HashableIterableIteratorSequence)	DataFrameIndexSeries)GroupBy)	Resampler)
BaseWindowFcompatobjr&   funcr   axisr   rawboolresult_type
str | Noneby_rowLiteral[False, 'compat']return
FrameApplyc           
   	   C  s^   |  |}|dkrt}n|dkrt}t|fi |\}	}}	}	|dus$J || ||||||dS )z=construct and return a row or column based frame apply objectr      Nr0   r2   r4   argskwargs)_get_axis_numberFrameRowApplyFrameColumnApplyreconstruct_func)
r-   r.   r/   r0   r2   r4   r:   r;   klass_ rB   D/var/www/html/venv/lib/python3.10/site-packages/pandas/core/apply.pyframe_applyL   s    
rD   c                   @  s   e Zd ZU ded< dddKddZejdLddZejdMddZejdMddZ	dNddZ
dLdd Zd!d" ZdLd#d$ZdLd%d&ZdOd,d-ZdPd2d3ZdLd4d5ZdQd8d9ZdRd=d>ZdLd?d@ZdLdAdBZdSdFdGZdTdHdIZdJS )UApplyr   r/   r,   r4   r-   r   r.   r   r0   r1   r2   r3   r4   #Literal[False, 'compat', '_compat']r6   Nonec                C  sZ   || _ || _|du s|dv sJ || _|pd| _|pi | _|dvr%td|| _|| _d S )NF)r,   _compatrB   )Nreduce	broadcastexpandzUinvalid value for result_type, must be one of {None, 'reduce', 'broadcast', 'expand'})r-   r0   r4   r:   r;   
ValueErrorr2   r.   selfr-   r.   r0   r2   r4   r:   r;   rB   rB   rC   __init__o   s   


zApply.__init__DataFrame | Seriesc                 C     d S NrB   rO   rB   rB   rC   apply   s   zApply.applyop_nameLiteral['agg', 'apply']c                 C  rR   rS   rB   rO   rV   rB   rB   rC   agg_or_apply_list_like      zApply.agg_or_apply_list_likec                 C  rR   rS   rB   rX   rB   rB   rC   agg_or_apply_dict_like   rZ   zApply.agg_or_apply_dict_likeDataFrame | Series | Nonec                 C  s   | j }| j}| j}| j}t|tr|  S t|r|  S t	|r%| 
 S t|r@t|}|r@|s@|s@t||| 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)r-   r.   r:   r;   
isinstancestr	apply_strr   agg_dict_liker   agg_list_likecallablecomget_cython_funcwarn_alias_replacementgetattr)rO   r-   r.   r:   r;   frB   rB   rC   agg   s    	

z	Apply.aggc              
     sP  | j }| j | j}| j}| j}|jdk}||dkr.|rJ |jj dg|R i |jS t	 rPt
 sPttt   |rGdd  D  n	 fdd|D  t
 r^tt  |  S tt  z|  }W n tyr     ty } ztd|d}~ww t|ttfr|jr|jstdt|ttfr|j|jst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.
        r8   r   c                 S  s   i | ]
}t |p
||qS rB   rc   get_callable_name.0vrB   rB   rC   
<dictcomp>   s    z#Apply.transform.<locals>.<dictcomp>c                   s   i | ]}| qS rB   rB   )rl   colr.   rB   rC   rn      s    zTransform function failedNzFunction did not transform)r-   r.   r/   r:   r;   ndimr<   T	transformr   r   r
   listr   r   transform_dict_liketransform_str_or_callable	TypeError	ExceptionrM   r]   r    r   emptyindexequals)rO   r-   r/   r:   r;   	is_seriesresulterrrB   rp   rC   rs      sL   




zApply.transformc           
      C  s   ddl m} | j}| j}| j}t|tsJ t|dkr td| 	d||}i }|
 D ]\}}|j|dd}	|	j|dg|R i |||< q-||ddS )zC
        Compute transform in the case of a dict-like func
        r   concatz$No transform functions were providedrs   r8   rq   r/   )pandas.core.reshape.concatr   r-   r:   r;   r]   r   lenrM   normalize_dictlike_argitems_gotitemrs   )
rO   r.   r   r-   r:   r;   resultsnamehowcolgrB   rB   rC   ru      s    zApply.transform_dict_likec                 C  s   | j }| j}| j}t|tr| j||g|R i |S |s2|s2t|}|r2t||| t	|| S z|j
|fd|i|W S  tyR   ||g|R i | Y S w )zL
        Compute transform in the case of a string or callable func
        r:   )r-   r:   r;   r]   r^   
_apply_strrc   rd   re   rf   rU   rx   )rO   r.   r-   r:   r;   rg   rB   rB   rC   rv     s   

zApply.transform_str_or_callablec                 C     | j ddS )z
        Compute aggregation in the case of a list-like argument.

        Returns
        -------
        Result of aggregation.
        rh   rV   )rY   rT   rB   rB   rC   ra   /     zApply.agg_list_likeselected_objSeries | DataFramer;   dict[str, Any] tuple[list[Hashable], list[Any]]c                 C  s>  t tt | j}| j}g }g }|jdkrT|D ]9}|j|jd|d}	t||	r-| j	g| j
n| j
}
t|	||g|
R i |}|| t|pI|}|| q||fS g }t|D ]:\}}|j|d|jdd|f d}	t||	ry| j	g| j
n| j
}
t|	||g|
R i |}|| || qZ|j|}||fS )a=  
        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]
            Index labels for result.
        results : list
            Data for result. When aggregating with a Series, this can contain any
            Python objects.
        r8   )rq   subsetN)r
   rt   r   r.   r-   rq   r   r   include_axisr/   r:   rf   appendrc   rj   	enumerateiloccolumnstake)rO   rV   r   r;   r.   r-   r   keysar   r:   new_resr   indicesrz   ro   rB   rB   rC   compute_list_like9  s8   


zApply.compute_list_liker   list[Hashable]r   list[Series | DataFrame]c              
   C  s|   ddl m} | j}z	|||dddW S  ty= } zddlm} ||||jd}t|r1td||W  Y d }~S d }~ww )	Nr   r   r8   F)r   r/   sortr(   rz   r   z3cannot combine transform and aggregation operations)	r   r   r-   rw   pandasr(   r   r   rM   )rO   r   r   r   r-   r~   r(   r}   rB   rB   rC   wrap_results_list_likey  s    zApply.wrap_results_list_likec                 C  r   )z
        Compute aggregation in the case of a dict-like argument.

        Returns
        -------
        Result of aggregation.
        rh   r   )r[   rT   rB   rB   rC   r`     r   zApply.agg_dict_like	selectionHashable | Sequence[Hashable]c                   st  ddl m}m} | jt||f}tt| j}| |}j	dko-j
 tj
k }	j	dkrQj|dd  fdd| D }
t| }||
fS |s|	rg }
g }| D ]A\}j
|g}j
|}tt}t||D ]\}}|| | qwfdd| D }||gt| 7 }|
|7 }
q]||
fS fd	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   r8   r   c                   s&   g | ]\}}t  |fi qS rB   )rf   )rl   rA   r   )r   r;   rV   rB   rC   
<listcomp>  s   & z+Apply.compute_dict_like.<locals>.<listcomp>c                   s:   g | ]\}}|D ]}t j|d d fi qqS )r8   r   )rf   _ixs)rl   labelr   indice)r   r;   rV   r   rB   rC   r     s    c                   s0   g | ]\}}t j|d d|fi  qS )r8   r   )rf   r   )rl   keyr   )r;   r-   rV   rB   rC   r     s    )pandas.core.groupby.genericr   r   r-   r]   r
   r   r.   r   rq   r   nuniquer   r   r   rt   r   get_indexer_forr   r   zipr   )rO   rV   r   r   r;   r   r   
is_groupbyr.   is_non_unique_colr   r   r   r   labelslabel_to_indicesrz   r   key_datarB   )r   r   r;   r-   rV   r   rC   compute_dict_like  sB   


	zApply.compute_dict_likeresult_indexresult_datart   c                   s  ddl m} ddlm} | j}dd |D }t|r]tt||  fdd|D }|g kr0|n|}|jdkrD||}	|		|j
j |	}t|trKdnd}
| fd	d
|D |
|d}|S t|retdddl m} |jdkrytd|}|j}nd }||||d}|S )Nr   r'   r   c                 S  s   g | ]}t |tqS rB   )r]   r   )rl   rrB   rB   rC   r         z0Apply.wrap_results_dict_like.<locals>.<listcomp>c                   s   g | ]	} | j s|qS rB   )ry   rl   kr   rB   rC   r     s    r   r8   c                   s   i | ]}| | qS rB   rB   r   r   rB   rC   rn     r   z0Apply.wrap_results_dict_like.<locals>.<dictcomp>)r/   r   zLcannot perform both aggregation and transformation operations simultaneouslyr   r(   r   )r   r'   r   r   r-   alldictr   rq   
_set_namesr   namesr]   r    anyrM   r(   r
   r   )rO   r   r   r   r'   r   r-   
is_ndframekeys_to_usektur/   r}   r(   r   rB   r   rC   wrap_results_dict_like  s<   


zApply.wrap_results_dict_likec           	      C  s   t t| j}| j}ddlm}m} t||d}t|ret	
|}g |j|jR }| jdkr>d|vs6|dv r>td| dd|v ret|||fr_d}|dv rS| jj}|| jkr^| j| jd< n| 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   Nr/   )corrwithskewz
Operation z does not support axis=1)idxmaxidxmin)r
   r^   r.   r-   r   r   r   rf   rb   inspectgetfullargspecr:   
kwonlyargsr/   rM   r]   r;   r   )	rO   r.   r-   r   r   methodsig	arg_namesdefault_axisrB   rB   rC   r_     s(   	


zApply.apply_strc                 C  s~   | j dkrt| jtr| jjj| jdfd| ji| jjS | j}| j}t	|r.| j
dd}n| jd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.
        r8   r   r:   rU   r   )r/   r]   r-   r   rr   rU   r.   r:   r;   r   r[   rY   reconstruct_and_relabel_result)rO   r.   r;   r}   rB   rB   rC   apply_list_or_dict_likeL  s   	$zApply.apply_list_or_dict_liker   r^   r   c           	        s  |dv sJ |dkrt |trtdd | D s%tdd | D r)td|jdkrRdd	lm} |t|	 j
|jd
d}t|dkrRtdt| dtttf t fdd| D ri }| D ]\}}t | sy|g||< qj|||< qj|}|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.
        )rU   rh   rs   rh   c                 s      | ]	\}}t |V  qd S rS   )r   rl   rA   rm   rB   rB   rC   	<genexpr>t      z/Apply.normalize_dictlike_arg.<locals>.<genexpr>c                 s  r   rS   )r   r   rB   rB   rC   r   u  r   znested renamer is not supportedr8   r   r   T)r   z
Column(s) z do not existc                 3  s    | ]
\}}t | V  qd S rS   )r]   )rl   rA   xaggregator_typesrB   rC   r     s    )r]   r    r   r   r   rq   r   r'   rt   r   
differencer   r   KeyErrortupler   )	rO   r   r-   r.   r'   colsnew_funcr   rm   rB   r   rC   r   d  s.   




zApply.normalize_dictlike_argc                 O  s   t |tsJ t||r3t||}t|r||i |S t|dks$J tdd |D dks1J |S tt|rMt|drMt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                 S  s   g | ]}|d vr|qS )r   rB   )rl   kwargrB   rB   rC   r     s    z$Apply._apply_str.<locals>.<listcomp>	__array__'z' is not a valid function for 'z' object)
r]   r^   hasattrrf   rb   r   nptype__name__AttributeError)rO   r-   r.   r:   r;   rg   msgrB   rB   rC   r     s   


zApply._apply_strN)r-   r   r.   r   r0   r1   r2   r3   r4   rG   r6   rH   r6   rQ   rV   rW   r6   rQ   )r6   r\   )rV   rW   r   r   r;   r   r6   r   )r   r   r   r   )
rV   rW   r   r   r   r   r;   r   r6   r   )r   r   r   r   r   rt   )r   r^   r-   rQ   r.   r   r6   r   )r.   r^   )r   
__module____qualname____annotations__rP   abcabstractmethodrU   rY   r[   rh   rs   ru   rv   ra   r   r   r`   r   r   r_   r   r   r   rB   rB   rB   rC   rE   l   s0   
 	

 C




@



O
6
/
-rE   )	metaclassc                   @  sJ   e Zd ZU dZded< edddZeddd	ZdddZdddZ	dS )NDFrameApplyzg
    Methods shared by FrameApply and SeriesApply but
    not GroupByApply or ResamplerWindowApply
    rQ   r-   r6   r'   c                 C     | j jS rS   )r-   rz   rT   rB   rB   rC   rz        zNDFrameApply.indexc                 C  s   | j | jS rS   )r-   _get_agg_axisr/   rT   rB   rB   rC   agg_axis  s   zNDFrameApply.agg_axisrV   rW   c                 C  s   | j }| j}|dkr*t| tr| j}nt| tr | jrdnd}nd}i |d|i}t|dddkr6td| |||\}}| 	||}|S )	NrU   rI   Fr4   r/   r   r8   "axis other than 0 is not supported)
r-   r;   r]   r7   r4   SeriesApplyrf   NotImplementedErrorr   r   )rO   rV   r-   r;   r4   r   r   r}   rB   rB   rC   rY     s   

z#NDFrameApply.agg_or_apply_list_likec           	      C  s|   |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rh   rU   rU   rI   Fr4   r/   r   r8   r   )r-   r4   updaterf   r   r   r   )	rO   rV   r-   r;   r4   r   r   r   r}   rB   rB   rC   r[     s   z#NDFrameApply.agg_or_apply_dict_likeNr6   r'   r   )
r   r   r   __doc__r   propertyrz   r   rY   r[   rB   rB   rB   rC   r     s   
 
r   c                      s   e Zd ZU ded< ddd: fddZeejd;ddZeejd;ddZ	eejd<ddZ
ejd=ddZed;d d!Zed;d"d#Zed$d% Zd>d&d'Z fd(d)Zd*d+ Zd,d- Zd?d/d0Zd1d2 Zd@d4d5Zd=d6d7Zd> fd8d9Z  ZS )Ar7   r&   r-   FrF   r   r.   r   r0   r1   r2   r3   r4   r5   r6   rH   c             	     s>   |dur|dkrt d| dt j|||||||d d S )NFr,   zby_row=z not allowed)r4   r:   r;   )rM   superrP   rN   	__class__rB   rC   rP     s
   
zFrameApply.__init__r'   c                 C  rR   rS   rB   rT   rB   rB   rC   r        zFrameApply.result_indexc                 C  rR   rS   rB   rT   rB   rB   rC   result_columns  r  zFrameApply.result_columnsIterator[Series]c                 C  rR   rS   rB   rT   rB   rB   rC   series_generator  r  zFrameApply.series_generatorr   ResType	res_indexrQ   c                 C  rR   rS   rB   rO   r   r  rB   rB   rC   wrap_results_for_axis  rZ   z FrameApply.wrap_results_for_axisc                 C     | j S rS   )r  rT   rB   rB   rC   res_columns     zFrameApply.res_columnsc                 C  r   rS   )r-   r   rT   rB   rB   rC   r     r   zFrameApply.columnsc                 C  r   rS   )r-   valuesrT   rB   rB   rC   r     r   zFrameApply.valuesc                 C  s   t | jr	|  S t| jdkrt| jdkr|  S t| jtr%| 	 S t| jt
jrUt
jdd | jjjd| jd}W d   n1 sGw   Y  | jj||jdS | jdkr`| | jS t| jjsj|  S | jrq|  S |  S )	zcompute the resultsr   ignorer   rU   rp   N)axesrK   )r   r.   r   r   r   rz   apply_empty_resultr]   r^   r_   r   ufuncerrstater-   _mgrrU   _constructor_from_mgrr  r2   apply_broadcastr   shaper0   	apply_rawapply_standard)rO   r   rB   rB   rC   rU   $  s$   

zFrameApply.applyc                   s   | j }| j}| jdkr| j n| j j| _ d| _d }zt  }W || _ || _n|| _ || _w |dkr:|d ur8|jn|}|d u rN| j j| j|fd| ji| j}|S )Nr   r8   r:   )	r-   r/   rr   r  rh   rU   r.   r:   r;   )rO   r-   r/   r}   r  rB   rC   rh   G  s     zFrameApply.aggc                 C  s  t | jsJ | jdvr| j S | jdk}ddlm} |s]z/| jdkr8| j|g tj	dg| j
R i | j}n| j|| jtj	dg| j
R i | j}W n	 tyV   Y nw t|| }|rt| jrx| j|g tj	dg| j
R i | j}ntj}| jj|| jd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)rz   r   rz   )rb   r.   r2   r-   copyr   r(   r/   r   float64r:   r;   r   rx   r]   r   r   nan_constructor_sliced)rO   should_reducer(   r   rB   rB   rC   r  ^  sB   




(
zFrameApply.apply_empty_resultc                 C  sR   dd }t || j| j| j}|jdkr | jj|| j| j	dS | jj
|| jdS )z$apply to the values as a numpy arrayc                   s    fdd}|S )z
            Wrap user supplied function to work around numpy issue.

            see https://github.com/numpy/numpy/issues/8352
            c                    s*    | i |}t |trtj|td}|S )Nr  )r]   r^   r   arrayobject)r:   r;   r}   rp   rB   rC   wrapper  s   
z<FrameApply.apply_raw.<locals>.wrap_function.<locals>.wrapperrB   )r.   r)  rB   rp   rC   wrap_function  s   z+FrameApply.apply_raw.<locals>.wrap_functionr   rz   r   r!  )r   apply_along_axisr.   r/   r  rq   r-   _constructorrz   r   r%  r   )rO   r*  r}   rB   rB   rC   r    s
   
zFrameApply.apply_rawtargetc           	      C  s   t | jsJ t|j}|jd }t|jD ]8\}}| j|| g| jR i | j	}t
|j}|dkr9td|dkrG|t|krGtd||d d |f< q| jj||j|jd}|S )Nr   r8   ztoo many dims to broadcastzcannot broadcast resultr+  )rb   r.   r   
empty_liker  r  r   r   r:   r;   asarrayrq   rM   r   r-   r-  rz   )	rO   r.  result_valuesresult_compareiro   resaresr}   rB   rB   rC   r    s    
 
zFrameApply.apply_broadcastc                 C  s   |   \}}| ||S rS   )apply_series_generatorwrap_resultsr  rB   rB   rC   r    s   zFrameApply.apply_standardtuple[ResType, Index]c                 C  s   t | jsJ | j}| j}i }tdd 5 t|D ]%\}}| j|g| jR i | j||< t|| t	r>|| j
dd||< qW d    ||fS 1 sLw   Y  ||fS )Nzmode.chained_assignmentF)deep)rb   r.   r
  r   r   r   r:   r;   r]   r    r"  )rO   
series_genr  r   r3  rm   rB   rB   rC   r6    s    
		z!FrameApply.apply_series_generatorc                 C  sv   ddl m} t|dkrd|v rt|d r| ||S | jj}t|dkr2||u r2||tjd}n||}||_	|S )Nr   r   r  )
r   r(   r   r   r  r-   r%  r   r#  rz   )rO   r   r  r(   constructor_slicedr}   rB   rB   rC   r7    s    zFrameApply.wrap_resultsc                   s6   | j dkr| j}|j| j }|j|| jdS t  S )Nsizer!  )r.   r-   r  r/   r%  r   r  r_   )rO   r-   valuer  rB   rC   r_     s
   

zFrameApply.apply_str)r-   r   r.   r   r0   r1   r2   r3   r4   r5   r6   rH   r  )r6   r	  r   r  r  r'   r6   rQ   r   r.  r&   r6   r&   )r6   r8  )r   r   r   r   rP   r  r   r   r   r  r
  r  r  r   r   r  rU   rh   r  r  r  r  r6  r7  r_   __classcell__rB   rB   r  rC   r7     s<   
 	

#.


c                   @  sL   e Zd ZU dZded< edd Zeddd	Zedd
dZdddZ	dS )r=   r   r   r/   c                   s    fddt t jD S )Nc                 3  s     | ]} j j|d dV  qdS )r8   r   N)r-   r   )rl   r3  rT   rB   rC   r      s    z1FrameRowApply.series_generator.<locals>.<genexpr>)ranger   r   rT   rB   rT   rC   r
    s   zFrameRowApply.series_generatorr6   r'   c                 C  r  rS   r   rT   rB   rB   rC   r     r  zFrameRowApply.result_indexc                 C  r  rS   r!  rT   rB   rB   rC   r    r  zFrameRowApply.result_columnsr   r  r  rQ   c              
   C  s   | j dkr| j|}||_|S | j du r+tdd | D r+| j|}||_|S z	| jj|d}W n$ tyX } zdt|v rS| j|}||_|W  Y d}~S  d}~ww t	|d t
snt|jt| jkrn| j|_t|jt|krz||_|S )zreturn the results for the rowsrJ   Nc                 s  s    | ]}t |tV  qd S rS   )r]   r   )rl   r   rB   rB   rC   r     s    

z6FrameRowApply.wrap_results_for_axis.<locals>.<genexpr>dataz%All arrays must be of the same lengthr   )r2   r-   r%  rz   r   r  r-  rM   r^   r]   r    r   r  r   )rO   r   r  r4  r}   r~   rB   rB   rC   r  
  s4   

z#FrameRowApply.wrap_results_for_axisNr  r>  )
r   r   r   r/   r   r  r
  r   r  r  rB   rB   rB   rC   r=     s   
 
r=   c                      sh   e Zd ZU dZded< d fddZed	d
 ZedddZedddZ	dddZ
dddZ  ZS )r>   r8   r   r/   r.  r&   r6   c                   s   t  |j}|jS rS   )r  r  rr   )rO   r.  r}   r  rB   rC   r  7  s   z FrameColumnApply.apply_broadcastc                 c  s    | j }t|}t|dksJ | jjddd}|j}t|jtr7| j}t	t|D ]
}|j|ddV  q*d S t
|| jD ]\}}||_|| t|d| |V  q=d S )Nr   r   _name)r  r!   r   r-   r   r  r]   r   r   rA  r   rz   
set_valuesr(  __setattr__)rO   r  sermgrr-   r3  arrr   rB   rB   rC   r
  ;  s"   
z!FrameColumnApply.series_generatorr'   c                 C  r  rS   r!  rT   rB   rB   rC   r   U  r  zFrameColumnApply.result_indexc                 C  r  rS   rB  rT   rB   rB   rC   r  Y  r  zFrameColumnApply.result_columnsr   r  r  rQ   c                 C  sN   | j dkr| ||}|S t|d ts| j|}||_|S | ||}|S )z"return the results for the columnsrL   r   )r2   infer_to_same_shaper]   r    r-   r%  rz   rO   r   r  r}   rB   rB   rC   r  ]  s   
z&FrameColumnApply.wrap_results_for_axisc                 C  s*   | j j|d}|j}||_|jdd}|S )z7infer the results to the same shape as the input objectrC  Fr"  )r-   r-  rr   rz   infer_objectsrL  rB   rB   rC   rK  r  s
   z$FrameColumnApply.infer_to_same_shaper?  r  r>  )r   r  r  r'   r6   r&   )r   r   r   r/   r   r  r  r
  r   r  r  rK  r@  rB   rB   r  rC   r>   4  s   
 

r>   c                      sx   e Zd ZU ded< dZded< ded< ejdd	d fddZdddZ fddZ	dddZ
dd ZdddZ  ZS ) r   r(   r-   r   r   r/   rG   r4   r,   )convert_dtyper4   r.   r   rO  bool | lib.NoDefaultr6   rH   c             	     sF   |t ju rd}n	tjdtt d || _t j||dd |||d d S )NTzthe convert_dtype parameter is deprecated and will be removed in a future version.  Do ``ser.astype(object).apply()`` instead if you want ``convert_dtype=False``.
stacklevelFr9   )	r   
no_defaultwarningswarnFutureWarningr   rO  r  rP   )rO   r-   r.   rO  r4   r:   r;   r  rB   rC   rP     s"   


zSeriesApply.__init__rQ   c                 C  sZ   | j }t|dkr|  S t| jr|  S t| jtr |  S | j	dkr)| 
 S |  S )Nr   rI   )r-   r   r  r   r.   r   r]   r^   r_   r4   apply_compatr  rO   r-   rB   rB   rC   rU     s   

zSeriesApply.applyc              
     s   t   }|d u rZ| j}| j}t|sJ z|j|fd| ji| j}W n tt	t
fy>   ||g| jR i | j}Y |S w d| dt|j dt|j d}tj|tt d |S )Nr:   zusing z in z3.agg cannot aggregate and has been deprecated. Use z&.transform to keep behavior unchanged.rQ  )r  rh   r-   r.   rb   rU   r:   r;   rM   r   rw   r   r   rT  rU  rV  r   )rO   r}   r-   r.   r   r  rB   rC   rh     s"   
	zSeriesApply.aggc                 C  s"   | j }|j|j|jdj|ddS )N)r   rz   rU   r   )r-   r-  r   rz   __finalize__rX  rB   rB   rC   r    s   zSeriesApply.apply_empty_resultc              
   C  sz   | j }| j}t|rt|}|r| js| js|j|ddS z
|j|dd}W |S  tt	t
fy<   |j|dd}Y |S w )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
        FrF   r,   )r-   r.   rb   rc   rd   r:   r;   rU   rM   r   rw   )rO   r-   r.   rg   r}   rB   rB   rC   rW    s   
zSeriesApply.apply_compatc                   s  t tj j}t tjr3tjdd  |gjR i j	W  d    S 1 s-w   Y  nj
sC |gjR i j	S jsIj	rQ fdd}n }t|jtr[dnd }|j||jd}t|r{t|d tr{|jt||jdS |j||jdj|dd	S )
Nr  r  c                   s    | gj R i jS rS   )r:   r;   )r   r.   rO   rB   rC   curried  s   z+SeriesApply.apply_standard.<locals>.curried)mapper	na_actionconvertr   r!  rU   rY  )r
   r   r.   r-   r]   r   r  r  r:   r;   r4   r   r   _map_valuesrO  r   r    _constructor_expanddimrt   rz   r-  rZ  )rO   r-   r\  actionmappedrB   r[  rC   r    s(   "zSeriesApply.apply_standard)
r-   r(   r.   r   rO  rP  r4   rG   r6   rH   r   )r6   r(   )r   r   r   r   r/   r   rS  rP   rU   rh   r  rW  r  r@  rB   rB   r  rC   r     s   
 
 
r   c                      sL   e Zd ZU ded< d fdd	Zd
d Zdd ZdddZdddZ  Z	S )GroupByApplyz GroupBy | Resampler | BaseWindowr-   GroupBy[NDFrameT]r.   r   r6   rH   c                  s:   |  }|j|dd| _t j||dd ||d d S )Nr/   r   Fr0   r2   r:   r;   )r"  r-   r<   getr/   r  rP   rO   r-   r.   r:   r;   r  rB   rC   rP     s   
zGroupByApply.__init__c                 C     t rS   r   rT   rB   rB   rC   rU   +     zGroupByApply.applyc                 C  ri  rS   rj  rT   rB   rB   rC   rs   .  rk  zGroupByApply.transformrV   rW   rQ   c                 C  s   | 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d
 | 
|||\}}W d    n1 sKw   Y  | ||}|S )NrU   r4   Fr/   r   r8   r   as_indexT	condition)r-   r;   rf   r   _selected_objrq   _obj_with_exclusionsrc   temp_setattrr   r   r   )rO   rV   r-   r;   r   r   r   r}   rB   rB   rC   rY   1  s    z#GroupByApply.agg_or_apply_list_likec                 C  s
  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r1td
|j}|j	}t
|||f}	|	rV| jdd }
| jdd }||
|d tj|ddt|dd | ||||\}}W d    n1 sww   Y  | |||}|S )Nr   r   r   rU   rI   Fr4   r/   r8   r   engineengine_kwargs)rr  rs  rl  Trm  )r   r   r   r-   r4   r   rf   r   ro  
_selectionr]   r;   rg  rc   rq  r   r   r   )rO   rV   r   r   r-   r;   r4   r   r   r   rr  rs  r   r   r}   rB   rB   rC   r[   K  s2   
z#GroupByApply.agg_or_apply_dict_like)r-   re  r.   r   r6   rH   r   )
r   r   r   r   rP   rU   rs   rY   r[   r@  rB   rB   r  rC   rd    s   
 
rd  c                      sD   e Zd ZU dZded< ded< d fd
dZdd Zdd Z  ZS )ResamplerWindowApplyr   r   r/   Resampler | BaseWindowr-   r.   r   r6   rH   c                  s    t t| j||dd ||d d S )NFrf  )r  rd  rP   rh  r  rB   rC   rP   w  s   

zResamplerWindowApply.__init__c                 C  ri  rS   rj  rT   rB   rB   rC   rU     rk  zResamplerWindowApply.applyc                 C  ri  rS   rj  rT   rB   rB   rC   rs     rk  zResamplerWindowApply.transform)r-   rv  r.   r   r6   rH   )	r   r   r   r/   r   rP   rU   rs   r@  rB   rB   r  rC   ru  s  s   
 ru  AggFuncType | NoneGtuple[bool, AggFuncType, list[str] | None, npt.NDArray[np.intp] | None]c                 K  s   | du o
t di |}d}d}|s,t| tr$t| tt| kr$td| du r,td|r5t|\} }}| dus;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: 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).rB   )is_multi_agg_with_relabelr]   rt   r   setr   rw   normalize_keyword_aggregation)r.   r;   
relabelingr   orderrB   rB   rC   r?     s   'r?   c                  K  s"   t d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                 s  s&    | ]}t |tot|d kV  qdS )r   N)r]   r   r   rk   rB   rB   rC   r     s   $ z,is_multi_agg_with_relabel.<locals>.<genexpr>r   )r   r  r   )r;   rB   rB   rC   ry    s   
ry  r;   r   ,tuple[dict, list[str], npt.NDArray[np.intp]]c                 C  s   ddl m} tt}g }tt|   \}}|D ]\}}|| | ||t|p,|f qt	|}d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                 S  s,   g | ]\}}|D ]}|t |p|fqqS rB   ri   )rl   columnaggfuncsaggfuncrB   rB   rC   r     s    z1normalize_keyword_aggregation.<locals>.<listcomp>)pandas.core.indexes.baser'   r   rt   r   r   r   rc   rj   _make_unique_kwarg_listget_indexer)r;   r'   aggspecr}  r   pairsr  r  uniquified_orderaggspec_orderuniquified_aggspeccol_idx_orderrB   rB   rC   r{    s   
r{  seqSequence[tuple[Any, Any]]c                   s    fd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                   sJ   g | ]!\}}  |d kr!|d |d   d d|  | fn|qS )r8   r   rA   N)count)rl   r3  pairr  rB   rC   r   .  s    8z+_make_unique_kwarg_list.<locals>.<listcomp>)r   r  rB   r  rC   r  "  s   
r  r}   rQ   dict[str, list[Callable | str]]r   Iterable[Hashable]r}  Iterable[int]dict[Hashable, Series]c                 C  s   ddl m} dd tt||dd dD }i }d}t| t o&t| jdk}| D ]:\}	}
| |	 	 }|rKd	d |
D }
||j
|
}|j| }|||t|
  |_
|j|d
d||	< |t|
 }q+|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                 S  s   g | ]}|d  qS )r   rB   )rl   r  rB   rB   rC   r   Y  s    z"relabel_result.<locals>.<listcomp>c                 S  s   | d S )Nr8   rB   )trB   rB   rC   <lambda>Z  s    z relabel_result.<locals>.<lambda>)r   r8   c                 S  s$   g | ]}t |tst|n|qS rB   )r]   r^   rc   rj   )rl   rg   rB   rB   rC   r   x  s    FrM  )r  r'   sortedr   r]   r    r   r   r   dropnarz   r  r   reindex)r}   r.   r   r}  r'   reordered_indexesreordered_result_in_dictidxreorder_maskro   funsr  rB   rB   rC   relabel_result4  s&   #
r  c                 K  s^   ddl m} t|fi |\}}}}|r-|d usJ |d us J t| |||}|||d} | S )Nr   )r&   r!  )r   r&   r?   r  )r}   r.   r;   r&   r|  r   r}  result_in_dictrB   rB   rC   r     s   r   r  Sequence[Any]c                 C  s\   t | dkr| S d}g }| D ]}t|dkr&t|}d| d|_|d7 }|| q|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.
    r8   r   z<lambda>z<lambda_>)r   rc   rj   r   r   r   )r  r3  mangled_aggfuncsr  rB   rB   rC   _managle_lambda_list  s   r  agg_specr   c                 C  sn   t | }|st| s| S t|  }|r1|  D ]\}}t|r(t |s(t|}n|}|||< q|S 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  rB   rB   rC   maybe_mangle_lambdas  s   


r  0tuple[list[str], list[str | Callable[..., Any]]]c                 C  sf   d}t | }g }|  D ]}t|ts!t|s!t|t|j|	| q|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.)
rt   r  r]   r^   rb   rw   formatr   r   r   )r;   tuple_given_messager   r.   col_funcno_arg_messagerB   rB   rC   validate_func_kwargs  s   r  rV   rW   r   r   c                 C  s   t |tpt |to| dkS )Nrh   )r]   r   r    )rV   r   rB   rB   rC   r     s   
r   r   r   aliasr^   rH   c                 C  sZ   | dr|}nt| j d| }d| d}tjd| d| d| dtt d d S )	Nznp.."zThe provided callable z is currently using zw. In a future version of pandas, the provided callable will be used directly. To keep current behavior pass the string z	 instead.)categoryrR  )
startswithr   r   rT  rU  rV  r   )r-   r.   r  
full_aliasrB   rB   rC   re     s   

re   )r   FNr,   NN)r-   r&   r.   r   r/   r   r0   r1   r2   r3   r4   r5   r6   r7   )r.   rw  r6   rx  )r6   r1   )r;   r   r6   r~  )r  r  r6   r  )
r}   rQ   r.   r  r   r  r}  r  r6   r  r   )r  r  r6   r  )r  r   r6   r   )r;   r   r6   r  )rV   rW   r   r   r6   r1   )r-   r   r.   r   r  r^   r6   rH   )_
__future__r   r   collectionsr   	functoolsr   r   typingr   r   r   r   r	   r
   rT  numpyr   pandas._configr   pandas._libsr   pandas._typingr   r   r   r   r   r   r   r   pandas.errorsr   pandas.util._decoratorsr   pandas.util._exceptionsr   pandas.core.dtypes.castr   pandas.core.dtypes.commonr   r   r   pandas.core.dtypes.dtypesr   r   pandas.core.dtypes.genericr   r   r    pandas.core.commoncorecommonrc   pandas.core.constructionr!   collections.abcr"   r#   r$   r%   r   r&   r'   r(   pandas.core.groupbyr)   pandas.core.resampler*   pandas.core.window.rollingr+   r   intr  rD   ABCMetarE   r   r7   r=   r>   r   rd  ru  r?   ry  r{  r  r  r   r  r  r  r   re   rB   rB   rB   rC   <module>   sx     (
     E=  9L ^

>

;

R

!
,
$