U
    sVchw                  
   @  s  d Z ddlmZ ddl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 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! ddl"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z* ddl+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2 ddl3m4Z4m5Z5 ddl6m7Z7m8Z8m9Z9m:Z:m;Z; ddl<m=Z= ddl>m?  m@ZA er\ddlBmCZCmDZDmEZE dMdddddddZFe
dNdddddddZGe
dOdddd dd!dZGdPdddd dd#dZGd$d% ZHd&d'd(d)d*ZIdQd"d+d,d-ddddd.d/d0ZJd1d'd2d3d4ZKd"d+dd-d,ddd5d6d7ZLd'd8dd'd9d:d;ZMdd,dd<d=d>ZNd?d-dddd@dAdBZOdCdd(dDdEZPddddd"d"eQfdCdFddGdddHdIdJdKdLZRdS )Rz
Constructor functions intended to be shared by pd.array, Series.__init__,
and Index.__new__.

These should not depend on core.internals.
    )annotations)TYPE_CHECKINGAnyOptionalSequenceUnioncastoverloadN)lib)Period)AnyArrayLike	ArrayLikeDtypeDtypeObjT)IntCastingNaNError)find_stack_level)ExtensionDtype	_registry)"construct_1d_arraylike_from_scalar'construct_1d_object_array_from_listlikemaybe_cast_to_datetimemaybe_cast_to_integer_arraymaybe_convert_platformmaybe_infer_to_datetimelikemaybe_upcastsanitize_to_nanoseconds)is_datetime64_ns_dtypeis_extension_array_dtypeis_float_dtypeis_integer_dtypeis_list_likeis_object_dtypeis_timedelta64_ns_dtype)DatetimeTZDtypePandasDtype)ABCExtensionArrayABCIndexABCPandasArrayABCRangeIndex	ABCSeries)isna)ExtensionArrayIndexSeriesTzSequence[object] | AnyArrayLikezDtype | Noneboolr,   )datadtypecopyreturnc                 C  s,  ddl m}m}m}m}m}m}m}	m}
