o
    ҷh                     @  s  d dl mZ d dlmZ d dlZd dlmZmZmZm	Z	m
Z
mZmZ d dlZd dlZd dlmZ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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/m0Z0 d dl1m2Z2m3Z3 d dl4m5Z5 d dl6m7Z7m8Z8 d dl9m:Z:m;Z; d dl<m=Z=m>Z>m?Z?m@Z@ d dlAmBZB d dlCmD  mEZ d dlFmGZH d dlImD  mJZK erd dlLmMZM d dlNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZV d dlFmWZWmXZX d dlYmZZZ e
dedZ[ddiZ\dCdDdd Z]G d!d deHj^e"j_Z`d"d# Za		$dEdFd,d-ZbedGd.d/ZcedHd2d/ZcdId4d/Zc	dCdJd6d7ZdKdLd;d<Zd								dMdNd>d?ZedOdAdBZfdS )P    )annotations)	timedeltaN)TYPE_CHECKINGAnyCallableLiteralTypeVarcastoverload)algoslib)NDArrayBacked)
BaseOffsetNaTNaTType	Timedeltaastype_overflowsafedt64arr_to_periodarrget_unit_from_dtypeiNaTparsingperiod	to_offset)	FreqGroup)isleapyear_arr)Tickdelta_to_tick)DIFFERENT_FREQIncompatibleFrequencyPeriodget_period_field_arrperiod_asfreq_arr)cache_readonlydoc)find_stack_level)ensure_objectpandas_dtype)DatetimeTZDtypePeriodDtype)ABCIndexABCPeriodIndex	ABCSeriesABCTimedeltaArray)isna)datetimelike)Sequence)AnyArrayLikeDtypeFillnaOptionsNpDtypeNumpySorterNumpyValueArrayLikeSelfnpt)DatetimeArrayTimedeltaArray)ExtensionArrayBaseOffsetT)boundklassPeriodArraynamestr	docstring
str | Nonec                   s     fdd} |_ ||_t|S )Nc                   s   | j j}t | j|}|S N)dtype_dtype_coder    asi8)selfbaseresultr?    L/var/www/html/venv/lib/python3.10/site-packages/pandas/core/arrays/period.pyfi   s   z_field_accessor.<locals>.f)__name____doc__property)r?   rA   rM   rK   rJ   rL   _field_accessorh   s   rQ   c                      s  e Zd ZU dZdZdZeeZ	e
fZdd ZdZedd	d
Zg Zded< dgZded< g dZded< g dZded< ee e Zded< g dZded< ded< 	dddd Zedd$d%Zeddd&dd'd(Zeddd&dd)d*Zeddd+d,Zed-d. Zdd2d3Zdd6d7Zdd8d9Z e!dd:d;Z"edd=d>Z#dddAdBZ$ddCdDZ%e&dEdFZ'e&dGdHZ(e&dIdJZ)e&dKdLZ*e&dMdNZ+e&dOdPZ,e&dQdRZ-e-Z.e&dSdTZ/e/Z0e0Z1e&dUdV Z2Z3e&dWdXZ4e&dYZ5e&dZd[Z6e6Z7edd]d^Z8dddbdcZ9ddddeZ:e;di e<dfdfdgdddidjZ=dddldmZ>dnddoddsdtZ?dd fdvdwZ@	x	ddddZAdduddddZB	udd fddZCdddZDdddZE fddZFdddZGdd ZH  ZIS )r>   a  
    Pandas ExtensionArray for storing Period data.

    Users should use :func:`~pandas.array` to create new instances.

    Parameters
    ----------
    values : Union[PeriodArray, Series[period], ndarray[int], PeriodIndex]
        The data to store. These should be arrays that can be directly
        converted to ordinals without inference or copy (PeriodArray,
        ndarray[int64]), or a box around such an array (Series[period],
        PeriodIndex).
    dtype : PeriodDtype, optional
        A PeriodDtype instance from which to extract a `freq`. If both
        `freq` and `dtype` are specified, then the frequencies must match.
    freq : str or DateOffset
        The `freq` to use for the array. Mostly applicable when `values`
        is an ndarray of integers, when `freq` is required. When `values`
        is a PeriodArray (or box around), it's checked that ``values.freq``
        matches `freq`.
    copy : bool, default False
        Whether to copy the ordinals before storing.

    Attributes
    ----------
    None

    Methods
    -------
    None

    See Also
    --------
    Period: Represents a period of time.
    PeriodIndex : Immutable Index for period data.
    period_range: Create a fixed-frequency PeriodArray.
    array: Construct a pandas array.

    Notes
    -----
    There are two components to a PeriodArray

    - ordinals : integer ndarray
    - freq : pd.tseries.offsets.Offset

    The values are physically stored as a 1-D ndarray of integers. These are
    called "ordinals" and represent some kind of offset from a base.

    The `freq` indicates the span covered by each element of the array.
    All elements in the PeriodArray have the same `freq`.

    Examples
    --------
    >>> pd.arrays.PeriodArray(pd.PeriodIndex(['2023-01-01',
    ...                                       '2023-01-02'], freq='D'))
    <PeriodArray>
    ['2023-01-01', '2023-01-02']
    Length: 2, dtype: period[D]
    i  periodarrayc                 C  s
   t | tS rC   )
