U
    +ifB                  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 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/m0Z0 ddl1m2Z2 erddl3m4Z4 G dd de5Z6G dd de7Z8dd Z9dd Z:dddddZ;ddddd Z<d!d" Z=dd#d$d%Z>dd#d&d'Z?dd#d(d)Z@dd#d*d+ZAd,d#d-d.ZBdd/d0d1d2d3ZCdd/d0d1d4d5ZDd6d7 ZEd8d9d:d;d<ZFdd#d=d>ZGd?d#d@dAZHd,ddBdCdDZIdEdF ZJdGdH ZKdIdJ ZLedKdKdLdMdNZMedOdPdLdQdNZMddRdSdTdNZMdUdVdWdXdYZNdZd[ ZOd\d]d^d_d`ZPejQdadbdcdddeZRdfdgdhdiZSejTejTejUejVjWejXejYjWiZZejTdjejUdkejXdlej[dmej\dnejTdjej]djej^doej_doej`dpejadpejbdqejcdqejddrejedrejfdsejgdsejUdkejhdkejXdlejidlejjdtejkdtejlduejmduiZndvdwdxdydzZod{d| Zpd}d~dddZqd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Scalar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                   @  s   e Zd ZdS )SettingWithCopyErrorN__name__
__module____qualname__ r(   r(   E/home/mars/bis/venv/lib/python3.8/site-packages/pandas/core/common.pyr#   >   s   r#   c                   @  s   e Zd ZdS )SettingWithCopyWarningNr$   r(   r(   r(   r)   r*   B   s   r*   c                 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elementr(   r(   r)   r+   F   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)Zobjsr/   objr(   r(   r)   consensus_name_attr^   s    

r2   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!   anyr0   r   listlentypeZis_bool_list)r4   Zna_msgr(   r(   r)   is_bool_indexeri   s*    




rA   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)valrB   r(   r(   r)   cast_scalar_indexer   s    rI   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    rQ   )r5   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 rJ   r(   rK   r(   r(   r)   rN      s     zany_none.<locals>.<genexpr>r=   rO   r(   r(   r)   any_none   s    rS   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 rJ   r(   rK   r(   r(   r)   rN      s     zall_none.<locals>.<genexpr>allrO   r(   r(   r)   all_none   s    rV   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 rJ   r(   rK   r(   r(   r)   rN      s     zany_not_none.<locals>.<genexpr>rR   rO   r(   r(   r)   any_not_none   s    rW   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 rJ   r(   rK   r(   r(   r)   rN      s     zall_not_none.<locals>.<genexpr>rT   rO   r(   r(   r)   all_not_none   s    rX   rG   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 rJ   r(   rL   xr(   r(   r)   rN      s     z!count_not_none.<locals>.<genexpr>)sumrO   r(   r(   r)   count_not_none   s    r\   zNpDtype | Nonez
np.ndarray)r:   r5   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 tj
| |d}t|jjtr|tj
| td}|jdkrdd | D } t	| }|S )NZ	__array__r:      c                 S  s   g | ]}t |qS r(   )tuplerY   r(   r(   r)   
<listcomp>   s     z%asarray_tuplesafe.<locals>.<listcomp>)r7   r>   r_   hasattrr   Z_valuesr8   r;   objectr   r<   
issubclassr:   r@   strndim)valuesr:   resultr(   r(   r)   asarray_tuplesafe   s    


rh   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]   )r7   rd   r_   r>   r8   r9   	TypeErrorrh   )labelsr:   r(   r(   r)   index_labels_to_array   s    rk   c                 C  s    | d k	rt | ttfs| gS | S rJ   )r7   r_   r>   r1   r(   r(   r)   maybe_make_list  s    rm   zIterable[T] | TzCollection[T] | T)r1   r5   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.
    )r7   r   r   Sizedr>   r   r	   rl   r(   r(   r)   maybe_iterable_to_list  s    
ro   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r7   slicestartstopsteprl   r(   r(   r)   is_null_slice)  s    
ru   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(   )r7   rq   ru   )rL   kr(   r(   r)   r`   9  s     z"is_true_slices.<locals>.<listcomp>r(   )r,   r(   r(   r)   is_true_slices5  s    rw   )r,   r5   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   Nrp   )r1   r,   r(   r(   r)   is_full_slice=  s    
rx   c                 C  s>   t | drt| dS t| tr(t| jS t| r:t| jS d S )Nr%   )	ra   getattrr7   r   get_callable_namefunccallabler@   r%   rl   r(   r(   r)   rz   I  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_callabler1   kwargsr(   r(   r)   apply_if_callableZ  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isclassr7   r   r   default_factoryr@   rc   r   Mappingri   )Zintor(   r(   r)   standardize_mappingk  s    

r   znp.random.Generator)stater5   c                 C  s   d S rJ   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 rJ   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   r7   r8   randomZBitGeneratorr   	Generatorr0   r   r(   r(   r)   r     s     z/Callable[..., T] | tuple[Callable[..., T], str]r   )r{   r5   c                 O  sR   t |tr>|\}}||kr,| d}t|| ||< |||S || f||S dS )ar  
    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)r7   r_   r0   )r1   r{   rP   r}   targetmsgr(   r(   r)   pipe  s    


r   c                   s&   t  tjtfr fdd}n }|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 rJ   r(   )rZ   mapperr(   r)   f  s    zget_rename_function.<locals>.f)r7   r   r   r   )r   r   r(   r   r)   get_rename_function  s    r   z Scalar | Iterable | AnyArrayLikezlist | AnyArrayLike)rf   r5   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.
    )
r7   r>   r8   r9   r   r   r   r   r   rd   )rf   r(   r(   r)   convert_to_list_like  s
    r   rd   zIterator[None])attrr5   c                 c  s,   t | |}t| || | V  t| || 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)r1   r   value	old_valuer(   r(   r)   temp_setattr  s    
r   r"   )indexc                 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)r?   r0   )datar   r(   r(   r)   require_length_match(  s    r   r[   maxminrU   r=   meanprodstdvarmediancumprodcumsumr   z
str | None)rM   r5   c                 C  s
   t | S )zH
    if we define an internal function for this argument, return it
    )_cython_tablegetrM   r(   r(   r)   get_cython_func[  s    r   c                 C  s   t | | S )ze
    if we define an builtin function for this argument, return it,
    otherwise return the arg
    )_builtin_tabler   r   r(   r(   r)   is_builtin_funcb  s    r   zSequence[Hashable | None]zlist[Hashable])namesr5   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(   )rL   ir/   r(   r(   r)   r`   z  s     z&fill_missing_names.<locals>.<listcomp>)	enumerate)r   r(   r(   r)   fill_missing_namesj  s    r   )F)N)N)N)r__doc__
__future__r   builtinscollectionsr   r   
contextlib	functoolsr   r   typingr   r   r   r	   r
   r   r   r   r   r   rD   numpyr8   Zpandas._libsr   Zpandas._typingr   r   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"   r0   r#   Warningr*   r+   r2   rA   rI   rQ   rS   rV   rW   rX   r\   rh   rk   rm   ro   ru   rw   rx   rz   r~   r   r   r   r   r   contextmanagerr   r   r[   r   maximumreducer   minimumr   rU   r=   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)   <module>   s   0 7
 8%                            