m	} ddl
m} t| rVd|  d}t||dkrtt| tt|frt| j}t| dd} t|trt|p|}t|rtt| }|j| ||d	S |dkrtj| dd
}|dkrttttt   t!f | }|
j||dS |dkr|| |dS |"drTz|j| |dW S  tk
rP   Y nX n|"drn|j| |dS |dkr|  j| |dS |dkr|j| |dS |dkrt#| ddt$j%kr|j| |dS |dkr|j| |dS t&|r|j| ||d	S t'|r|j| ||d	S |	j| ||d	S )a  
    Create an array.

    Parameters
    ----------
    data : Sequence of objects
        The scalars inside `data` should be instances of the
        scalar type for `dtype`. It's expected that `data`
        represents a 1-dimensional array of data.

        When `data` is an Index or Series, the underlying array
        will be extracted from `data`.

    dtype : str, np.dtype, or ExtensionDtype, optional
        The dtype to use for the array. This may be a NumPy
        dtype or an extension type registered with pandas using
        :meth:`pandas.api.extensions.register_extension_dtype`.

        If not specified, there are two possibilities:

        1. When `data` is a :class:`Series`, :class:`Index`, or
           :class:`ExtensionArray`, the `dtype` will be taken
           from the data.
        2. Otherwise, pandas will attempt to infer the `dtype`
           from the data.

        Note that when `data` is a NumPy array, ``data.dtype`` is
        *not* used for inferring the array type. This is because
        NumPy cannot represent all the types of data that can be
        held in extension arrays.

        Currently, pandas will infer an extension dtype for sequences of

        ============================== =======================================
        Scalar Type                    Array Type
        ============================== =======================================
        :class:`pandas.Interval`       :class:`pandas.arrays.IntervalArray`
        :class:`pandas.Period`         :class:`pandas.arrays.PeriodArray`
        :class:`datetime.datetime`     :class:`pandas.arrays.DatetimeArray`
        :class:`datetime.timedelta`    :class:`pandas.arrays.TimedeltaArray`
        :class:`int`                   :class:`pandas.arrays.IntegerArray`
        :class:`float`                 :class:`pandas.arrays.FloatingArray`
        :class:`str`                   :class:`pandas.arrays.StringArray` or
                                       :class:`pandas.arrays.ArrowStringArray`
        :class:`bool`                  :class:`pandas.arrays.BooleanArray`
        ============================== =======================================

        The ExtensionArray created when the scalar type is :class:`str` is determined by
        ``pd.options.mode.string_storage`` if the dtype is not explicitly given.

        For all other cases, NumPy's usual inference rules will be used.

        .. versionchanged:: 1.0.0

           Pandas infers nullable-integer dtype for integer data,
           string dtype for string data, and nullable-boolean dtype
           for boolean data.

        .. versionchanged:: 1.2.0

            Pandas now also infers nullable-floating dtype for float-like
            input data

    copy : bool, default True
        Whether to copy the data, even if not necessary. Depending
        on the type of `data`, creating the new array may require
        copying data, even if ``copy=False``.

    Returns
    -------
    ExtensionArray
        The newly created array.

    Raises
    ------
    ValueError
        When `data` is not 1-dimensional.

    See Also
    --------
    numpy.array : Construct a NumPy array.
    Series : Construct a pandas Series.
    Index : Construct a pandas Index.
    arrays.PandasArray : ExtensionArray wrapping a NumPy array.
    Series.array : Extract the array stored within a Series.

    Notes
    -----
    Omitting the `dtype` argument means pandas will attempt to infer the
    best array type from the values in the data. As new array types are
    added by pandas and 3rd party libraries, the "best" array type may
    change. We recommend specifying `dtype` to ensure that

    1. the correct array type for the data is returned
    2. the returned array type doesn't change as new extension types
       are added by pandas and third-party libraries

    Additionally, if the underlying memory representation of the returned
    array matters, we recommend specifying the `dtype` as a concrete object
    rather than a string alias or allowing it to be inferred. For example,
    a future version of pandas or a 3rd-party library may include a
    dedicated ExtensionArray for string data. In this event, the following
    would no longer return a :class:`arrays.PandasArray` backed by a NumPy
    array.

    >>> pd.array(['a', 'b'], dtype=str)
    <PandasArray>
    ['a', 'b']
    Length: 2, dtype: str32

    This would instead return the new ExtensionArray dedicated for string
    data. If you really need the new array to be backed by a  NumPy array,
    specify that in the dtype.

    >>> pd.array(['a', 'b'], dtype=np.dtype("<U1"))
    <PandasArray>
    ['a', 'b']
    Length: 2, dtype: str32

    Finally, Pandas has arrays that mostly overlap with NumPy

      * :class:`arrays.DatetimeArray`
      * :class:`arrays.TimedeltaArray`

    When data with a ``datetime64[ns]`` or ``timedelta64[ns]`` dtype is
    passed, pandas will always return a ``DatetimeArray`` or ``TimedeltaArray``
    rather than a ``PandasArray``. This is for symmetry with the case of
    timezone-aware data, which NumPy does not natively support.

    >>> pd.array(['2015', '2016'], dtype='datetime64[ns]')
    <DatetimeArray>
    ['2015-01-01 00:00:00', '2016-01-01 00:00:00']
    Length: 2, dtype: datetime64[ns]

    >>> pd.array(["1H", "2H"], dtype='timedelta64[ns]')
    <TimedeltaArray>
    ['0 days 01:00:00', '0 days 02:00:00']
    Length: 2, dtype: timedelta64[ns]

    Examples
    --------
    If a dtype is not specified, pandas will infer the best dtype from the values.
    See the description of `dtype` for the types pandas infers for.

    >>> pd.array([1, 2])
    <IntegerArray>
    [1, 2]
    Length: 2, dtype: Int64

    >>> pd.array([1, 2, np.nan])
    <IntegerArray>
    [1, 2, <NA>]
    Length: 3, dtype: Int64

    >>> pd.array([1.1, 2.2])
    <FloatingArray>
    [1.1, 2.2]
    Length: 2, dtype: Float64

    >>> pd.array(["a", None, "c"])
    <StringArray>
    ['a', <NA>, 'c']
    Length: 3, dtype: string

    >>> with pd.option_context("string_storage", "pyarrow"):
    ...     arr = pd.array(["a", None, "c"])
    ...
    >>> arr
    <ArrowStringArray>
    ['a', <NA>, 'c']
    Length: 3, dtype: string

    >>> pd.array([pd.Period('2000', freq="D"), pd.Period("2000", freq="D")])
    <PeriodArray>
    ['2000-01-01', '2000-01-01']
    Length: 2, dtype: period[D]

    You can use the string alias for `dtype`

    >>> pd.array(['a', 'b', 'a'], dtype='category')
    ['a', 'b', 'a']
    Categories (2, object): ['a', 'b']

    Or specify the actual dtype

    >>> pd.array(['a', 'b', 'a'],
    ...          dtype=pd.CategoricalDtype(['a', 'b', 'c'], ordered=True))
    ['a', 'b', 'a']
    Categories (3, object): ['a' < 'b' < 'c']

    If pandas does not infer a dedicated extension type a
    :class:`arrays.PandasArray` is returned.

    >>> pd.array([1 + 1j, 3 + 2j])
    <PandasArray>
    [(1+1j), (3+2j)]
    Length: 2, dtype: complex128

    As mentioned in the "Notes" section, new extension types may be added
    in the future (by pandas or 3rd party libraries), causing the return
    value to no longer be a :class:`arrays.PandasArray`. Specify the `dtype`
    as a NumPy dtype if you need to ensure there's no future change in
    behavior.

    >>> pd.array([1, 2], dtype=np.dtype("int32"))
    <PandasArray>
    [1, 2]
    Length: 2, dtype: int32

    `data` must be 1-dimensional. A ValueError is raised when the input
    has the wrong dimensionality.

    >>> pd.array(1)
    Traceback (most recent call last):
      ...
    ValueError: Cannot pass scalar '1' to 'pandas.array'.
    r   )	BooleanArrayDatetimeArrayr,   FloatingArrayIntegerArrayIntervalArrayPandasArrayPeriodArrayTimedeltaArray)StringDtypezCannot pass scalar 'z' to 'pandas.array'.NT)extract_numpyr1   r2   )ZskipnaZperiodr2   intervaldatetime	timedeltastringinteger)Zfloatingzmixed-integer-floatr1   boolean)(pandas.core.arraysr4   r5   r,   r6   r7   r8   r9   r:   r;   Zpandas.core.arrays.string_r<   r
   	is_scalar
ValueError
isinstancer*   r'   r1   extract_arraystrregistryfindr   r   r   construct_array_type_from_sequenceZinfer_dtyper   r   r   r   r   
startswithgetattrnpZfloat16r   r#   )r0   r1   r2   r4   r5   r,   r6   r7   r8   r9   r:   r;   r<   msgclsZinferred_dtypeZperiod_data rU   </tmp/pip-unpacked-wheel-xj8nt62q/pandas/core/construction.pyarrayQ   sX     _,









rW   .zSeries | Indexr   )objr=   extract_ranger3   c                 C  s   d S NrU   rX   r=   rY   rU   rU   rV   rJ     s    rJ   r   zT | ArrayLikec                 C  s   d S rZ   rU   r[   rU   rU   rV   rJ     s    Fc                 C  sF   t | ttfr,t | tr&|r"| jS | S | jS |rBt | trB|  S | S )a  
    Extract the ndarray or ExtensionArray from a Series or Index.

    For all other types, `obj` is just returned as is.

    Parameters
    ----------
    obj : object
        For Series / Index, the underlying ExtensionArray is unboxed.

    extract_numpy : bool, default False
        Whether to extract the ndarray from a PandasArray.

    extract_range : bool, default False
        If we have a RangeIndex, return range._values if True
        (which is a materialized integer ndarray), otherwise return unchanged.

    Returns
    -------
    arr : object

    Examples
    --------
    >>> extract_array(pd.Series(['a', 'b', 'c'], dtype='category'))
    ['a', 'b', 'c']
    Categories (3, object): ['a', 'b', 'c']

    Other objects like lists, arrays, and DataFrames are just passed through.

    >>> extract_array([1, 2, 3])
    [1, 2, 3]

    For an ndarray-backed Series / Index the ndarray is returned.

    >>> extract_array(pd.Series([1, 2, 3]))
    array([1, 2, 3])

    To extract all the way down to the ndarray, pass ``extract_numpy=True``.

    >>> extract_array(pd.Series([1, 2, 3]), extract_numpy=True)
    array([1, 2, 3])
    )rI   r'   r*   r)   Z_valuesr(   Zto_numpyr[   rU   rU   rV   rJ     s    -
