-
-
Notifications
You must be signed in to change notification settings - Fork 18k
/
datetimelike.py
2532 lines (2126 loc) · 86.3 KB
/
datetimelike.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 (
datetime,
timedelta,
)
from functools import wraps
import operator
from typing import (
TYPE_CHECKING,
Any,
Literal,
Union,
cast,
final,
overload,
)
import warnings
import numpy as np
from pandas._config import using_string_dtype
from pandas._config.config import get_option
from pandas._libs import (
algos,
lib,
)
from pandas._libs.tslibs import (
BaseOffset,
IncompatibleFrequency,
NaT,
NaTType,
Period,
Resolution,
Tick,
Timedelta,
Timestamp,
add_overflowsafe,
astype_overflowsafe,
get_unit_from_dtype,
iNaT,
ints_to_pydatetime,
ints_to_pytimedelta,
periods_per_day,
to_offset,
)
from pandas._libs.tslibs.fields import (
RoundTo,
round_nsint64,
)
from pandas._libs.tslibs.np_datetime import compare_mismatched_resolutions
from pandas._libs.tslibs.timedeltas import get_unit_for_round
from pandas._libs.tslibs.timestamps import integer_op_not_supported
from pandas._typing import (
ArrayLike,
AxisInt,
DatetimeLikeScalar,
Dtype,
DtypeObj,
F,
InterpolateOptions,
NpDtype,
PositionalIndexer2D,
PositionalIndexerTuple,
ScalarIndexer,
Self,
SequenceIndexer,
TakeIndexer,
TimeAmbiguous,
TimeNonexistent,
npt,
)
from pandas.compat.numpy import function as nv
from pandas.errors import (
AbstractMethodError,
InvalidComparison,
PerformanceWarning,
)
from pandas.util._decorators import (
Appender,
Substitution,
cache_readonly,
)
from pandas.util._exceptions import find_stack_level
from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike
from pandas.core.dtypes.common import (
is_all_strings,
is_integer_dtype,
is_list_like,
is_object_dtype,
is_string_dtype,
pandas_dtype,
)
from pandas.core.dtypes.dtypes import (
ArrowDtype,
CategoricalDtype,
DatetimeTZDtype,
ExtensionDtype,
PeriodDtype,
)
from pandas.core.dtypes.generic import (
ABCCategorical,
ABCMultiIndex,
)
from pandas.core.dtypes.missing import (
is_valid_na_for_dtype,
isna,
)
from pandas.core import (
algorithms,
missing,
nanops,
ops,
)
from pandas.core.algorithms import (
isin,
map_array,
unique1d,
)
from pandas.core.array_algos import datetimelike_accumulations
from pandas.core.arraylike import OpsMixin
from pandas.core.arrays._mixins import (
NDArrayBackedExtensionArray,
ravel_compat,
)
from pandas.core.arrays.arrow.array import ArrowExtensionArray
from pandas.core.arrays.base import ExtensionArray
from pandas.core.arrays.integer import IntegerArray
import pandas.core.common as com
from pandas.core.construction import (
array as pd_array,
ensure_wrapped_if_datetimelike,
extract_array,
)
from pandas.core.indexers import (
check_array_indexer,
check_setitem_lengths,
)
from pandas.core.ops.common import unpack_zerodim_and_defer
from pandas.core.ops.invalid import (
invalid_comparison,
make_invalid_op,
)
from pandas.tseries import frequencies
if TYPE_CHECKING:
from collections.abc import (
Callable,
Iterator,
Sequence,
)
from pandas import Index
from pandas.core.arrays import (
DatetimeArray,
PeriodArray,
TimedeltaArray,
)
DTScalarOrNaT = Union[DatetimeLikeScalar, NaTType]
def _make_unpacked_invalid_op(op_name: str):
op = make_invalid_op(op_name)
return unpack_zerodim_and_defer(op_name)(op)
def _period_dispatch(meth: F) -> F:
"""
For PeriodArray methods, dispatch to DatetimeArray and re-wrap the results
in PeriodArray. We cannot use ._ndarray directly for the affected
methods because the i8 data has different semantics on NaT values.
"""
@wraps(meth)
def new_meth(self, *args, **kwargs):
if not isinstance(self.dtype, PeriodDtype):
return meth(self, *args, **kwargs)
arr = self.view("M8[ns]")
result = meth(arr, *args, **kwargs)
if result is NaT:
return NaT
elif isinstance(result, Timestamp):
return self._box_func(result._value)
res_i8 = result.view("i8")
return self._from_backing_data(res_i8)
return cast(F, new_meth)
# error: Definition of "_concat_same_type" in base class "NDArrayBacked" is
# incompatible with definition in base class "ExtensionArray"
class DatetimeLikeArrayMixin( # type: ignore[misc]
OpsMixin, NDArrayBackedExtensionArray
):
"""
Shared Base/Mixin class for DatetimeArray, TimedeltaArray, PeriodArray
Assumes that __new__/__init__ defines:
_ndarray
and that inheriting subclass implements:
freq
"""
# _infer_matches -> which infer_dtype strings are close enough to our own
_infer_matches: tuple[str, ...]
_is_recognized_dtype: Callable[[DtypeObj], bool]
_recognized_scalars: tuple[type, ...]
_ndarray: np.ndarray
freq: BaseOffset | None
@cache_readonly
def _can_hold_na(self) -> bool:
return True
def __init__(
self, data, dtype: Dtype | None = None, freq=None, copy: bool = False
) -> None:
raise AbstractMethodError(self)
@property
def _scalar_type(self) -> type[DatetimeLikeScalar]:
"""
The scalar associated with this datelike
* PeriodArray : Period
* DatetimeArray : Timestamp
* TimedeltaArray : Timedelta
"""
raise AbstractMethodError(self)
def _scalar_from_string(self, value: str) -> DTScalarOrNaT:
"""
Construct a scalar type from a string.
Parameters
----------
value : str
Returns
-------
Period, Timestamp, or Timedelta, or NaT
Whatever the type of ``self._scalar_type`` is.
Notes
-----
This should call ``self._check_compatible_with`` before
unboxing the result.
"""
raise AbstractMethodError(self)
def _unbox_scalar(
self, value: DTScalarOrNaT
) -> np.int64 | np.datetime64 | np.timedelta64:
"""
Unbox the integer value of a scalar `value`.
Parameters
----------
value : Period, Timestamp, Timedelta, or NaT
Depending on subclass.
Returns
-------
int
Examples
--------
>>> arr = pd.array(np.array(["1970-01-01"], "datetime64[ns]"))
>>> arr._unbox_scalar(arr[0])
numpy.datetime64('1970-01-01T00:00:00.000000000')
"""
raise AbstractMethodError(self)
def _check_compatible_with(self, other: DTScalarOrNaT) -> None:
"""
Verify that `self` and `other` are compatible.
* DatetimeArray verifies that the timezones (if any) match
* PeriodArray verifies that the freq matches
* Timedelta has no verification
In each case, NaT is considered compatible.
Parameters
----------
other
Raises
------
Exception
"""
raise AbstractMethodError(self)
# ------------------------------------------------------------------
def _box_func(self, x):
"""
box function to get object from internal representation
"""
raise AbstractMethodError(self)
def _box_values(self, values) -> np.ndarray:
"""
apply box func to passed values
"""
return lib.map_infer(values, self._box_func, convert=False)
def __iter__(self) -> Iterator:
if self.ndim > 1:
return (self[n] for n in range(len(self)))
else:
return (self._box_func(v) for v in self.asi8)
@property
def asi8(self) -> npt.NDArray[np.int64]:
"""
Integer representation of the values.
Returns
-------
ndarray
An ndarray with int64 dtype.
"""
# do not cache or you'll create a memory leak
return self._ndarray.view("i8")
# ----------------------------------------------------------------
# Rendering Methods
def _format_native_types(
self, *, na_rep: str | float = "NaT", date_format=None
) -> npt.NDArray[np.object_]:
"""
Helper method for astype when converting to strings.
Returns
-------
ndarray[str]
"""
raise AbstractMethodError(self)
def _formatter(self, boxed: bool = False) -> Callable[[object], str]:
# TODO: Remove Datetime & DatetimeTZ formatters.
return "'{}'".format
# ----------------------------------------------------------------
# Array-Like / EA-Interface Methods
def __array__(
self, dtype: NpDtype | None = None, copy: bool | None = None
) -> np.ndarray:
# used for Timedelta/DatetimeArray, overwritten by PeriodArray
if is_object_dtype(dtype):
if copy is False:
raise ValueError(
"Unable to avoid copy while creating an array as requested."
)
return np.array(list(self), dtype=object)
if copy is True:
return np.array(self._ndarray, dtype=dtype)
return self._ndarray
@overload
def __getitem__(self, key: ScalarIndexer) -> DTScalarOrNaT: ...
@overload
def __getitem__(
self,
key: SequenceIndexer | PositionalIndexerTuple,
) -> Self: ...
def __getitem__(self, key: PositionalIndexer2D) -> Self | DTScalarOrNaT:
"""
This getitem defers to the underlying array, which by-definition can
only handle list-likes, slices, and integer scalars
"""
# Use cast as we know we will get back a DatetimeLikeArray or DTScalar,
# but skip evaluating the Union at runtime for performance
# (see https://github.com/pandas-dev/pandas/pull/44624)
result = cast("Union[Self, DTScalarOrNaT]", super().__getitem__(key))
if lib.is_scalar(result):
return result
else:
# At this point we know the result is an array.
result = cast(Self, result)
result._freq = self._get_getitem_freq(key)
return result
def _get_getitem_freq(self, key) -> BaseOffset | None:
"""
Find the `freq` attribute to assign to the result of a __getitem__ lookup.
"""
is_period = isinstance(self.dtype, PeriodDtype)
if is_period:
freq = self.freq
elif self.ndim != 1:
freq = None
else:
key = check_array_indexer(self, key) # maybe ndarray[bool] -> slice
freq = None
if isinstance(key, slice):
if self.freq is not None and key.step is not None:
freq = key.step * self.freq
else:
freq = self.freq
elif key is Ellipsis:
# GH#21282 indexing with Ellipsis is similar to a full slice,
# should preserve `freq` attribute
freq = self.freq
elif com.is_bool_indexer(key):
new_key = lib.maybe_booleans_to_slice(key.view(np.uint8))
if isinstance(new_key, slice):
return self._get_getitem_freq(new_key)
return freq
# error: Argument 1 of "__setitem__" is incompatible with supertype
# "ExtensionArray"; supertype defines the argument type as "Union[int,
# ndarray]"
def __setitem__(
self,
key: int | Sequence[int] | Sequence[bool] | slice,
value: NaTType | Any | Sequence[Any],
) -> None:
# I'm fudging the types a bit here. "Any" above really depends
# on type(self). For PeriodArray, it's Period (or stuff coercible
# to a period in from_sequence). For DatetimeArray, it's Timestamp...
# I don't know if mypy can do that, possibly with Generics.
# https://mypy.readthedocs.io/en/latest/generics.html
no_op = check_setitem_lengths(key, value, self)
# Calling super() before the no_op short-circuit means that we raise
# on invalid 'value' even if this is a no-op, e.g. wrong-dtype empty array.
super().__setitem__(key, value)
if no_op:
return
self._maybe_clear_freq()
def _maybe_clear_freq(self) -> None:
# inplace operations like __setitem__ may invalidate the freq of
# DatetimeArray and TimedeltaArray
pass
def astype(self, dtype, copy: bool = True):
# Some notes on cases we don't have to handle here in the base class:
# 1. PeriodArray.astype handles period -> period
# 2. DatetimeArray.astype handles conversion between tz.
# 3. DatetimeArray.astype handles datetime -> period
dtype = pandas_dtype(dtype)
if dtype == object:
if self.dtype.kind == "M":
self = cast("DatetimeArray", self)
# *much* faster than self._box_values
# for e.g. test_get_loc_tuple_monotonic_above_size_cutoff
i8data = self.asi8
converted = ints_to_pydatetime(
i8data,
tz=self.tz,
box="timestamp",
reso=self._creso,
)
return converted
elif self.dtype.kind == "m":
return ints_to_pytimedelta(self._ndarray, box=True)
return self._box_values(self.asi8.ravel()).reshape(self.shape)
elif is_string_dtype(dtype):
if isinstance(dtype, ExtensionDtype):
arr_object = self._format_native_types(na_rep=dtype.na_value) # type: ignore[arg-type]
cls = dtype.construct_array_type()
return cls._from_sequence(arr_object, dtype=dtype, copy=False)
else:
return self._format_native_types()
elif isinstance(dtype, ExtensionDtype):
return super().astype(dtype, copy=copy)
elif dtype.kind in "iu":
# we deliberately ignore int32 vs. int64 here.
# See https://github.com/pandas-dev/pandas/issues/24381 for more.
values = self.asi8
if dtype != np.int64:
raise TypeError(
f"Converting from {self.dtype} to {dtype} is not supported. "
"Do obj.astype('int64').astype(dtype) instead"
)
if copy:
values = values.copy()
return values
elif (dtype.kind in "mM" and self.dtype != dtype) or dtype.kind == "f":
# disallow conversion between datetime/timedelta,
# and conversions for any datetimelike to float
msg = f"Cannot cast {type(self).__name__} to dtype {dtype}"
raise TypeError(msg)
else:
return np.asarray(self, dtype=dtype)
@overload
def view(self) -> Self: ...
@overload
def view(self, dtype: Literal["M8[ns]"]) -> DatetimeArray: ...
@overload
def view(self, dtype: Literal["m8[ns]"]) -> TimedeltaArray: ...
@overload
def view(self, dtype: Dtype | None = ...) -> ArrayLike: ...
def view(self, dtype: Dtype | None = None) -> ArrayLike:
# we need to explicitly call super() method as long as the `@overload`s
# are present in this file.
return super().view(dtype)
# ------------------------------------------------------------------
# Validation Methods
# TODO: try to de-duplicate these, ensure identical behavior
def _validate_comparison_value(self, other):
if isinstance(other, str):
try:
# GH#18435 strings get a pass from tzawareness compat
other = self._scalar_from_string(other)
except (ValueError, IncompatibleFrequency) as err:
# failed to parse as Timestamp/Timedelta/Period
raise InvalidComparison(other) from err
if isinstance(other, self._recognized_scalars) or other is NaT:
other = self._scalar_type(other)
try:
self._check_compatible_with(other)
except (TypeError, IncompatibleFrequency) as err:
# e.g. tzawareness mismatch
raise InvalidComparison(other) from err
elif not is_list_like(other):
raise InvalidComparison(other)
elif len(other) != len(self):
raise ValueError("Lengths must match")
else:
try:
other = self._validate_listlike(other, allow_object=True)
self._check_compatible_with(other)
except (TypeError, IncompatibleFrequency) as err:
if is_object_dtype(getattr(other, "dtype", None)):
# We will have to operate element-wise
pass
else:
raise InvalidComparison(other) from err
return other
def _validate_scalar(
self,
value,
*,
allow_listlike: bool = False,
unbox: bool = True,
):
"""
Validate that the input value can be cast to our scalar_type.
Parameters
----------
value : object
allow_listlike: bool, default False
When raising an exception, whether the message should say
listlike inputs are allowed.
unbox : bool, default True
Whether to unbox the result before returning. Note: unbox=False
skips the setitem compatibility check.
Returns
-------
self._scalar_type or NaT
"""
if isinstance(value, self._scalar_type):
pass
elif isinstance(value, str):
# NB: Careful about tzawareness
try:
value = self._scalar_from_string(value)
except ValueError as err:
msg = self._validation_error_message(value, allow_listlike)
raise TypeError(msg) from err
elif is_valid_na_for_dtype(value, self.dtype):
# GH#18295
value = NaT
elif isna(value):
# if we are dt64tz and value is dt64("NaT"), dont cast to NaT,
# or else we'll fail to raise in _unbox_scalar
msg = self._validation_error_message(value, allow_listlike)
raise TypeError(msg)
elif isinstance(value, self._recognized_scalars):
# error: Argument 1 to "Timestamp" has incompatible type "object"; expected
# "integer[Any] | float | str | date | datetime | datetime64"
value = self._scalar_type(value) # type: ignore[arg-type]
else:
msg = self._validation_error_message(value, allow_listlike)
raise TypeError(msg)
if not unbox:
# NB: In general NDArrayBackedExtensionArray will unbox here;
# this option exists to prevent a performance hit in
# TimedeltaIndex.get_loc
return value
return self._unbox_scalar(value)
def _validation_error_message(self, value, allow_listlike: bool = False) -> str:
"""
Construct an exception message on validation error.
Some methods allow only scalar inputs, while others allow either scalar
or listlike.
Parameters
----------
allow_listlike: bool, default False
Returns
-------
str
"""
if hasattr(value, "dtype") and getattr(value, "ndim", 0) > 0:
msg_got = f"{value.dtype} array"
else:
msg_got = f"'{type(value).__name__}'"
if allow_listlike:
msg = (
f"value should be a '{self._scalar_type.__name__}', 'NaT', "
f"or array of those. Got {msg_got} instead."
)
else:
msg = (
f"value should be a '{self._scalar_type.__name__}' or 'NaT'. "
f"Got {msg_got} instead."
)
return msg
def _validate_listlike(self, value, allow_object: bool = False):
if isinstance(value, type(self)):
if self.dtype.kind in "mM" and not allow_object and self.unit != value.unit: # type: ignore[attr-defined]
# error: "DatetimeLikeArrayMixin" has no attribute "as_unit"
value = value.as_unit(self.unit, round_ok=False) # type: ignore[attr-defined]
return value
if isinstance(value, list) and len(value) == 0:
# We treat empty list as our own dtype.
return type(self)._from_sequence([], dtype=self.dtype)
if hasattr(value, "dtype") and value.dtype == object:
# `array` below won't do inference if value is an Index or Series.
# so do so here. in the Index case, inferred_type may be cached.
if lib.infer_dtype(value) in self._infer_matches:
try:
value = type(self)._from_sequence(value)
except (ValueError, TypeError) as err:
if allow_object:
return value
msg = self._validation_error_message(value, True)
raise TypeError(msg) from err
# Do type inference if necessary up front (after unpacking
# NumpyExtensionArray)
# e.g. we passed PeriodIndex.values and got an ndarray of Periods
value = extract_array(value, extract_numpy=True)
value = pd_array(value)
value = extract_array(value, extract_numpy=True)
if is_all_strings(value):
# We got a StringArray
try:
# TODO: Could use from_sequence_of_strings if implemented
# Note: passing dtype is necessary for PeriodArray tests
value = type(self)._from_sequence(value, dtype=self.dtype)
except ValueError:
pass
if isinstance(value.dtype, CategoricalDtype):
# e.g. we have a Categorical holding self.dtype
if value.categories.dtype == self.dtype:
# TODO: do we need equal dtype or just comparable?
value = value._internal_get_values()
value = extract_array(value, extract_numpy=True)
if allow_object and is_object_dtype(value.dtype):
pass
elif not type(self)._is_recognized_dtype(value.dtype):
msg = self._validation_error_message(value, True)
raise TypeError(msg)
if self.dtype.kind in "mM" and not allow_object:
# error: "DatetimeLikeArrayMixin" has no attribute "as_unit"
value = value.as_unit(self.unit, round_ok=False) # type: ignore[attr-defined]
return value
def _validate_setitem_value(self, value):
if is_list_like(value):
value = self._validate_listlike(value)
else:
return self._validate_scalar(value, allow_listlike=True)
return self._unbox(value)
@final
def _unbox(self, other) -> np.int64 | np.datetime64 | np.timedelta64 | np.ndarray:
"""
Unbox either a scalar with _unbox_scalar or an instance of our own type.
"""
if lib.is_scalar(other):
other = self._unbox_scalar(other)
else:
# same type as self
self._check_compatible_with(other)
other = other._ndarray
return other
# ------------------------------------------------------------------
# Additional array methods
# These are not part of the EA API, but we implement them because
# pandas assumes they're there.
@ravel_compat
def map(self, mapper, na_action: Literal["ignore"] | None = None):
from pandas import Index
result = map_array(self, mapper, na_action=na_action)
result = Index(result)
if isinstance(result, ABCMultiIndex):
return result.to_numpy()
else:
return result.array
def isin(self, values: ArrayLike) -> npt.NDArray[np.bool_]:
"""
Compute boolean array of whether each value is found in the
passed set of values.
Parameters
----------
values : np.ndarray or ExtensionArray
Returns
-------
ndarray[bool]
"""
if values.dtype.kind in "fiuc":
# TODO: de-duplicate with equals, validate_comparison_value
return np.zeros(self.shape, dtype=bool)
values = ensure_wrapped_if_datetimelike(values)
if not isinstance(values, type(self)):
if values.dtype == object:
values = lib.maybe_convert_objects(
values, # type: ignore[arg-type]
convert_non_numeric=True,
dtype_if_all_nat=self.dtype,
)
if values.dtype != object:
return self.isin(values)
else:
# TODO: Deprecate this case
# https://github.com/pandas-dev/pandas/pull/58645/files#r1604055791
return isin(self.astype(object), values)
return np.zeros(self.shape, dtype=bool)
if self.dtype.kind in "mM":
self = cast("DatetimeArray | TimedeltaArray", self)
# error: "DatetimeLikeArrayMixin" has no attribute "as_unit"
values = values.as_unit(self.unit) # type: ignore[attr-defined]
try:
# error: Argument 1 to "_check_compatible_with" of "DatetimeLikeArrayMixin"
# has incompatible type "ExtensionArray | ndarray[Any, Any]"; expected
# "Period | Timestamp | Timedelta | NaTType"
self._check_compatible_with(values) # type: ignore[arg-type]
except (TypeError, ValueError):
# Includes tzawareness mismatch and IncompatibleFrequencyError
return np.zeros(self.shape, dtype=bool)
# error: Item "ExtensionArray" of "ExtensionArray | ndarray[Any, Any]"
# has no attribute "asi8"
return isin(self.asi8, values.asi8) # type: ignore[union-attr]
# ------------------------------------------------------------------
# Null Handling
def isna(self) -> npt.NDArray[np.bool_]:
return self._isnan
@property # NB: override with cache_readonly in immutable subclasses
def _isnan(self) -> npt.NDArray[np.bool_]:
"""
return if each value is nan
"""
return self.asi8 == iNaT
@property # NB: override with cache_readonly in immutable subclasses
def _hasna(self) -> bool:
"""
return if I have any nans; enables various perf speedups
"""
return bool(self._isnan.any())
def _maybe_mask_results(
self, result: np.ndarray, fill_value=iNaT, convert=None
) -> np.ndarray:
"""
Parameters
----------
result : np.ndarray
fill_value : object, default iNaT
convert : str, dtype or None
Returns
-------
result : ndarray with values replace by the fill_value
mask the result if needed, convert to the provided dtype if its not
None
This is an internal routine.
"""
if self._hasna:
if convert:
result = result.astype(convert)
if fill_value is None:
fill_value = np.nan
np.putmask(result, self._isnan, fill_value)
return result
# ------------------------------------------------------------------
# Frequency Properties/Methods
@property
def freqstr(self) -> str | None:
"""
Return the frequency object as a string if it's set, otherwise None.
See Also
--------
DatetimeIndex.inferred_freq : Returns a string representing a frequency
generated by infer_freq.
Examples
--------
For DatetimeIndex:
>>> idx = pd.DatetimeIndex(["1/1/2020 10:00:00+00:00"], freq="D")
>>> idx.freqstr
'D'
The frequency can be inferred if there are more than 2 points:
>>> idx = pd.DatetimeIndex(
... ["2018-01-01", "2018-01-03", "2018-01-05"], freq="infer"
... )
>>> idx.freqstr
'2D'
For PeriodIndex:
>>> idx = pd.PeriodIndex(["2023-1", "2023-2", "2023-3"], freq="M")
>>> idx.freqstr
'M'
"""
if self.freq is None:
return None
return self.freq.freqstr
@property # NB: override with cache_readonly in immutable subclasses
def inferred_freq(self) -> str | None:
"""
Tries to return a string representing a frequency generated by infer_freq.
Returns None if it can't autodetect the frequency.
See Also
--------
DatetimeIndex.freqstr : Return the frequency object as a string if it's set,
otherwise None.
Examples
--------
For DatetimeIndex:
>>> idx = pd.DatetimeIndex(["2018-01-01", "2018-01-03", "2018-01-05"])
>>> idx.inferred_freq
'2D'
For TimedeltaIndex:
>>> tdelta_idx = pd.to_timedelta(["0 days", "10 days", "20 days"])
>>> tdelta_idx
TimedeltaIndex(['0 days', '10 days', '20 days'],
dtype='timedelta64[ns]', freq=None)
>>> tdelta_idx.inferred_freq
'10D'
"""
if self.ndim != 1:
return None
try:
return frequencies.infer_freq(self)
except ValueError:
return None
@property # NB: override with cache_readonly in immutable subclasses
def _resolution_obj(self) -> Resolution | None:
freqstr = self.freqstr
if freqstr is None:
return None
try:
return Resolution.get_reso_from_freqstr(freqstr)
except KeyError:
return None
@property # NB: override with cache_readonly in immutable subclasses
def resolution(self) -> str:
"""
Returns day, hour, minute, second, millisecond or microsecond
"""
# error: Item "None" of "Optional[Any]" has no attribute "attrname"
return self._resolution_obj.attrname # type: ignore[union-attr]
# monotonicity/uniqueness properties are called via frequencies.infer_freq,
# see GH#23789
@property
def _is_monotonic_increasing(self) -> bool:
return algos.is_monotonic(self.asi8, timelike=True)[0]
@property
def _is_monotonic_decreasing(self) -> bool:
return algos.is_monotonic(self.asi8, timelike=True)[1]
@property
def _is_unique(self) -> bool:
return len(unique1d(self.asi8.ravel("K"))) == self.size
# ------------------------------------------------------------------
# Arithmetic Methods
def _cmp_method(self, other, op):
if self.ndim > 1 and getattr(other, "shape", None) == self.shape:
# TODO: handle 2D-like listlikes
return op(self.ravel(), other.ravel()).reshape(self.shape)
try:
other = self._validate_comparison_value(other)
except InvalidComparison:
return invalid_comparison(self, other, op)
dtype = getattr(other, "dtype", None)
if is_object_dtype(dtype):
# We have to use comp_method_OBJECT_ARRAY instead of numpy
# comparison otherwise it would raise when comparing to None
result = ops.comp_method_OBJECT_ARRAY(
op, np.asarray(self.astype(object)), other
)
return result
if other is NaT:
if op is operator.ne:
result = np.ones(self.shape, dtype=bool)
else:
result = np.zeros(self.shape, dtype=bool)
return result
if not isinstance(self.dtype, PeriodDtype):
self = cast(TimelikeOps, self)
if self._creso != other._creso:
if not isinstance(other, type(self)):
# i.e. Timedelta/Timestamp, cast to ndarray and let
# compare_mismatched_resolutions handle broadcasting
try:
# GH#52080 see if we can losslessly cast to shared unit
other = other.as_unit(self.unit, round_ok=False)