a
    Of4                     @  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#m$Z$ d dl%m&Z&m'Z'm(Z( d d	l)m*Z* d d
l+m,Z,m-Z- d dl.m/Z/m0Z0m1Z1m2Z2m3Z3 d dl4m5Z5m6Z6 d dl7m8Z8 d dl9m:Z:m;Z; d dl<m=Z=m>Z> d dl?m@Z@mAZAmBZBmCZC d dlDmEZE d dlFmGZH d dlImJ  mKZL erd dlMmNZN d dlOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZW d dlFmXZXmYZY d dlZm[Z[ e
dedZ\ddiZ]dBdddddZ^G d d deHj_e#j`Zad!d"d#d$ZbdCd&d'd(dd)d*d+Zceddd,d-d.Zded/d0d,d1d.Zdd2dd,d3d.ZddDd4d"d5d6ZdEd8d9d:d;ZedFd<d"d=d>Zfd?d"d@dAZgdS )G    )annotations)	timedeltaN)TYPE_CHECKINGAnyCallableLiteralTypeVarcastoverload)algoslib)NDArrayBacked)
BaseOffsetNaTNaTType	Timedeltaadd_overflowsafeastype_overflowsafedt64arr_to_periodarrget_unit_from_dtypeiNaTparsingperiod	to_offset)	FreqGroupPeriodDtypeBasefreq_to_period_freqstr)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strz
str | None)name	docstringc                   s     fdd} |_ ||_t|S )Nc                   s   | j j}t | j|}|S N)dtype_dtype_coder#   asi8)selfbaseresultrC    R/var/www/ai-form-bot/venv/lib/python3.9/site-packages/pandas/core/arrays/period.pyfm   s    z_field_accessor.<locals>.f)__name____doc__property)rC   rD   rO   rM   rL   rN   _field_accessorl   s    rS   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ddd	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< dddddddZed dd!d"d#d$Zeddd%ddd!dd&d'Zeddd%ddd!dd(d)Zedd!dd*d+Zed,d- Zed.d!d/d0d1Zd2d3d4d5d6Zd7d8d4d9d:Z d;dd<d=d>Z!e"ddd?d@Z#edAddBdCZ$ed7ddDdEZ%ddFdGdHddIdJZ&ddKdLZ'e(dMdNZ)e(dOdPZ*e(dQdRZ+e(dSdTZ,e(dUdVZ-e(dWdXZ.e(dYdZZ/e/Z0e(d[d\Z1e1Z2e2Z3e(d]d^ Z4Z5e(d_d`Z6e(daZ7e(dbdcZ8e8Z9eddddedfZ:dd7dhdidjdkZ;d2ddldmZ<e=f i e>dndndodd7d!didqdrZ?dddsdtduZ@dvddwdxdydzd{d|ZAddd~ fddZBddddddddZCddd}dddddd!dddZDdddd!d fddZEddd!dddZFdAdddZG fddZHdd!d<ddZIdd ZJ  ZKS )rA   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  Zperiodarrayc                 C  s
   t | tS rE   )
isinstancer+   )xrM   rM   rN   <lambda>   s   zPeriodArray.<lambda>)r   ztype[Period]returnc                 C  s   t S rE   )r"   rI   rM   rM   rN   _scalar_type   s    zPeriodArray._scalar_typez	list[str]
_other_opsis_leap_year	_bool_ops)
start_timeZ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+   _dtypeNFzDtype | NoneboolNone)rF   copyrX   c                 C  s  |d ur,t jdtt d t||}t|}|d urVt|}t|tsVtd| dt|t	r~|j
}t|t| stdnt|tr|j
}t|t| r|d ur||jkrt||j|j|j }}|stj|dd}ntj|d|d}|d u rt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rF   rF   r{   z-dtype is not specified and cannot be inferred)warningswarnFutureWarningr'   validate_dtype_freqr+   r)   rT   
ValueErrorr.   _valuestype	TypeErrorr-   rF   raise_on_incompatibler_   _ndarraynpasarrayarrayr	   r   __init__)rI   valuesrF   r_   r{   rM   rM   rN   r      s:    





zPeriodArray.__init__znpt.NDArray[np.int64]r9   )r   rF   rX   c                 C  s.   d}t |tjr|jdks"J || ||dS )Nz Should be numpy array of type i8i8r~   )rT   r   ndarrayrF   )clsr   rF   Zassertion_msgrM   rM   rN   _simple_new  s    zPeriodArray._simple_newr   c                C  s   |d urt |}|r&t|tr&|j}nd }t|| rPt|j| |rL| }|S tj|t	d}|pjt
|}t
||}t|}| ||dS )Nr~   )r)   rT   r+   r_   r   rF   r{   r   r   object	libperiodextract_freqZextract_ordinals)r   ZscalarsrF   r{   r_   periodsordinalsrM   rM   rN   _from_sequence  s    
zPeriodArray._from_sequencec                C  s   | j |||dS )Nr   )r   )r   stringsrF   r{   rM   rM   rN   _from_sequence_of_strings4  s    z%PeriodArray._from_sequence_of_stringsc                 C  s<   t |trt|j|j}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~   )rT   r   r   nrC   r   r+   )r   datar_   tzrF   rM   rM   rN   _from_datetime64:  s
    