isinstancer(   )xrK   rK   rL   <lambda>   s    zPeriodArray.<lambda>)r   returntype[Period]c                 C  s   t S rC   )r   rG   rK   rK   rL   _scalar_type      zPeriodArray._scalar_typez	list[str]
_other_opsis_leap_year	_bool_ops)
start_timeend_timefreq_object_ops)yearmonthdayhourminutesecond
weekofyearweekdayweek	dayofweekday_of_week	dayofyearday_of_yearquarterqyeardays_in_monthdaysinmonth
_field_ops_datetimelike_ops)strftimeto_timestampasfreq_datetimelike_methodsr(   _dtypeNFrD   Dtype | NonecopyboolNonec                 C  s  |d urt jdtt d t||}t|}|d ur+t|}t|ts+td| dt|t	r?|j
}t|t| s>tdnt|trG|j
}t|t| rd|d ur]||jkr]t||j|j|j}}tj|d|d}|d u rttdtt|}t| || d S )	Nz}The 'freq' keyword in the PeriodArray constructor is deprecated and will be removed in a future version. Pass 'dtype' instead)
stacklevelzInvalid dtype z for PeriodArrayzIncorrect dtypeint64rD   r{   z-dtype is not specified and cannot be inferred)warningswarnFutureWarningr$   validate_dtype_freqr(   r&   rS   
ValueErrorr+   _valuestype	TypeErrorr*   rD   raise_on_incompatibler`   _ndarraynparrayr	   r   __init__)rG   valuesrD   r`   r{   rK   rK   rL   r      s8   




zPeriodArray.__init__r   npt.NDArray[np.int64]r6   c                 C  s.   d}t |tjr|jdksJ || ||dS )Nz Should be numpy array of type i8i8rD   )rS   r   ndarrayrD   )clsr   rD   assertion_msgrK   rK   rL   _simple_new  s   zPeriodArray._simple_newr   c                C  s   |d urt |}|rt|tr|j}nd }t|| r(t|j| |r&| }|S tj|t	d}|p5t
|}t
||}t|}| ||dS )Nr   )r&   rS   r(   r`   r   rD   r{   r   asarrayobject	libperiodextract_freqextract_ordinals)r   scalarsrD   r{   r`   periodsordinalsrK   rK   rL   _from_sequence  s   
zPeriodArray._from_sequencec                C  s   | j |||dS )Nr   )r   )r   stringsrD   r{   rK   rK   rL   _from_sequence_of_strings-  s   z%PeriodArray._from_sequence_of_stringsc                 C  s$   t |||\}}t|}| ||dS )a  
        Construct a PeriodArray from a datetime64 array

        Parameters
        ----------
        data : ndarray[datetime64[ns], datetime64[ns, tz]]
        freq : str or Tick
        tz : tzinfo, optional

        Returns
        -------
        PeriodArray[freq]
        r   )r   r(   )r   datar`   tzrD   rK   rK   rL   _from_datetime643  s   zPeriodArray._from_datetime64c                 C  s   t |}|d urt|}t|}|d us|d ur/|dkr"tdt||||\}}||fS |dkrBtdd|i|\}}||fS td)Nr   z=Can either instantiate from fields or endpoints, but not bothr`   z/Not enough parameters to construct Period rangerK   )dtlvalidate_periodsr   _maybe_convert_freqlenr   _get_ordinal_range_range_from_fields)r   startendr   r`   fieldsfield_countsubarrrK   rK   rL   _generate_rangeF  s   

zPeriodArray._generate_rangevaluePeriod | NaTTypenp.int64c                 C  sF   |t u r
t|jS t|| jr| | t|jS td| d)Nz!'value' should be a Period. Got 'z
' instead.)	r   r   r   _valuerS   rY   _check_compatible_withordinalr   rG   r   rK   rK   rL   _unbox_scalara  s   
zPeriodArray._unbox_scalarr@   r   c                 C  s   t || jdS )N)r`   )r   r`   r   rK   rK   rL   _scalar_from_stringn  s   zPeriodArray._scalar_from_stringc                 C  s   |t u rd S | | d S rC   )r   _require_matching_freqrG   otherrK   rK   rL   r   q  s   z"PeriodArray._check_compatible_withc                 C  s   | j S rC   )ry   rX   rK   rK   rL   rD   y  s   zPeriodArray.dtyper   c                 C  s   | j jS )zC
        Return the frequency object for this PeriodArray.
        rD   r`   rX   rK   rK   rL   r`   ~  s   zPeriodArray.freqNpDtype | None
np.ndarrayc                 C  s0   |dkr| j S |tkr| j S tjt| tdS )Nr   r   )rF   r|   _isnanr   r   listr   )rG   rD   rK   rK   rL   	__array__  s
   zPeriodArray.__array__c                 C  s   ddl }ddlm} |dur@|j|r|j| j|  |dS t||r8| j	|j
kr7td| j	 d|j
 dntd| d	|| j	}|j| j|  d
d}|j||S )z6
        Convert myself into a pyarrow Array.
        r   N)ArrowPeriodType)maskr   zENot supported to convert PeriodArray to array with different 'freq' (z vs )z)Not supported to convert PeriodArray to 'z' typer   )pyarrow(pandas.core.arrays.arrow.extension_typesr   types
is_integerr   r   r-   rS   freqstrr`   r   r:   from_storage)rG   r   r   r   period_typestorage_arrayrK   rK   rL   __arrow_array__  s*   


