U
    sVcM                  2   @  s  d Z ddlmZ ddlZddlmZmZ ddlZddlm	Z	 ddl
Z
ddlmZmZmZmZmZ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mZmZmZm Z  dd	l!m"Z" dd
l#m$Z$ ddl%m&Z&m'Z'm(Z(m)Z) ddl*m+Z+m,Z,m-Z- ddl.m/Z/ ddl0m1Z1 erddl2m3Z3 dd Z4dd Z5dddddZ6dddddZ7dd Z8ddd d!Z9ddd"d#Z:ddd$d%Z;ddd&d'Z<d(dd)d*Z=edd,d-d.d/d0d1Z>edd2d-d3d/d4d1Z>dd2d-d3d/d5d1Z>dd6d-d.d7d8d9Z?d:d; Z@d<d=d>d?d@ZAdddAdBZBdCddDdEZCd(ddFdGdHZDdIdJ ZEdKdL ZFdMdN ZGedOdOdPdQdRZHedSdTdPdUdRZHddVdWdXdRZHdYdZd[d\d]ZId^d_ ZJd`dadbdcddZKejLdedfdgdhdiZMdjdkdldmdnZNejOejOejPejQjRejSejTjRiZUejOdoejPdpejSdqejVdrejWdsejOdoejXdoejYdtejZdtej[duej\duej]dvej^dvej_dwej`dwejadxejbdxejPdpejcdpejSdqejddqejedyejfdyejgdzejhdziZid{d|d}d~dZjdd ZkdddddZldddddZmdddeddkdddZndS )zh
Misc tools for implementing data structures

Note: pandas.core.common is *not* part of the public API.
    )annotationsN)abcdefaultdict)partial)
TYPE_CHECKINGAnyCallable
CollectionHashableIterableIteratorSequencecastoverload)lib)AnyArrayLike	ArrayLikeNpDtypeRandomStateT)find_stack_level)'construct_1d_object_array_from_listlike)is_array_likeis_bool_dtypeis_extension_array_dtype
is_integer)ABCExtensionArrayABCIndex	ABCSeries)iterable_not_string)isna)Indexc                 c  s,   | D ]"}t |r t|E dH  q|V  qdS )a  
    Flatten an arbitrarily nested sequence.

    Parameters
    ----------
    line : sequence
        The non string sequence to flatten

    Notes
    -----
    This doesn't consider strings sequences.

    Returns
    -------
    flattened : generator
    N)r   flatten)lineelement r%   6/tmp/pip-unpacked-wheel-xj8nt62q/pandas/core/common.pyr"   =   s    r"   c              	   C  sL   | d j }| dd  D ]0}z|j |kr*d }W q tk
rD   d }Y qX q|S )Nr      )name
ValueError)objsr(   objr%   r%   r&   consensus_name_attrU   s    

r,   r   bool)keyreturnc                 C  s   t | ttjtfs$t| rt| jr| jtjkrrt	| }t
|snd}t
|dkrjt| rjt|dS dS t| jrdS n4t | trt| dkrt| tk	rt| } t
| S dS )a  
    Check whether `key` is a valid boolean indexer.

    Parameters
    ----------
    key : Any
        Only list-likes may be considered boolean indexers.
        All other types are not considered a boolean indexer.
        For array-like input, boolean ndarrays or ExtensionArrays
        with ``_is_boolean`` set are considered boolean indexers.

    Returns
    -------
    bool
        Whether `key` is a valid boolean indexer.

    Raises
    ------
    ValueError
        When the array is an object-dtype ndarray or ExtensionArray
        and contains missing values.

    See Also
    --------
    check_array_indexer : Check that `key` is a valid array to index,
        and convert to an ndarray.
    z=Cannot mask with non-boolean array containing NA / NaN valuesbooleanFTr   )