zPeriodArray._from_datetime64c                 C  sP   t |}|d urt|}|d us,|d ur@t||||\}}ntd||fS )Nz/Not enough parameters to construct Period range)dtlZvalidate_periodsr"   _maybe_convert_freq_get_ordinal_ranger   )r   startendr   r_   subarrrM   rM   rN   _generate_rangeO  s    

zPeriodArray._generate_rangedict)fieldsrX   c                C  s,   t f d|i|\}}t|}| j||dS )Nr_   r~   )_range_from_fieldsr+   r   )r   r   r_   r   rF   rM   rM   rN   _from_fields]  s    zPeriodArray._from_fieldszPeriod | NaTTypeznp.int64)valuerX   c                 C  sJ   |t u rt|jS t|| jr6| | t|jS td| dd S )Nz!'value' should be a Period. Got 'z
' instead.)	r   r   r}   _valuerT   rZ   _check_compatible_withordinalr   rI   r   rM   rM   rN   _unbox_scalari  s    
zPeriodArray._unbox_scalarrB   r"   c                 C  s   t || jdS )N)r_   )r"   r_   r   rM   rM   rN   _scalar_from_stringv  s    zPeriodArray._scalar_from_stringzPeriod | NaTType | PeriodArray)otherrX   c                 C  s   |t u rd S | |j d S rE   )r   _require_matching_freqr_   rI   r   rM   rM   rN   r   |  s    z"PeriodArray._check_compatible_withc                 C  s   | j S rE   )rx   rY   rM   rM   rN   rF     s    zPeriodArray.dtyper   c                 C  s   | j jS )zC
        Return the frequency object for this PeriodArray.
        rF   r_   rY   rM   rM   rN   r_     s    zPeriodArray.freqc                 C  s   t | jj| jjS rE   )r   r_   r   rC   rY   rM   rM   rN   freqstr  s    zPeriodArray.freqstrzNpDtype | Nonezbool | Nonez
np.ndarrayc                 C  s0   |dkr| j S |tkr| j S tjt| tdS )Nr   r~   )rH   ry   _isnanr   r   listr   )rI   rF   r{   rM   rM   rN   	__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||rp| j	|j
krt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}   )pyarrowZ(pandas.core.arrays.arrow.extension_typesr   types
is_integerr   r   r0   rT   r   r_   r   r=   Zfrom_storage)rI   r   r   r   Zperiod_typeZstorage_arrayrM   rM   rN   __arrow_array__  s(    


zPeriodArray.__arrow_array__ra   z
        The year of the period.

        Examples
        --------
        >>> idx = pd.PeriodIndex(["2023", "2024", "2025"], freq="Y")
        >>> idx.year
        Index([2023, 2024, 2025], dtype='int64')
        rb   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')
        rc   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')
        rd   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')
        re   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')
        rf   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')
        ri   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')
        rk   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')
        rm   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[Y-DEC]')
        >>> idx.dayofyear
        Index([365, 366, 365], dtype='int64')
        rn   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')
        ro   rp   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')
        z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   ra   rY   rM   rM   rN   r\   b  s    zPeriodArray.is_leap_yearr   r;   )howrX   c                 C  sD  ddl m} t|}|dk}|rx|dks4| jdkrXtddtdd }| jdd	| S tdd}| | j jdd	| S |d