c                 C  sT   t | tjrP| jjdkr.ddlm} || S | jjdkrPddlm} || S | S )zS
    Wrap datetime64 and timedelta64 ndarrays in DatetimeArray/TimedeltaArray.
    Mr   )r5   m)r;   )	rI   rR   ndarrayr1   kindrF   r5   rO   r;   )arrr5   r;   rU   rU   rV   ensure_wrapped_if_datetimelike  s    

ra   zma.MaskedArrayz
np.ndarray)r0   r3   c                 C  s@   t | }| r4t| dd\} }|   || |< n|  } | S )z?
    Convert numpy MaskedArray to ensure mask is softened.
    Tr?   )maZgetmaskarrayanyr   Zsoften_maskr2   )r0   maskZ
fill_valuerU   rU   rV   sanitize_masked_array  s    

re   allow_2dzIndex | NonezDtypeObj | None)indexr1   r2   raise_cast_failurerg   r3   c                C  s&  t | tjrt| } t |tr$|j}t| ddd} t | tjrb| j	dkrb|dkrV| j
}t| } nt | trxt| } d}t| s|dkrtdt| t||} | S t | tjrt | tjr| j} |dk	rt| j
rt|rz*tjdd t| ||d}W 5 Q R X W n tk
rD   tjd	tt d
 tj| |d}Y n\ tk