zPeriodArray.__arrow_array__rb   z
        The year of the period.

        Examples
        --------
        >>> idx = pd.PeriodIndex(["2023", "2024", "2025"], freq="Y")
        >>> idx.year
        Index([2023, 2024, 2025], dtype='int64')
        rc   z
        The month as January=1, December=12.

        Examples
        --------
        >>> idx = pd.PeriodIndex(["2023-01", "2023-02", "2023-03"], freq="M")
        >>> idx.month
        Index([1, 2, 3], dtype='int64')
        rd   z
        The days of the period.

        Examples
        --------
        >>> idx = pd.PeriodIndex(['2020-01-31', '2020-02-28'], freq='D')
        >>> idx.day
        Index([31, 28], dtype='int64')
        re   z
        The hour of the period.

        Examples
        --------
        >>> idx = pd.PeriodIndex(["2023-01-01 10:00", "2023-01-01 11:00"], freq='H')
        >>> idx.hour
        Index([10, 11], dtype='int64')
        rf   a  
        The minute of the period.

        Examples
        --------
        >>> idx = pd.PeriodIndex(["2023-01-01 10:30:00",
        ...                       "2023-01-01 11:50:00"], freq='min')
        >>> idx.minute
        Index([30, 50], dtype='int64')
        rg   a	  
        The second of the period.

        Examples
        --------
        >>> idx = pd.PeriodIndex(["2023-01-01 10:00:30",
        ...                       "2023-01-01 10:00:31"], freq='s')
        >>> idx.second
        Index([30, 31], dtype='int64')
        rj   a   
        The week ordinal of the year.

        Examples
        --------
        >>> idx = pd.PeriodIndex(["2023-01", "2023-02", "2023-03"], freq="M")
        >>> idx.week  # It can be written `weekofyear`
        Index([5, 9, 13], dtype='int64')
        rl   z
        The day of the week with Monday=0, Sunday=6.

        Examples
        --------
        >>> idx = pd.PeriodIndex(["2023-01-01", "2023-01-02", "2023-01-03"], freq="D")
        >>> idx.weekday
        Index([6, 0, 1], dtype='int64')
        rn   a  
        The ordinal day of the year.

        Examples
        --------
        >>> idx = pd.PeriodIndex(["2023-01-10", "2023-02-01", "2023-03-01"], freq="D")
        >>> idx.dayofyear
        Index([10, 32, 60], dtype='int64')

        >>> idx = pd.PeriodIndex(["2023", "2024", "2025"], freq="Y")
        >>> idx
        PeriodIndex(['2023', '2024', '2025'], dtype='period[A-DEC]')
        >>> idx.dayofyear
        Index([365, 366, 365], dtype='int64')
        ro   z
        The quarter of the date.

        Examples
        --------
        >>> idx = pd.PeriodIndex(["2023-01", "2023-02", "2023-03"], freq="M")
        >>> idx.quarter
        Index([1, 1, 1], dtype='int64')
        rp   rq   a  
        The number of days in the month.

        Examples
        --------
        For Series:

        >>> period = pd.period_range('2020-1-1 00:00', '2020-3-1 00:00', freq='M')
        >>> s = pd.Series(period)
        >>> s
        0   2020-01
        1   2020-02
        2   2020-03
        dtype: period[M]
        >>> s.dt.days_in_month
        0    31
        1    29
        2    31
        dtype: int64

        For PeriodIndex:

        >>> idx = pd.PeriodIndex(["2023-01", "2023-02", "2023-03"], freq="M")
        >>> idx.days_in_month   # It can be also entered as `daysinmonth`
        Index([31, 28, 31], dtype='int64')
        npt.NDArray[np.bool_]c                 C  s   t t| jS )z
        Logical indicating if the date belongs to a leap year.

        Examples
        --------
        >>> idx = pd.PeriodIndex(["2023", "2024", "2025"], freq="Y")
        >>> idx.is_leap_year
        array([False,  True, False])
        )r   r   r   rb   rX   rK   rK   rL   r\   O  s   zPeriodArray.is_leap_yearr   howr8   c                 C  s(  ddl m} t|}|dk}|r<|dks| jdkr,tddtdd }| jdd	| S tdd}| | j jdd	| S |d