u r| j }t	|d}|j
}|}nt|}|j}| j||d	}	t|	j|}
||
}| jjdkr6t| j}t|dkr2|d }|| jjkr| j|_n|dkr2| jj|_|S |d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   )r;   EB   Dnsr   )r   NZinfer)pandas.core.arraysr;   r   validate_end_aliasr_   r   ru   rx   Z_get_to_timestamp_baser   _freqstrr"   r   _period_dtype_coderv   Zperiodarr_to_dt64arrrH   r   rC   libalgosZunique_deltaslenrF   _nZ_freqrJ   Z
_with_freq)rI   r_   r   r;   r   adjustZ	freq_coderF   rJ   Znew_parrnew_datadtaZdiffsdiffrM   rM   rN   ru   o  s:    








zPeriodArray.to_timestampc                 C  s   t j|| jdS )N)r   r_   )r"   Z_from_ordinalr_   )rI   rU   rM   rM   rN   	_box_func  s    zPeriodArray._box_funcZPeriodIndex)r   Z
other_namer   c           
      C  s   t |}t|tr(t|dr(t|j}t|}| j	j
}|j}| j}|dk}|rd|| jj d }n|}t||||}| jrt|| 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='Y')
        >>> pidx
        PeriodIndex(['2010', '2011', '2012', '2013', '2014', '2015'],
        dtype='period[Y-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   rT   r   hasattrr+   r   r"   r   rx   rG   r   rH   rF   r   r$   Z_hasnar   r   r   )
rI   r_   r   Zbase1Zbase2rH   r   r   r   rF   rM   rM   rN   rv     s     .



zPeriodArray.asfreq)boxedc                 C  s   |rt S djS )Nz'{}')rB   format)rI   r   rM   rM   rN   
_formatter  s    zPeriodArray._formatterr   )na_repdate_formatzstr | floatznpt.NDArray[np.object_])r   rX   c                K  s   t | j| jj||S )z3
        actually format my specific types
        )r   Zperiod_array_strftimerH   rF   rG   )rI   r   r   kwargsrM   rM   rN   _format_native_types  s    z PeriodArray._format_native_typesTr{   c                   s   t |}|| jkr"|s| S |  S t|tr8| |jS t|dsNt|t	rxt
|dd }t|}|  ||S t j||dS )NMr   r   )r)   rx   r{   rT   r+   rv   r_   r   is_np_dtyper*   getattrr   Zdtype_to_unitru   Ztz_localizeZas_unitsuperastype)rI   rF   r{   r   unit	__class__rM   rN   r     s    


zPeriodArray.astypeleftz$NumpyValueArrayLike | ExtensionArrayzLiteral['left', 'right']zNumpySorter | Noneznpt.NDArray[np.intp] | np.intp)r   sidesorterrX   c                 C  s,   |  |d}| jd}|j|||dS )NM8[ns])r   r   )Z_validate_setitem_valueviewr   searchsorted)rI   r   r   r   ZnpvalueZm8arrrM   rM   rN   r   $  s    zPeriodArray.searchsorted)limit
limit_arear{   r5   z
int | Nonez#Literal['inside', 'outside'] | None)methodr   r   r{   rX   c                C  s:   |  d}|j||||d}|r2td| | jS | S d S )Nr   )r   r   r   r{   r9   )r   _pad_or_backfillr	   rF   )rI   r   r   r   r{   r   rK   rM   rM   rN   r   1  s    

zPeriodArray._pad_or_backfill)r   r{   rX   c                   sD   |d ur0|  d}|j||||d}| | jS t j||||dS )Nr   )r   r   r   r{   )r   fillnarF   r   )rI   r   r   r   r{   r   rK   r   rM   rN   r   D  s
    
zPeriodArray.fillnaznp.ndarray | intzCallable[[Any, Any], Any])r   oprX   c                 C  sL   |t jt jfv sJ |t ju r$| }t| jtj|d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
        r   r~   )	operatoraddsubr   rH   r   r   r   rF   )rI   r   r   
res_valuesrM   rM   rN   _addsub_int_array_or_scalarT  s
    