r   |stjdtt d
 ttj
|}tj| ||d Y S tj| |d}Y nX nt| |||}n4t | t r| }|dk	r|j!||d}n|r|" }nt | t#t$frt%dt&| j' dt(| dr0tj| |d} nt)| } |dk	sPt| dkrzt| |||}W nZ tk
r   t|rtj| dd}|j
j*dkrt+|||d||d Y S  n Y nX n(t,| }|j
t-krttj|}t.|}t/|| |||d}t |tjr"ttj
|}t0|| ||}|S )a  
    Sanitize input data to an ndarray or ExtensionArray, copy if specified,
    coerce to the dtype if specified.

    Parameters
    ----------
    data : Any
    index : Index or None, default None
    dtype : np.dtype, ExtensionDtype, or None, default None
    copy : bool, default False
    raise_cast_failure : bool, default True
    allow_2d : bool, default False
        If False, raise if we have a 2D Arraylike.

    Returns
    -------
    np.ndarray or ExtensionArray

    Notes
    -----
    raise_cast_failure=False is only intended to be True when called from the
    DataFrame constructor, as the dtype keyword there may be interpreted as only
    applying to a subset of columns, see GH#24435.
    T)r=   rY   r   NFz2index must be specified when data is not list-likeignore)invalida  In a future version, passing float-dtype values containing NaN and an integer dtype will raise IntCastingNaNError (subclass of ValueError) instead of silently ignoring the passed dtype. To retain the old behavior, call Series(arr) or DataFrame(arr) without passing a dtype.
stacklevelr?   zIn a future version, passing float-dtype values and an integer dtype to DataFrame will retain floating dtype if they cannot be cast losslessly (matching Series behavior). To retain the old behavior, use DataFrame(data).astype(dtype)r>   'z' type is unorderedZ	__array__f)r2   ri   rg   rf   )1rI   rb   ZMaskedArrayre   r%   Znumpy_dtyperJ   rR   r^   ndimr1   r
   Zitem_from_zerodimrangerange_to_ndarrayr!   rH   r   lenZmatrixAr   r    Zerrstate	_try_castr   warningswarnFutureWarningr   rW   r   r&   astyper2   set	frozenset	TypeErrortype__name__hasattrlistr_   sanitize_arrayr   objectr   _sanitize_ndim_sanitize_str_dtypes)r0   rh   r1   r2   ri   rg   subarrZcastedrU   rU   rV   r     s    !

 	



	
r   rq   )rngr3   c                 C  s   zt j| j| j| jdd}W n tk
r   | jdkr@| jdksT| jdkr| jdk rzt j| j| j| jdd}W q tk
r   tt| }Y qX ntt| }Y nX |S )z)
    Cast a range object to ndarray.
    Zint64r1   r   Zuint64)rR   ZarangestartstopstepOverflowErrorr   r   )r   r`   rU   rU   rV   rr     s    (rr   )resultr1   rh   rg   r3   c                C  s   t | dddkrtdn| jdkr0t| |} nr| jdkrt|tjrV|rN| S tdt|rt|trt	j
|tdd} | }|j| |d} nt	j
||d} | S )z6
    Ensure we have a 1-dimensional result array.
    rp   r   z(result should be arraylike with ndim > 0   zData must be 1-dimensionalr   r   )rQ   rH   rp   _maybe_repeatrI   rR   r^   r"   r   comZasarray_tuplesafer1   rN   rO   )r   r0   r1   rh   rg   rT   rU   rU   rV   r     s    


r   znp.dtype | None)r   r1   r2   r3   c                 C  sJ   t | jjtrFt|sFtt|s6tj	||dd}tj	|t
|d} | S )z=
    Ensure we have a dtype that is supported by pandas.
    Fr>   )
issubclassr1   r}   rK   r
   rG   rR   allr+   rW   r   )r   r0   r1   r2   rU   rU   rV   r     s    	
r   )r`   rh   r3   c                 C  s:   |dk	r6dt |   kr$t |kr6n n| t |} | S )zx
    If we have a length-1 array and an index describing how long we expect
    the result to be, repeat the array.
    Nr   )rs   repeat)r`   rh   rU   rU   rV   r     s     r   zlist | np.ndarray)r`   r1   r2   ri   r3   c           
   	   C  s  t | tj}|dkr|rZttj| } | jtkr:t| |dS t| }|| krV|rV| }|S tj	| dd}|jtks||j
