forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathperiod.py
1453 lines (1221 loc) · 44.9 KB
/
period.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
from datetime import timedelta
import operator
from typing import (
TYPE_CHECKING,
Any,
Literal,
TypeVar,
cast,
overload,
)
import warnings
import numpy as np
from pandas._libs import (
algos as libalgos,
lib,
)
from pandas._libs.arrays import NDArrayBacked
from pandas._libs.tslibs import (
BaseOffset,
NaT,
NaTType,
Timedelta,
add_overflowsafe,
astype_overflowsafe,
dt64arr_to_periodarr as c_dt64arr_to_periodarr,
get_unit_from_dtype,
iNaT,
parsing,
period as libperiod,
to_offset,
)
from pandas._libs.tslibs.dtypes import (
FreqGroup,
PeriodDtypeBase,
)
from pandas._libs.tslibs.fields import isleapyear_arr
from pandas._libs.tslibs.offsets import (
Tick,
delta_to_tick,
)
from pandas._libs.tslibs.period import (
DIFFERENT_FREQ,
IncompatibleFrequency,
Period,
get_period_field_arr,
period_asfreq_arr,
)
from pandas.util._decorators import (
cache_readonly,
doc,
)
from pandas.core.dtypes.common import (
ensure_object,
pandas_dtype,
)
from pandas.core.dtypes.dtypes import (
DatetimeTZDtype,
PeriodDtype,
)
from pandas.core.dtypes.generic import (
ABCIndex,
ABCPeriodIndex,
ABCSeries,
ABCTimedeltaArray,
)
from pandas.core.dtypes.missing import isna
from pandas.core.arrays import datetimelike as dtl
import pandas.core.common as com
if TYPE_CHECKING:
from collections.abc import (
Callable,
Sequence,
)
from pandas._typing import (
AnyArrayLike,
Dtype,
FillnaOptions,
NpDtype,
NumpySorter,
NumpyValueArrayLike,
Self,
npt,
)
from pandas.core.dtypes.dtypes import ExtensionDtype
from pandas.core.arrays import (
DatetimeArray,
TimedeltaArray,
)
from pandas.core.arrays.base import ExtensionArray
BaseOffsetT = TypeVar("BaseOffsetT", bound=BaseOffset)
_shared_doc_kwargs = {
"klass": "PeriodArray",
}
def _field_accessor(name: str, docstring: str | None = None):
def f(self):
base = self.dtype._dtype_code
result = get_period_field_arr(name, self.asi8, base)
return result
f.__name__ = name
f.__doc__ = docstring
return property(f)
# error: Definition of "_concat_same_type" in base class "NDArrayBacked" is
# incompatible with definition in base class "ExtensionArray"
class PeriodArray(dtl.DatelikeOps, libperiod.PeriodMixin): # type: ignore[misc]
"""
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.
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]
"""
# array priority higher than numpy scalars
__array_priority__ = 1000
_typ = "periodarray" # ABCPeriodArray
_internal_fill_value = np.int64(iNaT)
_recognized_scalars = (Period,)
_is_recognized_dtype = lambda x: isinstance(
x, PeriodDtype
) # check_compatible_with checks freq match
_infer_matches = ("period",)
@property
def _scalar_type(self) -> type[Period]:
return Period
# Names others delegate to us
_other_ops: list[str] = []
_bool_ops: list[str] = ["is_leap_year"]
_object_ops: list[str] = ["start_time", "end_time", "freq"]
_field_ops: list[str] = [
"year",
"month",
"day",
"hour",
"minute",
"second",
"weekofyear",
"weekday",
"week",
"dayofweek",
"day_of_week",
"dayofyear",
"day_of_year",
"quarter",
"qyear",
"days_in_month",
"daysinmonth",
]
_datetimelike_ops: list[str] = _field_ops + _object_ops + _bool_ops
_datetimelike_methods: list[str] = ["strftime", "to_timestamp", "asfreq"]
_dtype: PeriodDtype
# --------------------------------------------------------------------
# Constructors
def __init__(self, values, dtype: Dtype | None = None, copy: bool = False) -> None:
if dtype is not None:
dtype = pandas_dtype(dtype)
if not isinstance(dtype, PeriodDtype):
raise ValueError(f"Invalid dtype {dtype} for PeriodArray")
if isinstance(values, ABCSeries):
values = values._values
if not isinstance(values, type(self)):
raise TypeError("Incorrect dtype")
elif isinstance(values, ABCPeriodIndex):
values = values._values
if isinstance(values, type(self)):
if dtype is not None and dtype != values.dtype:
raise raise_on_incompatible(values, dtype.freq)
values, dtype = values._ndarray, values.dtype
if not copy:
values = np.asarray(values, dtype="int64")
else:
values = np.array(values, dtype="int64", copy=copy)
if dtype is None:
raise ValueError("dtype is not specified and cannot be inferred")
dtype = cast(PeriodDtype, dtype)
NDArrayBacked.__init__(self, values, dtype)
# error: Signature of "_simple_new" incompatible with supertype "NDArrayBacked"
@classmethod
def _simple_new( # type: ignore[override]
cls,
values: npt.NDArray[np.int64],
dtype: PeriodDtype,
) -> Self:
# alias for PeriodArray.__init__
assertion_msg = "Should be numpy array of type i8"
assert isinstance(values, np.ndarray) and values.dtype == "i8", assertion_msg
return cls(values, dtype=dtype)
@classmethod
def _from_sequence(
cls,
scalars,
*,
dtype: Dtype | None = None,
copy: bool = False,
) -> Self:
if dtype is not None:
dtype = pandas_dtype(dtype)
if dtype and isinstance(dtype, PeriodDtype):
freq = dtype.freq
else:
freq = None
if isinstance(scalars, cls):
validate_dtype_freq(scalars.dtype, freq)
if copy:
scalars = scalars.copy()
return scalars
periods = np.asarray(scalars, dtype=object)
freq = freq or libperiod.extract_freq(periods)
ordinals = libperiod.extract_ordinals(periods, freq)
dtype = PeriodDtype(freq)
return cls(ordinals, dtype=dtype)
@classmethod
def _from_sequence_of_strings(
cls, strings, *, dtype: ExtensionDtype, copy: bool = False
) -> Self:
return cls._from_sequence(strings, dtype=dtype, copy=copy)
@classmethod
def _from_datetime64(cls, data, freq, tz=None) -> Self:
"""
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]
"""
if isinstance(freq, BaseOffset):
freq = PeriodDtype(freq)._freqstr
data, freq = dt64arr_to_periodarr(data, freq, tz)
dtype = PeriodDtype(freq)
return cls(data, dtype=dtype)
@classmethod
def _generate_range(cls, start, end, periods, freq):
periods = dtl.validate_periods(periods)
if freq is not None:
freq = Period._maybe_convert_freq(freq)
if start is not None or end is not None:
subarr, freq = _get_ordinal_range(start, end, periods, freq)
else:
raise ValueError("Not enough parameters to construct Period range")
return subarr, freq
@classmethod
def _from_fields(cls, *, fields: dict, freq) -> Self:
subarr, freq = _range_from_fields(freq=freq, **fields)
dtype = PeriodDtype(freq)
return cls._simple_new(subarr, dtype=dtype)
# -----------------------------------------------------------------
# DatetimeLike Interface
# error: Argument 1 of "_unbox_scalar" is incompatible with supertype
# "DatetimeLikeArrayMixin"; supertype defines the argument type as
# "Union[Union[Period, Any, Timedelta], NaTType]"
def _unbox_scalar( # type: ignore[override]
self,
value: Period | NaTType,
) -> np.int64:
if value is NaT:
# error: Item "Period" of "Union[Period, NaTType]" has no attribute "value"
return np.int64(value._value) # type: ignore[union-attr]
elif isinstance(value, self._scalar_type):
self._check_compatible_with(value)
return np.int64(value.ordinal)
else:
raise ValueError(f"'value' should be a Period. Got '{value}' instead.")
def _scalar_from_string(self, value: str) -> Period:
return Period(value, freq=self.freq)
# error: Argument 1 of "_check_compatible_with" is incompatible with
# supertype "DatetimeLikeArrayMixin"; supertype defines the argument type
# as "Period | Timestamp | Timedelta | NaTType"
def _check_compatible_with(self, other: Period | NaTType | PeriodArray) -> None: # type: ignore[override]
if other is NaT:
return
# error: Item "NaTType" of "Period | NaTType | PeriodArray" has no
# attribute "freq"
self._require_matching_freq(other.freq) # type: ignore[union-attr]
# --------------------------------------------------------------------
# Data / Attributes
@cache_readonly
def dtype(self) -> PeriodDtype:
return self._dtype
# error: Cannot override writeable attribute with read-only property
@property # type: ignore[override]
def freq(self) -> BaseOffset:
"""
Return the frequency object for this PeriodArray.
"""
return self.dtype.freq
@property
def freqstr(self) -> str:
return PeriodDtype(self.freq)._freqstr
def __array__(
self, dtype: NpDtype | None = None, copy: bool | None = None
) -> np.ndarray:
if dtype == "i8":
return self.asi8
elif dtype == bool:
return ~self._isnan
# This will raise TypeError for non-object dtypes
return np.array(list(self), dtype=object)
def __arrow_array__(self, type=None):
"""
Convert myself into a pyarrow Array.
"""
import pyarrow
from pandas.core.arrays.arrow.extension_types import ArrowPeriodType
if type is not None:
if pyarrow.types.is_integer(type):
return pyarrow.array(self._ndarray, mask=self.isna(), type=type)
elif isinstance(type, ArrowPeriodType):
# ensure we have the same freq
if self.freqstr != type.freq:
raise TypeError(
"Not supported to convert PeriodArray to array with different "
f"'freq' ({self.freqstr} vs {type.freq})"
)
else:
raise TypeError(
f"Not supported to convert PeriodArray to '{type}' type"
)
period_type = ArrowPeriodType(self.freqstr)
storage_array = pyarrow.array(self._ndarray, mask=self.isna(), type="int64")
return pyarrow.ExtensionArray.from_storage(period_type, storage_array)
# --------------------------------------------------------------------
# Vectorized analogues of Period properties
year = _field_accessor(
"year",
"""
The year of the period.
See Also
--------
PeriodIndex.day_of_year : The ordinal day of the year.
PeriodIndex.dayofyear : The ordinal day of the year.
PeriodIndex.is_leap_year : Logical indicating if the date belongs to a
leap year.
PeriodIndex.weekofyear : The week ordinal of the year.
PeriodIndex.year : The year of the period.
Examples
--------
>>> idx = pd.PeriodIndex(["2023", "2024", "2025"], freq="Y")
>>> idx.year
Index([2023, 2024, 2025], dtype='int64')
""",
)
month = _field_accessor(
"month",
"""
The month as January=1, December=12.
See Also
--------
PeriodIndex.days_in_month : The number of days in the month.
PeriodIndex.daysinmonth : The number of days in the month.
Examples
--------
>>> idx = pd.PeriodIndex(["2023-01", "2023-02", "2023-03"], freq="M")
>>> idx.month
Index([1, 2, 3], dtype='int64')
""",
)
day = _field_accessor(
"day",
"""
The days of the period.
See Also
--------
PeriodIndex.day_of_week : The day of the week with Monday=0, Sunday=6.
PeriodIndex.day_of_year : The ordinal day of the year.
PeriodIndex.dayofweek : The day of the week with Monday=0, Sunday=6.
PeriodIndex.dayofyear : The ordinal day of the year.
PeriodIndex.days_in_month : The number of days in the month.
PeriodIndex.daysinmonth : The number of days in the month.
PeriodIndex.weekday : The day of the week with Monday=0, Sunday=6.
Examples
--------
>>> idx = pd.PeriodIndex(['2020-01-31', '2020-02-28'], freq='D')
>>> idx.day
Index([31, 28], dtype='int64')
""",
)
hour = _field_accessor(
"hour",
"""
The hour of the period.
See Also
--------
PeriodIndex.minute : The minute of the period.
PeriodIndex.second : The second of the period.
PeriodIndex.to_timestamp : Cast to DatetimeArray/Index.
Examples
--------
>>> idx = pd.PeriodIndex(["2023-01-01 10:00", "2023-01-01 11:00"], freq='h')
>>> idx.hour
Index([10, 11], dtype='int64')
""",
)
minute = _field_accessor(
"minute",
"""
The minute of the period.
See Also
--------
PeriodIndex.hour : The hour of the period.
PeriodIndex.second : The second of the period.
PeriodIndex.to_timestamp : Cast to DatetimeArray/Index.
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')
""",
)
second = _field_accessor(
"second",
"""
The second of the period.
See Also
--------
PeriodIndex.hour : The hour of the period.
PeriodIndex.minute : The minute of the period.
PeriodIndex.to_timestamp : Cast to DatetimeArray/Index.
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')
""",
)
weekofyear = _field_accessor(
"week",
"""
The week ordinal of the year.
See Also
--------
PeriodIndex.day_of_week : The day of the week with Monday=0, Sunday=6.
PeriodIndex.dayofweek : The day of the week with Monday=0, Sunday=6.
PeriodIndex.week : The week ordinal of the year.
PeriodIndex.weekday : The day of the week with Monday=0, Sunday=6.
PeriodIndex.year : The year of the period.
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')
""",
)
week = weekofyear
day_of_week = _field_accessor(
"day_of_week",
"""
The day of the week with Monday=0, Sunday=6.
See Also
--------
PeriodIndex.day : The days of the period.
PeriodIndex.day_of_week : The day of the week with Monday=0, Sunday=6.
PeriodIndex.day_of_year : The ordinal day of the year.
PeriodIndex.dayofweek : The day of the week with Monday=0, Sunday=6.
PeriodIndex.dayofyear : The ordinal day of the year.
PeriodIndex.week : The week ordinal of the year.
PeriodIndex.weekday : The day of the week with Monday=0, Sunday=6.
PeriodIndex.weekofyear : The week ordinal of the year.
Examples
--------
>>> idx = pd.PeriodIndex(["2023-01-01", "2023-01-02", "2023-01-03"], freq="D")
>>> idx.weekday
Index([6, 0, 1], dtype='int64')
""",
)
dayofweek = day_of_week
weekday = dayofweek
dayofyear = day_of_year = _field_accessor(
"day_of_year",
"""
The ordinal day of the year.
See Also
--------
PeriodIndex.day : The days of the period.
PeriodIndex.day_of_week : The day of the week with Monday=0, Sunday=6.
PeriodIndex.day_of_year : The ordinal day of the year.
PeriodIndex.dayofweek : The day of the week with Monday=0, Sunday=6.
PeriodIndex.dayofyear : The ordinal day of the year.
PeriodIndex.weekday : The day of the week with Monday=0, Sunday=6.
PeriodIndex.weekofyear : The week ordinal of the year.
PeriodIndex.year : The year of the period.
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')
""",
)
quarter = _field_accessor(
"quarter",
"""
The quarter of the date.
See Also
--------
PeriodIndex.qyear : Fiscal year the Period lies in according to its
starting-quarter.
Examples
--------
>>> idx = pd.PeriodIndex(["2023-01", "2023-02", "2023-03"], freq="M")
>>> idx.quarter
Index([1, 1, 1], dtype='int64')
""",
)
qyear = _field_accessor(
"qyear",
"""
Fiscal year the Period lies in according to its starting-quarter.
The `year` and the `qyear` of the period will be the same if the fiscal
and calendar years are the same. When they are not, the fiscal year
can be different from the calendar year of the period.
Returns
-------
int
The fiscal year of the period.
See Also
--------
PeriodIndex.quarter : The quarter of the date.
PeriodIndex.year : The year of the period.
Examples
--------
If the natural and fiscal year are the same, `qyear` and `year` will
be the same.
>>> per = pd.Period('2018Q1', freq='Q')
>>> per.qyear
2018
>>> per.year
2018
If the fiscal year starts in April (`Q-MAR`), the first quarter of
2018 will start in April 2017. `year` will then be 2017, but `qyear`
will be the fiscal year, 2018.
>>> per = pd.Period('2018Q1', freq='Q-MAR')
>>> per.start_time
Timestamp('2017-04-01 00:00:00')
>>> per.qyear
2018
>>> per.year
2017
""",
)
days_in_month = _field_accessor(
"days_in_month",
"""
The number of days in the month.
See Also
--------
PeriodIndex.day : The days of the period.
PeriodIndex.days_in_month : The number of days in the month.
PeriodIndex.daysinmonth : The number of days in the month.
PeriodIndex.month : The month as January=1, December=12.
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')
""",
)
daysinmonth = days_in_month
@property
def is_leap_year(self) -> npt.NDArray[np.bool_]:
"""
Logical indicating if the date belongs to a leap year.
See Also
--------
PeriodIndex.qyear : Fiscal year the Period lies in according to its
starting-quarter.
PeriodIndex.year : The year of the period.
Examples
--------
>>> idx = pd.PeriodIndex(["2023", "2024", "2025"], freq="Y")
>>> idx.is_leap_year
array([False, True, False])
"""
return isleapyear_arr(np.asarray(self.year))
def to_timestamp(self, freq=None, how: str = "start") -> DatetimeArray:
"""
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
Timestamp representation of given Period-like object.
See Also
--------
PeriodIndex.day : The days of the period.
PeriodIndex.from_fields : Construct a PeriodIndex from fields
(year, month, day, etc.).
PeriodIndex.from_ordinals : Construct a PeriodIndex from ordinals.
PeriodIndex.hour : The hour of the period.
PeriodIndex.minute : The minute of the period.
PeriodIndex.month : The month as January=1, December=12.
PeriodIndex.second : The second of the period.
PeriodIndex.year : The year of the period.
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')
The frequency will not be inferred if the index contains less than
three elements, or if the values of index are not strictly monotonic:
>>> idx = pd.PeriodIndex(["2023-01", "2023-02"], freq="M")
>>> idx.to_timestamp()
DatetimeIndex(['2023-01-01', '2023-02-01'], dtype='datetime64[ns]', freq=None)
>>> idx = pd.PeriodIndex(
... ["2023-01", "2023-02", "2023-02", "2023-03"], freq="2M"
... )
>>> idx.to_timestamp()
DatetimeIndex(['2023-01-01', '2023-02-01', '2023-02-01', '2023-03-01'],
dtype='datetime64[ns]', freq=None)
"""
from pandas.core.arrays import DatetimeArray
how = libperiod.validate_end_alias(how)
end = how == "E"
if end:
if freq == "B" or self.freq == "B":
# roll forward to ensure we land on B date
adjust = Timedelta(1, "D") - Timedelta(1, "ns")
return self.to_timestamp(how="start") + adjust
else:
adjust = Timedelta(1, "ns")
return (self + self.freq).to_timestamp(how="start") - adjust
if freq is None:
freq_code = self._dtype._get_to_timestamp_base()
dtype = PeriodDtypeBase(freq_code, 1)
freq = dtype._freqstr
base = freq_code
else:
freq = Period._maybe_convert_freq(freq)
base = freq._period_dtype_code
new_parr = self.asfreq(freq, how=how)
new_data = libperiod.periodarr_to_dt64arr(new_parr.asi8, base)
dta = DatetimeArray._from_sequence(new_data)
if self.freq.name == "B":
# See if we can retain BDay instead of Day in cases where
# len(self) is too small for infer_freq to distinguish between them
diffs = libalgos.unique_deltas(self.asi8)
if len(diffs) == 1:
diff = diffs[0]
if diff == self.dtype._n:
dta._freq = self.freq
elif diff == 1:
dta._freq = self.freq.base
# TODO: other cases?
return dta
else:
return dta._with_freq("infer")
# --------------------------------------------------------------------
def _box_func(self, x) -> Period | NaTType:
return Period._from_ordinal(ordinal=x, freq=self.freq)
@doc(**_shared_doc_kwargs, other="PeriodIndex", other_name="PeriodIndex")
def asfreq(self, freq=None, how: str = "E") -> Self:
"""
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]')
"""
how = libperiod.validate_end_alias(how)
if isinstance(freq, BaseOffset) and hasattr(freq, "_period_dtype_code"):
freq = PeriodDtype(freq)._freqstr
freq = Period._maybe_convert_freq(freq)
base1 = self._dtype._dtype_code
base2 = freq._period_dtype_code
asi8 = self.asi8
# self.freq.n can't be negative or 0
end = how == "E"
if end:
ordinal = asi8 + self.dtype._n - 1
else:
ordinal = asi8
new_data = period_asfreq_arr(ordinal, base1, base2, end)
if self._hasna:
new_data[self._isnan] = iNaT
dtype = PeriodDtype(freq)
return type(self)(new_data, dtype=dtype)
# ------------------------------------------------------------------
# Rendering Methods
def _formatter(self, boxed: bool = False) -> Callable[[object], str]:
if boxed:
return str
return "'{}'".format
def _format_native_types(
self, *, na_rep: str | float = "NaT", date_format=None, **kwargs
) -> npt.NDArray[np.object_]:
"""
actually format my specific types
"""
return libperiod.period_array_strftime(
self.asi8, self.dtype._dtype_code, na_rep, date_format
)
# ------------------------------------------------------------------
def astype(self, dtype, copy: bool = True):
# We handle Period[T] -> Period[U]
# Our parent handles everything else.
dtype = pandas_dtype(dtype)
if dtype == self._dtype:
if not copy:
return self
else:
return self.copy()
if isinstance(dtype, PeriodDtype):
return self.asfreq(dtype.freq)
if lib.is_np_dtype(dtype, "M") or isinstance(dtype, DatetimeTZDtype):
# GH#45038 match PeriodIndex behavior.
tz = getattr(dtype, "tz", None)
unit = dtl.dtype_to_unit(dtype)
return self.to_timestamp().tz_localize(tz).as_unit(unit)
return super().astype(dtype, copy=copy)
def searchsorted(
self,
value: NumpyValueArrayLike | ExtensionArray,
side: Literal["left", "right"] = "left",
sorter: NumpySorter | None = None,
) -> npt.NDArray[np.intp] | np.intp:
npvalue = self._validate_setitem_value(value).view("M8[ns]")
# Cast to M8 to get datetime-like NaT placement,
# similar to dtl._period_dispatch
m8arr = self._ndarray.view("M8[ns]")
return m8arr.searchsorted(npvalue, side=side, sorter=sorter)
def _pad_or_backfill(
self,
*,
method: FillnaOptions,
limit: int | None = None,
limit_area: Literal["inside", "outside"] | None = None,
copy: bool = True,
) -> Self:
# view as dt64 so we get treated as timelike in core.missing,
# similar to dtl._period_dispatch
dta = self.view("M8[ns]")
result = dta._pad_or_backfill(
method=method, limit=limit, limit_area=limit_area, copy=copy
)
if copy:
return cast("Self", result.view(self.dtype))
else:
return self
# ------------------------------------------------------------------
# Arithmetic Methods
def _addsub_int_array_or_scalar(
self, other: np.ndarray | int, op: Callable[[Any, Any], Any]
) -> Self:
"""
Add or subtract array of integers.
Parameters
----------
other : np.ndarray[int64] or int
op : {operator.add, operator.sub}
Returns
-------
result : PeriodArray
"""
assert op in [operator.add, operator.sub]
if op is operator.sub:
other = -other
res_values = add_overflowsafe(self.asi8, np.asarray(other, dtype="i8"))