u rH| j }|}nt	
|}|j}| j||d	}t|j|}||}	| jjdkrt| j}
t|
dkr|
d }|| jjkr| j|	_|	S |dkr| jj|	_|	S |	dS )a  
        Cast to DatetimeArray/Index.

        Parameters
        ----------
        freq : str or DateOffset, optional
            Target frequency. The default is 'D' for week or longer,
            'S' otherwise.
        how : {'s', 'e', 'start', 'end'}
            Whether to use the start or end of the time period being converted.

        Returns
        -------
        DatetimeArray/Index

        Examples
        --------
        >>> idx = pd.PeriodIndex(["2023-01", "2023-02", "2023-03"], freq="M")
        >>> idx.to_timestamp()
        DatetimeIndex(['2023-01-01', '2023-02-01', '2023-03-01'],
        dtype='datetime64[ns]', freq='MS')
        r   )r8   EB   Dnsr   )r   Ninfer)pandas.core.arraysr8   r   validate_end_aliasr`   r   rv   ry   _get_to_timestamp_baser   r   _period_dtype_coderw   periodarr_to_dt64arrrF   r?   libalgosunique_deltasr   rD   _n_freqrH   
_with_freq)rG   r`   r   r8   r   adjustrH   new_parrnew_datadtadiffsdiffrK   rK   rL   rv   \  s8   





zPeriodArray.to_timestampc                 C  s   t j|| jdS )N)r   r`   )r   _from_ordinalr`   )rG   rT   rK   rK   rL   	_box_func  s   zPeriodArray._box_funcPeriodIndex)r   
other_namer   c           
      C  s   t |}t|}| jj}|j}| j}|dk}|r#|| jj	 d }n|}t