z'PeriodArray._addsub_int_array_or_scalar)r   c                 C  s,   t |trJ | j|dd | |jtjS )NT)rJ   )rT   r   r   r   r   r   r   r   rM   rM   rN   _add_offseti  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
        )rT   r_   r   r   r0   r   _add_timedeltalike_scalarr   r   r   asm8_add_timedelta_arraylike)rI   r   tdr   rM   rN   r   p  s    

z%PeriodArray._add_timedeltalike_scalarz,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yx } ztd|W Y d}~n
d}~0 0 t	| j
t|d}t| || j d	S )
z
        Parameters
        ----------
        other : TimedeltaArray or ndarray[timedelta64]

        Returns
        -------
        PeriodArray
        z2Cannot add or subtract timedelta64[ns] dtype from m8[]FrF   r{   Zround_okznCannot add/subtract timedelta-like from PeriodArray that is not an integer multiple of the PeriodArray's freq.Nr   r~   )rF   _is_tick_liker   r   
_td64_unitr   r   r   r!   r   rH   r   r   )rI   r   rF   deltaerrr   rM   rM   rN   r     s"    


z$PeriodArray._add_timedelta_arraylikec              
   C  s   | j  sJ t d| j j d}t|ttjtfrHtt	|j
}n
t|}zt||ddd}W n0 ty } zt| ||W Y d}~n
d}~0 0 |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   )rF   r   r   r   rT   r   Ztimedelta64r   r   r   r   r   r   r   r   r   Zitem_from_zerodim)rI   r   rF   r   r   r   rM   rM   rN    _check_timedeltalike_freq_compat  s    
"
z,PeriodArray._check_timedeltalike_freq_compat)NNF)N)NN)N)Nr   )Nr   )F)T)r   N)NNNT)LrP   
__module____qualname__rQ   Z__array_priority__Z_typr   r}   r   Z_internal_fill_valuer"   Z_recognized_scalarsZ_is_recognized_dtypeZ_infer_matchesrR   rZ   r[   __annotations__r]   r`   rr   rs   rw   r   classmethodr   r   r   r   r   r   r   r   r   r%   rF   r_   r   r   r   rS   ra   rb   rc   rd   re   rf   rg   ri   rk   rj   rh   rl   rm   rn   ro   rp   rq   r\   ru   r   r&   _shared_doc_kwargsrv   r   r   r   r   r   r   r   r   r   r   r   __classcell__rM   rM   r   rN   rA   y   s   
=
 *


 
DH   %r!   rW   c                 C  s   t |tjtfs|du rd}n@t |tr8t|j|j}n&t |tt	t
frP|j}ntt|j}t| jj| jj}tjt| 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)rT   r   r   r/   r   r   r   rC   r-   rA   r"   r   r   r   r_   r    r   r   rP   r!   )r   rightr  r  msgrM   rM   rN   r     s    
r   Fz,Sequence[Period | str | None] | AnyArrayLikezstr | Tick | BaseOffset | Nonery   )r   r_   r{   rX   c           	      C  s  t | dd}t|dr$t| |S t|trZt| }|durV||jkrL|S ||S |S t| t	j
tttfsvt| } t	| }|rt|}nd}|jjdkrt|dkrtd|jjdv r|jt	jdd	}t||}t||d
S t|} |du rt| }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='Y'),
    ...               pd.Period('2018', freq='Y')])
    <PeriodArray>
    ['2017', '2018']
    Length: 2, dtype: period[Y-DEC]

    >>> period_array([pd.Period('2017', freq='Y'),
    ...               pd.Period('2018', freq='Y'),
    ...               pd.NaT])
    <PeriodArray>
    ['2017', '2018', 'NaT']
    Length: 3, dtype: period[Y-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]
    rF   Nr   rO   r   z9PeriodIndex does not allow floating point in constructioniuFr   r~   )r   r   r   rA   r   rT   r+   r_   rv   r   r   r   tupler.   r   rF   kindr   r   r   r}   r   Zfrom_ordinalsr(   r   r   )	r   r_   r{   Z
data_dtypeoutZarrdatarF   Zarrr   rM   rM   rN   period_array  s6    :






r  )r_   rX   c                 C  s   d S rE   rM   r   rM   rM   rN   r   W  s    r   ztimedelta | str | Noner   c                 C  s   d S rE   rM   r   rM   rM   rN   r   \  s    z1BaseOffsetT | BaseOffset | timedelta | str | Nonec                 C  s\   |durt |dd}| durXt| } t| ts6td|du rF| j}n|| jkrXt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
    NTZ	is_periodzdtype must be PeriodDtypez&specified freq and dtype are different)r   r)   rT   r+   r   r_   r!   r   rM   rM   rN   r   a  s    