isinstancer   npndarrayr   r   r   dtypeobject_asarrayr   Zis_bool_arrayZinfer_dtyper    anyr)   r   listlentypeZis_bool_list)r.   Z	key_arrayZna_msgr%   r%   r&   is_bool_indexer`   s*    




r;   F)
warn_floatc                 C  s4   t | r0|  r0|r(tjdtt d t| S | S )a  
    To avoid numpy DeprecationWarnings, cast float to integer where valid.

    Parameters
    ----------
    val : scalar
    warn_float : bool, default False
        If True, issue deprecation warning for a float indexer.

    Returns
    -------
    outval : scalar
    zIndexing with a float is deprecated, and will raise an IndexError in pandas 2.0. You can manually convert to an integer key instead.
stacklevel)r   Zis_floatr   warningswarnFutureWarningr   int)valr<   r%   r%   r&   cast_scalar_indexer   s    rD   c                  G  s   dd | D S )zL
    Returns a generator consisting of the arguments that are not None.
    c                 s  s   | ]}|d k	r|V  qd S Nr%   .0argr%   r%   r&   	<genexpr>   s      znot_none.<locals>.<genexpr>r%   argsr%   r%   r&   not_none   s    rL   )r/   c                  G  s   t dd | D S )z?
    Returns a boolean indicating if any argument is None.
    c                 s  s   | ]}|d kV  qd S rE   r%   rF   r%   r%   r&   rI      s     zany_none.<locals>.<genexpr>r7   rJ   r%   r%   r&   any_none   s    rN   c                  G  s   t dd | D S )zA
    Returns a boolean indicating if all arguments are None.
    c                 s  s   | ]}|d kV  qd S rE   r%   rF   r%   r%   r&   rI      s     zall_none.<locals>.<genexpr>allrJ   r%   r%   r&   all_none   s    rQ   c                  G  s   t dd | D S )zC
    Returns a boolean indicating if any argument is not None.
    c                 s  s   | ]}|d k	V  qd S rE   r%   rF   r%   r%   r&   rI      s     zany_not_none.<locals>.<genexpr>rM   rJ   r%   r%   r&   any_not_none   s    rR   c                  G  s   t dd | D S )zE
    Returns a boolean indicating if all arguments are not None.
    c                 s  s   | ]}|d k	V  qd S rE   r%   rF   r%   r%   r&   rI      s     zall_not_none.<locals>.<genexpr>rO   rJ   r%   r%   r&   all_not_none   s    rS   rB   c                  G  s   t dd | D S )z;
    Returns the count of arguments that are not None.
    c                 s  s   | ]}|d k	V  qd S rE   r%   rG   xr%   r%   r&   rI      s     z!count_not_none.<locals>.<genexpr>)sumrJ   r%   r%   r&   count_not_none   s    rW   .zArrayLike | list | tuple | zipzNpDtype | Nonez
np.ndarray)valuesr4   r/   c                 C  s   d S rE   r%   rX   r4   r%   r%   r&   asarray_tuplesafe   s    rZ   r   r   c                 C  s   d S rE   r%   rY   r%   r%   r&   rZ      s    c              	   C  s   t | ttfs"t| ds"t| } nt | tr2| jS t | trR|tjtfkrRt	| S z4t
 " t
dtj tj| |d}W 5 Q R X W n tk
r   t	|  Y S X t|jjtrtj| td}|jdkrdd | D } t	| }|S )NZ	__array__ignorer4      c                 S  s   g | ]}t |qS r%   )tuplerT   r%   r%   r&   
<listcomp>  s     z%asarray_tuplesafe.<locals>.<listcomp>)r1   r8   r^   hasattrr   Z_valuesr2   r5   objectr   r?   catch_warningssimplefilterZVisibleDeprecationWarningr6   r)   
issubclassr4   r:   strndim)rX   r4   resultr%   r%   r&   rZ      s$    



znp.ndarray | Iterable)labelsr4   r/   c                 C  s\   t | ttfr| g} t | ttjfsLzt| } W n tk
rJ   | g} Y nX t| |d} | S )z
    Transform label or iterable of labels to array, for use in Index.

    Parameters
    ----------
    dtype : dtype
        If specified, use as dtype of the resulting array, otherwise infer.

    Returns
    -------
    array
    r\   )r1   re   r^   r8   r2   r3   	TypeErrorrZ   )rh   r4   r%   r%   r&   index_labels_to_array  s    rj   c                 C  s    | d k	rt | ttfs| gS | S rE   )r1   r^   r8   r+   r%   r%   r&   maybe_make_list)  s    rl   zIterable[T] | TzCollection[T] | T)r+   r/   c                 C  s.   t | tjr t | tjs t| S tt| } | S )zB
    If obj is Iterable but not list-like, consume into list.
    )r1   r   r   Sizedr8   r   r	   rk   r%   r%   r&   maybe_iterable_to_list/  s    
rn   c                 C  s(   t | to&| jdko&| jdko&| jdkS )z
    We have a null slice.
    Nr1   slicestartstopsteprk   r%   r%   r&   is_null_slice9  s    
rt   z
list[bool]c                 C  s   dd | D S )zX
    Find non-trivial slices in "line": return a list of booleans with same length.
    c                 S  s    g | ]}t |tot| qS r%   )r1   rp   rt   )rG   kr%   r%   r&   r_   I  s     z"is_true_slices.<locals>.<listcomp>r%   )r#   r%   r%   r&   is_true_slicesE  s    rv   )r#   r/   c                 C  s(   t | to&| jdko&| j|ko&| jdkS )z&
    We have a full length slice.
    r   Nro   )r+   r#   r%   r%   r&   is_full_sliceM  s    
rw   c                 C  s>   t | drt| dS t| tr(t| jS t| r:t| jS d S )N__name__)	r`   getattrr1   r   get_callable_namefunccallabler:   rx   rk   r%   r%   r&   rz   Y  s    