||||}| jr4t|| j< t|}	t| ||	dS )a  
        Convert the {klass} to the specified frequency `freq`.

        Equivalent to applying :meth:`pandas.Period.asfreq` with the given arguments
        to each :class:`~pandas.Period` in this {klass}.

        Parameters
        ----------
        freq : str
            A frequency.
        how : str {{'E', 'S'}}, default 'E'
            Whether the elements should be aligned to the end
            or start within pa period.

            * 'E', 'END', or 'FINISH' for end,
            * 'S', 'START', or 'BEGIN' for start.

            January 31st ('END') vs. January 1st ('START') for example.

        Returns
        -------
        {klass}
            The transformed {klass} with the new frequency.

        See Also
        --------
        {other}.asfreq: Convert each Period in a {other_name} to the given frequency.
        Period.asfreq : Convert a :class:`~pandas.Period` object to the given frequency.

        Examples
        --------
        >>> pidx = pd.period_range('2010-01-01', '2015-01-01', freq='A')
        >>> pidx
        PeriodIndex(['2010', '2011', '2012', '2013', '2014', '2015'],
        dtype='period[A-DEC]')

        >>> pidx.asfreq('M')
        PeriodIndex(['2010-12', '2011-12', '2012-12', '2013-12', '2014-12',
        '2015-12'], dtype='period[M]')

        >>> pidx.asfreq('M', how='S')
        PeriodIndex(['2010-01', '2011-01', '2012-01', '2013-01', '2014-01',
        '2015-01'], dtype='period[M]')
        r   r   r   )r   r   r   r   ry   rE   r   rF   rD   r   r!   _hasnar   r   r(   r   )
rG   r`   r   base1base2rF   r   r   r   rD   rK   rK   rL   rw     s   
.

zPeriodArray.asfreqboxedc                 C  s   |rt S djS )Nz'{}')r@   format)rG   r   rK   rK   rL   
_formatter  s   zPeriodArray._formatterr   )na_repdate_formatr   str | floatnpt.NDArray[np.object_]c                K  s   t | j| jj||S )z3
        actually format my specific types
        )r   period_array_strftimerF   rD   rE   )rG   r   r   kwargsrK   rK   rL   _format_native_types  s   z PeriodArray._format_native_typesTc                   sx   t |}|| jkr|s| S |  S t|tr| |jS t|ds't|t	r4t
|dd }|  |S t j||dS )NMr   r{   )r&   ry   r{   rS   r(   rw   r`   r   is_np_dtyper'   getattrrv   tz_localizesuperastype)rG   rD   r{   r   	__class__rK   rL   r     s   

zPeriodArray.astypeleft$NumpyValueArrayLike | ExtensionArraysideLiteral['left', 'right']sorterNumpySorter | Nonenpt.NDArray[np.intp] | np.intpc                 C  s,   |  |d}| jd}|j|||dS )NM8[ns])r  r  )_validate_setitem_valueviewr   searchsorted)rG   r   r  r  npvaluem8arrrK   rK   rL   r
    s   zPeriodArray.searchsorted)limitr{   methodr2   r  
int | Nonec                C  s4   |  d}|j|||d}|rtd| | jS | S )Nr  )r  r  r{   r6   )r	  _pad_or_backfillr	   rD   )rG   r  r  r{   r   rI   rK   rK   rL   r    s
   
zPeriodArray._pad_or_backfillc                   sD   |d ur|  d}|j||||d}| | jS t j||||dS )Nr  )r   r  r  r{   )r	  fillnarD   r   )rG   r   r  r  r{   r   rI   r   rK   rL   r  &  s
   
zPeriodArray.fillnar   np.ndarray | intopCallable[[Any, Any], Any]c                 C  sJ   |t jt jfv s
J |t ju r| }tj| j|| jd}t| || jdS )z
        Add or subtract array of integers.

        Parameters
        ----------
        other : np.ndarray[int64] or int
        op : {operator.add, operator.sub}

        Returns
        -------
        result : PeriodArray
        )arr_maskr   )	operatoraddsubr   checked_add_with_arrrF   r   r   rD   )rG   r   r  
res_valuesrK   rK   rL   _addsub_int_array_or_scalar6  s
   