z(tuple[npt.NDArray[np.int64], BaseOffset]c                 C  s   t | jtjr| jjdkr*td| j |du rht | trL| j| j } }q|t | tr|| 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)rT   rF   r   r  r   r,   r   r_   r.   dtr   r"   r   r   c_dt64arr_to_periodarrr   )r   r_   r   r  rJ   rM   rM   rN   r     s    



r   r   int)multc                 C  sR  t | ||dkrtd|d ur4t|dd}|j}| d urFt| |} |d urXt||}t| t}t|t}|r|r| j|jkrtd| tu s|tu rtd|d u r|r| j}n|r|j}ntd|j}|d ur.|| }| d u rt	j
|j| | |jd |t	jd	}nt	j
| j| j| |t	jd	}nt	j
| j|jd |t	jd	}||fS )
N   zOOf the three parameters: start, end, and periods, exactly two must be specifiedTr  z!start and end must have same freqzstart and end must not be NaTz#Could not infer freq from start/endr   r~   )comZcount_not_noner   r   r   r"   rT   r_   r   r   Zaranger   r}   )r   r   r   r_   r  Zis_start_perZ
is_end_perr   rM   rM   rN   r     sF    





r   ztuple[np.ndarray, BaseOffset]c                 C  s\  |d u rd}|d u rd}|d u r$d}|d u r0d}g }|d ur|d u rZt ddd}tjj}	n*t |dd}t|}	|	tjjkrtd|j}
t| |\} }t	| |D ]>\}}t
|||
\}}t||dddddd|		}|| qndt |dd}t|}	t| |||||}t	| D ]2\}}}}}}|t||||||dd|		 qtj|tjd|fS )Nr   r   QTr  zbase must equal FR_QTRr~   )r   r   ZFR_QTRr   r   Zfreq_to_dtype_codeAssertionErrorr   _make_field_arrayszipr   Zquarter_to_myearZperiod_ordinalappendr   r   r}   )ra   rb   rn   rc   rd   re   rf   r_   r   rJ   r   yqZcalendar_yearZcalendar_monthvalZarraysZmthdhZmnsrM   rM   rN   r     s>    



$r   zlist[np.ndarray]c                    s^   d  | D ]B}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 rM   )rT   r   r   r   r.   r   repeat).0rU   lengthrM   rN   
<listcomp>  s   z&_make_field_arrays.<locals>.<listcomp>)rT   r   r   r   r.   r   r   )r   rU   rM   r%  rN   r    s    

r  )N)NF)N)r   )NNNNNNNN)h
__future__r   datetimer   r   typingr   r   r   r   r   r	   r
   r   numpyr   Zpandas._libsr   r   r   Zpandas._libs.arraysr   Zpandas._libs.tslibsr   r   r   r   r   r   r   r  r   r   r   r   r   r   Zpandas._libs.tslibs.dtypesr   r   r   Zpandas._libs.tslibs.fieldsr   Zpandas._libs.tslibs.offsetsr   r   Zpandas._libs.tslibs.periodr    r!   r"   r#   r$   Zpandas.util._decoratorsr%   r&   Zpandas.util._exceptionsr'   Zpandas.core.dtypes.commonr(   r)   Zpandas.core.dtypes.dtypesr*   r+   Zpandas.core.dtypes.genericr,   r-   r.   r/   Zpandas.core.dtypes.missingr0   r   r1   r   Zpandas.core.commoncorecommonr  collections.abcr2   Zpandas._typingr3   r4   r5   r6   r7   r8   r9   r:   r;   r<   Zpandas.core.arrays.baser=   r>   r  rS   ZDatelikeOpsZPeriodMixinrA   r   r  r   r   r   r  rM   rM   rM   rN   <module>   st   $	8(      ]&  c& (2        1