rz   c                 K  s   t | r| |f|S | S )z
    Evaluate possibly callable input using obj and kwargs if it is callable,
    otherwise return as it is.

    Parameters
    ----------
    maybe_callable : possibly a callable
    obj : NDFrame
    **kwargs
    )r|   )Zmaybe_callabler+   kwargsr%   r%   r&   apply_if_callablej  s    r~   c                 C  sX   t | s(t| tr tt| jS t| } t| tj	sDt
d|  n| tkrTt
d| S )a  
    Helper function to standardize a supplied mapping.

    Parameters
    ----------
    into : instance or subclass of collections.abc.Mapping
        Must be a class, an initialized collections.defaultdict,
        or an instance of a collections.abc.Mapping subclass.

    Returns
    -------
    mapping : a collections.abc.Mapping subclass or other constructor
        a callable object that can accept an iterator to create
        the desired Mapping.

    See Also
    --------
    DataFrame.to_dict
    Series.to_dict
    zunsupported type: z/to_dict() only accepts initialized defaultdicts)inspectisclassr1   r   r   default_factoryr:   rd   r   Mappingri   )Zintor%   r%   r&   standardize_mapping{  s    

r   znp.random.Generator)stater/   c                 C  s   d S rE   r%   r   r%   r%   r&   random_state  s    r   zGint | ArrayLike | np.random.BitGenerator | np.random.RandomState | Noneznp.random.RandomStatec                 C  s   d S rE   r%   r   r%   r%   r&   r     s    zRandomState | Noner   c                 C  sh   t | st| st| tjjr*tj| S t| tjjr<| S t| tjjrN| S | dkr\tjS tddS )a  
    Helper function for processing random_state arguments.

    Parameters
    ----------
    state : int, array-like, BitGenerator, Generator, np.random.RandomState, None.
        If receives an int, array-like, or BitGenerator, passes to
        np.random.RandomState() as seed.
        If receives an np.random RandomState or Generator, just returns that unchanged.
        If receives `None`, returns np.random.
        If receives anything else, raises an informative ValueError.

        .. versionchanged:: 1.1.0

            array-like and BitGenerator object now passed to np.random.RandomState()
            as seed

        Default None.

    Returns
    -------
    np.random.RandomState or np.random.Generator. If state is None, returns np.random

    Nzdrandom_state must be an integer, array-like, a BitGenerator, Generator, a numpy RandomState, or None)	r   r   r1   r2   randomZBitGeneratorr   	Generatorr)   r   r%   r%   r&   r     s     z/Callable[..., T] | tuple[Callable[..., T], str]r   )r{   r/   c                 O  sR   t |tr>|\}}||kr,| d}t|| ||< |||S || f||S dS )as  
    Apply a function ``func`` to object ``obj`` either by passing obj as the
    first argument to the function or, in the case that the func is a tuple,
    interpret the first element of the tuple as a function and pass the obj to
    that function as a keyword argument whose key is the value of the second
    element of the tuple.

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

    Returns
    -------
    object : the return type of ``func``.
    z/ is both the pipe target and a keyword argumentN)r1   r^   r)   )r+   r{   rK   r}   targetmsgr%   r%   r&   pipe  s    


r   c                   s$    fdd}t  tjtfr |S  S )zv
    Returns a function that will map names/labels, dependent if mapper
    is a dict, Series or just a function.
    c                   s   |  kr |  S | S d S rE   r%   )rU   mapperr%   r&   f
  s    zget_rename_function.<locals>.f)r1   r   r   r   )r   r   r%   r   r&   get_rename_function  s    r   z"Hashable | Iterable | AnyArrayLikezlist | AnyArrayLike)rX   r/   c                 C  s>   t | ttjtttfr| S t | tjr8t | t	s8t| S | gS )z
    Convert list-like or scalar input to list-like. List, numpy and pandas array-like
    inputs are returned unmodified whereas others are converted to list.
    )