z'PeriodArray._addsub_int_array_or_scalarc                 C  s,   t |trJ | j|dd | |jtjS )NT)rH   )rS   r   r   r  nr  r  r   rK   rK   rL   _add_offsetK  s   zPeriodArray._add_offsetc                   sD   t | jtst| |t|rt |S tt	|j
}| |S )z
        Parameters
        ----------
        other : timedelta, Tick, np.timedelta64

        Returns
        -------
        PeriodArray
        )rS   r`   r   r   r-   r   _add_timedeltalike_scalarr   r   r   asm8_add_timedelta_arraylike)rG   r   tdr   rK   rL   r  R  s   


z%PeriodArray._add_timedeltalike_scalar,TimedeltaArray | npt.NDArray[np.timedelta64]c              
   C  s   | j  std| j  t d| j j d}ztt||ddd}W n ty6 } ztd|d}~ww t	|}t
j| j|d| j|d	}t|| j|B t t| || j d
S )z
        Parameters
        ----------
        other : TimedeltaArray or ndarray[timedelta64]

        Returns
        -------
        PeriodArray
        z2Cannot add or subtract timedelta64[ns] dtype from m8[]FrD   r{   round_okznCannot add/subtract timedelta-like from PeriodArray that is not an integer multiple of the PeriodArray's freq.Nr   )r  b_maskr   )rD   _is_tick_liker   r   
_td64_unitr   r   r   r   isnatr   r  rF   r	  r   putmaskr   r   )rG   r   rD   deltaerrr'  r  rK   rK   rL   r   g  s.   



z$PeriodArray._add_timedelta_arraylikec              
   C  s   | j  sJ t d| j j d}t|ttjtfr$tt	|j
}nt|}z
t||ddd}W n tyE } zt| ||d}~ww |d}t|S )a<  
        Arithmetic operations with timedelta-like scalars or array `other`
        are only valid if `other` is an integer multiple of `self.freq`.
        If the operation is valid, find that integer multiple.  Otherwise,
        raise because the operation is invalid.

        Parameters
        ----------
        other : timedelta, np.timedelta64, Tick,
                ndarray[timedelta64], TimedeltaArray, TimedeltaIndex

        Returns
        -------
        multiple : int or ndarray[int64]

        Raises
        ------
        IncompatibleFrequency
        r#  r$  Fr%  Nr   )rD   r(  r   r)  rS   r   timedelta64r   r   r   r  r   r   r   r	  r   item_from_zerodim)rG   r   rD   r!  r,  r-  rK   rK   rL    _check_timedeltalike_freq_compat  s   


z,PeriodArray._check_timedeltalike_freq_compat)rV   rW   )NNF)rD   rz   r{   r|   rV   r}   )r   r   rD   r(   rV   r6   )rD   rz   r{   r|   rV   r6   rC   )rV   r6   )r   r   rV   r   )r   r@   rV   r   )rV   r}   )rV   r(   )rV   r   )rD   r   rV   r   )rV   r   )Nr   )r   r@   rV   r8   )rV   r   rK   )Nr   )r   r@   rV   r6   )F)r   r|   )r   r   rV   r   )T)r{   r|   )r   N)r   r  r  r  r  r  rV   r  )r  r2   r  r  r{   r|   rV   r6   )NNNT)r  r  r{   r|   rV   r6   )r   r  r  r  rV   r6   )r   r   )r   r"  rV   r6   )JrN   
__module____qualname__rO   __array_priority___typr   r   r   _internal_fill_valuer   _recognized_scalars_is_recognized_dtype_infer_matchesrP   rY   r[   __annotations__r]   ra   rs   rt   rx   r   classmethodr   r   r   r   r   r   r   r   r"   rD   r`   r   r   rQ   rb   rc   rd   re   rf   rg   rh   rj   rl   rk   ri   rm   rn   ro   rp   rq   rr   r\   rv   r   r#   _shared_doc_kwargsrw   r   r   r   r
  r  r  r  r  r  r   r0  __classcell__rK   rK   r   rL   r>   u   s   
 =
'





	
BG


*c                 C  sf   t |tjtfs|du rd}nt |ttttfr|j}nt	t
|j}tjt| j| j|d}t|S )a>  
    Helper function to render a consistent error message when raising
    IncompatibleFrequency.

    Parameters
    ----------
    left : PeriodArray
    right : None, DateOffset, Period, ndarray, or timedelta-like

    Returns
    -------
    IncompatibleFrequency
        Exception to be raised by the caller.
    N)r   own_freq