dkr|S t|S nt |trt |trt| |S | j}|| ||d}|S t|r|st| }|S t| j||dS |jdkrH|r(ttj| } | j}	| jdkr2|  } n
t| f}	tj| d|d|	S |jd	kr^t| |S z*t|rvt| |}ntj	| ||d}W nN ttfk
r   |r n*t j!d
| dt"t# d tj	| t|d}Y nX |S )a  
    Convert input to numpy ndarray and optionally cast to a given dtype.

    Parameters
    ----------
    arr : ndarray or list
        Excludes: ExtensionArray, Series, Index.
    dtype : np.dtype, ExtensionDtype or None
    copy : bool
        If False, don't copy the data if not needed.
    raise_cast_failure : bool
        If True, and if a dtype is specified, raise errors during casting.
        Otherwise an object array is returned.

    Returns
    -------
    np.ndarray or ExtensionArray
    Nr?   Fr   r>   Ur   )Zconvert_na_valuer2   )r]   r\   zCould not cast to z, falling back to object. This behavior is deprecated. In a future version, when a dtype is passed to 'DataFrame', either all columns will be cast to that dtype, or a TypeError will be raised.rl   )$rI   rR   r^   r   r1   r   r   r   r2   rW   sizer   r$   r   rN   rO   r"   r   ra   ry   r_   shaperp   Zravelrs   r
   Zensure_string_arrayZreshaper    r   rH   r|   rv   rw   rx   r   )
r`   r1   r2   ri   Z
is_ndarrayoutZvarrZ
array_typer   r   rU   rU   rV   ru     sf    










ru   r   c                 C  s.   | dk}t | ot| d }|o$|  }|p,|S )a  
    Utility to check if a Series is instantiated with empty data,
    which does not contain dtype information.

    Parameters
    ----------
    data : array-like, Iterable, dict, or scalar value
        Contains data stored in Series.

    Returns
    -------
    bool
    Nr1   )r!   r   )r0   Zis_noneZis_list_like_without_dtypeZis_simple_emptyrU   rU   rV   is_empty_data]  s    
r   zArrayLike | Index | Nonez
str | Noner   r.   )r0   rh   r1   namer2   fastpathdtype_if_emptyr3   c                 C  s4   ddl m} t| r |dkr |}|| |||||dS )ag  
    Helper to pass an explicit dtype when instantiating an empty Series.

    This silences a DeprecationWarning described in GitHub-17261.

    Parameters
    ----------
    data : Mirrored from Series.__init__
    index : Mirrored from Series.__init__
    dtype : Mirrored from Series.__init__
    name : Mirrored from Series.__init__
    copy : Mirrored from Series.__init__
    fastpath : Mirrored from Series.__init__
    dtype_if_empty : str, numpy.dtype, or ExtensionDtype
        This dtype will be passed explicitly if an empty Series will
        be instantiated.

    Returns
    -------
    Series
    r   )r.   N)r0   rh   r1   r   r2   r   )Zpandas.core.seriesr.   r   )r0   rh   r1   r   r2   r   r   r.   rU   rU   rV   !create_series_with_explicit_dtypeq  s         r   )NT)..)..)FF)NFT)S__doc__
__future__r   typingr   r   r   r   r   r   r	   rv   ZnumpyrR   Znumpy.marb   Zpandas._libsr
   Zpandas._libs.tslibs.periodr   Zpandas._typingr   r   r   r   r   Zpandas.errorsr   Zpandas.util._exceptionsr   Zpandas.core.dtypes.baser   r   rL   Zpandas.core.dtypes.castr   r   r   r   r   r   r   r   Zpandas.core.dtypes.commonr   r   r   r    r!   r"   r#   Zpandas.core.dtypes.dtypesr$   r%   Zpandas.core.dtypes.genericr&   r'   r(   r)   r*   Zpandas.core.dtypes.missingr+   Zpandas.core.commoncorecommonr   Zpandasr,   r-   r.   rW   rJ   ra   re   r   rr   r   r   r   ru   r   r   r   rU   rU   rU   rV   <module>   sv   $	(
$		    2         >    %%u