r1   r8   r2   r3   r   r   r   r   r   re   )rX   r%   r%   r&   convert_to_list_like  s
    r   re   zIterator[None])attrr/   c              
   c  s4   t | |}t| || z
| V  W 5 t| || X dS )zTemporarily set attribute on an object.

    Args:
        obj: Object whose attribute will be modified.
        attr: Attribute to modify.
        value: Value to temporarily set attribute to.

    Yields:
        obj with modified attribute.
    N)ry   setattr)r+   r   value	old_valuer%   r%   r&   temp_setattr"  s
    

r   r!   None)indexr/   c                 C  s2   t | t |kr.tdt |  dt | ddS )zC
    Check the length of data matches the length of the index.
    zLength of values (z") does not match length of index ()N)r9   r)   )datar   r%   r%   r&   require_length_match6  s    r   rV   maxminrP   r7   meanprodstdvarmediancumprodcumsumr   z
str | None)rH   r/   c                 C  s
   t | S )zH
    if we define an internal function for this argument, return it
    )_cython_tablegetrH   r%   r%   r&   get_cython_funci  s    r   c                 C  s   t | | S )zd
    if we define a builtin function for this argument, return it,
    otherwise return the arg
    )_builtin_tabler   r   r%   r%   r&   is_builtin_funcp  s    r   zSequence[Hashable | None]zlist[Hashable])namesr/   c                 C  s   dd t | D S )a,  
    If a name is missing then replace it by level_n, where n is the count

    .. versionadded:: 1.4.0

    Parameters
    ----------
    names : list-like
        list of column names or None values.

    Returns
    -------
    list
        list of column names with the None values replaced.
    c                 S  s&   g | ]\}}|d krd| n|qS )NZlevel_r%   )rG   ir(   r%   r%   r&   r_     s     z&fill_missing_names.<locals>.<listcomp>)	enumerate)r   r%   r%   r&   fill_missing_namesx  s    r   zbool | None | lib.NoDefault)numeric_onlyr/   c                 C  s&   | t jkrd}n| dkrd}n| }|S )a  Determine the Boolean value of numeric_only.

    See GH#46560 for details on the deprecation.

    Parameters
    ----------
    numeric_only : bool, None, or lib.no_default
        Value passed to the method.

    Returns
    -------
    Resolved value of numeric_only.
    TNF)r   Z
no_default)r   rg   r%   r%   r&   resolve_numeric_only  s    
r   r:   )clsr(   deprecate_noner/   c                 C  sf   |dkrd}nd}d| d| j  d| d}|r@|d| d	7 }|d
| d7 }tj|tt d dS )a  Emit FutureWarning message for deprecation of numeric_only.

    See GH#46560 for details on the deprecation.

    Parameters
    ----------
    cls : type
        pandas type that is generating the warning.
    name : str
        Name of the method that is generating the warning.
    deprecate_none : bool, default False
        Whether to also warn about the deprecation of specifying ``numeric_only=None``.
    )rP   r7   Z	bool_onlyr   zThe default value of z in .z? is deprecated. In a future version, it will default to False. zIn addition, specifying 'z=None' is deprecated. z2Select only valid columns or specify the value of z to silence this warning.r=   N)rx   r?   r@   rA   r   )r   r(   r   Zarg_namer   r%   r%   r&   deprecate_numeric_only_default  s    
r   )F).).)N)N)N)F)o__doc__
__future__r   builtinscollectionsr   r   
contextlib	functoolsr   r   typingr   r   r   r	   r
   r   r   r   r   r   r?   Znumpyr2   Zpandas._libsr   Zpandas._typingr   r   r   r   r   Zpandas.util._exceptionsr   Zpandas.core.dtypes.castr   Zpandas.core.dtypes.commonr   r   r   r   Zpandas.core.dtypes.genericr   r   r   Zpandas.core.dtypes.inferencer   Zpandas.core.dtypes.missingr    Zpandasr!   r"   r,   r;   rD   rL   rN   rQ   rR   rS   rW   rZ   rj   rl   rn   rt   rv   rw   rz   r~   r   r   r   r   r   contextmanagerr   r   rV   r   maximumreducer   Zminimumr   rP   r7   Znansumr   Znanmeanr   Znanprodr   Znanstdr   Znanvarr   Z	nanmedianZnanmaxZnanminr   Z
nancumprodr   Z	nancumsumr   r   r   r   r   r   r%   r%   r%   r&   <module>   s   07 	" 
 8%                             