other_freq)rS   r   r   r,   r*   r>   r   r   r   r   r   r   r   r   rN   r   )r   rightr>  msgrK   rK   rL   r     s   r   Fr   ,Sequence[Period | str | None] | AnyArrayLiker`   str | Tick | BaseOffset | Noner{   r|   rV   c           	      C  s   t | dd}t|drt| |S t|tr-t| }|dur+||jkr&|S ||S |S t| t	j
tttfs;t| } t	| }|rGt|}nd}|jjdkrYt|dkrYtd|jjdv rs|jt	jdd	}t||}t||d
S t|} tj| |d
S )a  
    Construct a new PeriodArray from a sequence of Period scalars.

    Parameters
    ----------
    data : Sequence of Period objects
        A sequence of Period objects. These are required to all have
        the same ``freq.`` Missing values can be indicated by ``None``
        or ``pandas.NaT``.
    freq : str, Tick, or Offset
        The frequency of every element of the array. This can be specified
        to avoid inferring the `freq` from `data`.
    copy : bool, default False
        Whether to ensure a copy of the data is made.

    Returns
    -------
    PeriodArray

    See Also
    --------
    PeriodArray
    pandas.PeriodIndex

    Examples
    --------
    >>> period_array([pd.Period('2017', freq='A'),
    ...               pd.Period('2018', freq='A')])
    <PeriodArray>
    ['2017', '2018']
    Length: 2, dtype: period[A-DEC]

    >>> period_array([pd.Period('2017', freq='A'),
    ...               pd.Period('2018', freq='A'),
    ...               pd.NaT])
    <PeriodArray>
    ['2017', '2018', 'NaT']
    Length: 3, dtype: period[A-DEC]

    Integers that look like years are handled

    >>> period_array([2000, 2001, 2002], freq='D')
    <PeriodArray>
    ['2000-01-01', '2001-01-01', '2002-01-01']
    Length: 3, dtype: period[D]

    Datetime-like strings may also be passed

    >>> period_array(['2000-Q1', '2000-Q2', '2000-Q3', '2000-Q4'], freq='Q')
    <PeriodArray>
    ['2000Q1', '2000Q2', '2000Q3', '2000Q4']
    Length: 4, dtype: period[Q-DEC]
    rD   Nr   rM   r   z9PeriodIndex does not allow floating point in constructioniuFr   r   )r   r   r   r>   r   rS   r(   r`   rw   r   r   r   tupler+   r   rD   kindr   r   r   r   r   from_ordinalsr%   r   )	r   r`   r{   
data_dtypeoutarrdatarD   arrr   rK   rK   rL   period_array  s0   :




rK  c                 C     d S rC   rK   r   rK   rK   rL   r   9  rZ   r   timedelta | str | Noner   c                 C  rL  rC   rK   r   rK   rK   rL   r   >  rZ   $BaseOffsetT | timedelta | str | Nonec                 C  sZ   |durt |}| dur+t| } t| tstd|du r"| j}|S || jkr+td|S )at  
    If both a dtype and a freq are available, ensure they match.  If only
    dtype is available, extract the implied freq.

    Parameters
    ----------
    dtype : dtype
    freq : DateOffset or None

    Returns
    -------
    freq : DateOffset

    Raises
    ------
    ValueError : non-period dtype
    IncompatibleFrequency : mismatch between dtype and freq
    Nzdtype must be PeriodDtypez&specified freq and dtype are different)r   r&   rS   r(   r   r`   r   r   rK   rK   rL   r   C  s   

(tuple[npt.NDArray[np.int64], BaseOffset]c                 C  s   t | jtjr| jjdkrtd| j |du r4t | tr&| j| j} }nt | tr3| j| j	j} }n
t | ttfr>| j} t
| j}t|}|j}t| d|||d|fS )a  
    Convert an datetime-like array to values Period ordinals.

    Parameters
    ----------
    data : Union[Series[datetime64[ns]], DatetimeIndex, ndarray[datetime64ns]]
    freq : Optional[Union[str, Tick]]
        Must match the `freq` on the `data` if `data` is a DatetimeIndex
        or Series.
    tz : Optional[tzinfo]

    Returns
    -------
    ordinals : ndarray[int64]
    freq : Tick
        The frequency extracted from the Series or DatetimeIndex if that's
        used.

    r   zWrong dtype: Nr   )reso)rS   rD   r   rE  r   r)   r   r`   r+   dtr   r   r   r   c_dt64arr_to_periodarrr	  )r   r`   r   rP  rH   rK   rK   rL   r   k  s   



r   r   multintc                 C  sV  t | ||dkrtd|d urt|}|j}| d ur!t| |} |d ur*t||}t| t}t|t}|rB|rB| j|jkrBtd| tu sJ|tu rNtd|d u re|rX| j}n
|r^|j}ntd|j}|d ur|| }| d u rt	j
|j| | |jd |t	jd}||fS t	j
| j| j| |t	jd}||fS t	j
| j|jd |t	jd}||fS )N   zOOf the three parameters: start, end, and periods, exactly two must be specifiedz!start and end must have same freqzstart and end must not be NaTz#Could not infer freq from start/endr   r   )comcount_not_noner   r   r  r   rS   r`   r   r   aranger   r   )r   r   r   r`   rS  is_start_per
is_end_perr   rK   rK   rL   r     sJ   




r   tuple[np.ndarray, BaseOffset]c                 C  sN  |d u rd}|d u rd}|d u rd}|d u rd}g }|d urn|d u r+t d}tjj}	nt |}t|}	|	tjjkr>td|j}
t| |\} }t	| |D ]\}}t
|||
\}}t||dddddd|		}|| qMn/t |}t|}	t| |||||}t	| D ]\}}}}}}|t||||||dd|		 qtj|tjd|fS )Nr   r   Qzbase must equal FR_QTRr   )r   r   FR_QTRr   r   freq_to_dtype_codeAssertionErrorr   _make_field_arrayszipr   quarter_to_myearperiod_ordinalappendr   r   r   )rb   rc   ro   rd   re   rf   rg   r`   r   rH   r   yqcalendar_yearcalendar_monthvalarraysmthdhmnsrK   rK   rL   r     s@   



"r   list[np.ndarray]c                    s^   d  | D ]!}t |ttjtfr% d urt| krtd d u r%t| q fdd| D S )NzMismatched Period array lengthsc                   s4   g | ]}t |tjttfrt|nt| qS rK   )rS   r   r   r   r+   r   repeat).0rT   lengthrK   rL   
<listcomp>  s    
z&_make_field_arrays.<locals>.<listcomp>)rS   r   r   r   r+   r   r   )r   rT   rK   rs  rL   r`    s   
r`  rC   )r?   r@   rA   rB   )NF)r   rA  r`   rB  r{   r|   rV   r>   )r`   r;   rV   r;   )r`   rM  rV   r   )r`   rN  rV   r;   )rV   rO  )r   )rS  rT  )NNNNNNNN)rV   r[  )rV   rp  )g
__future__r   datetimer   r  typingr   r   r   r   r   r	   r
   r   numpyr   pandas._libsr   r   r   pandas._libs.arraysr   pandas._libs.tslibsr   r   r   r   r   r   rR  r   r   r   r   r   r   pandas._libs.tslibs.dtypesr   pandas._libs.tslibs.fieldsr   pandas._libs.tslibs.offsetsr   r   pandas._libs.tslibs.periodr   r   r   r    r!   pandas.util._decoratorsr"   r#   pandas.util._exceptionsr$   pandas.core.dtypes.commonr%   r&   pandas.core.dtypes.dtypesr'   r(   pandas.core.dtypes.genericr)   r*   r+   r,   pandas.core.dtypes.missingr-   pandas.core.algorithmscore
algorithmsr   r.   r   pandas.core.commoncommonrV  collections.abcr/   pandas._typingr0   r1   r2   r3   r4   r5   r6   r7   r8   r9   pandas.core.arrays.baser:   r;   r;  rQ   DatelikeOpsPeriodMixinr>   r   rK  r   r   r   r`  rK   rK   rK   rL   <module>   sx    $	4(      H#a
)(21