forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathinference.pyx
1722 lines (1359 loc) · 46.8 KB
/
inference.pyx
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
import sys
from decimal import Decimal
cimport util
cimport cython
from tslib import NaT
from tslibs.timezones cimport get_timezone
from datetime import datetime, timedelta
iNaT = util.get_nat()
cdef bint PY2 = sys.version_info[0] == 2
from util cimport (UINT8_MAX, UINT16_MAX, UINT32_MAX, UINT64_MAX,
INT8_MIN, INT8_MAX, INT16_MIN, INT16_MAX,
INT32_MAX, INT32_MIN, INT64_MAX, INT64_MIN)
# core.common import for fast inference checks
cpdef bint is_float(object obj):
return util.is_float_object(obj)
cpdef bint is_integer(object obj):
return util.is_integer_object(obj)
cpdef bint is_bool(object obj):
return util.is_bool_object(obj)
cpdef bint is_complex(object obj):
return util.is_complex_object(obj)
cpdef bint is_decimal(object obj):
return isinstance(obj, Decimal)
cpdef bint is_interval(object obj):
return isinstance(obj, Interval)
cpdef bint is_period(object val):
""" Return a boolean if this is a Period object """
return util.is_period_object(val)
_TYPE_MAP = {
'categorical': 'categorical',
'category': 'categorical',
'int8': 'integer',
'int16': 'integer',
'int32': 'integer',
'int64': 'integer',
'i': 'integer',
'uint8': 'integer',
'uint16': 'integer',
'uint32': 'integer',
'uint64': 'integer',
'u': 'integer',
'float32': 'floating',
'float64': 'floating',
'f': 'floating',
'complex128': 'complex',
'c': 'complex',
'string': 'string' if PY2 else 'bytes',
'S': 'string' if PY2 else 'bytes',
'unicode': 'unicode' if PY2 else 'string',
'U': 'unicode' if PY2 else 'string',
'bool': 'boolean',
'b': 'boolean',
'datetime64[ns]': 'datetime64',
'M': 'datetime64',
'timedelta64[ns]': 'timedelta64',
'm': 'timedelta64',
}
# types only exist on certain platform
try:
np.float128
_TYPE_MAP['float128'] = 'floating'
except AttributeError:
pass
try:
np.complex256
_TYPE_MAP['complex256'] = 'complex'
except AttributeError:
pass
try:
np.float16
_TYPE_MAP['float16'] = 'floating'
except AttributeError:
pass
cdef class Seen(object):
"""
Class for keeping track of the types of elements
encountered when trying to perform type conversions.
"""
cdef:
bint int_ # seen_int
bint bool_ # seen_bool
bint null_ # seen_null
bint uint_ # seen_uint (unsigned integer)
bint sint_ # seen_sint (signed integer)
bint float_ # seen_float
bint object_ # seen_object
bint complex_ # seen_complex
bint datetime_ # seen_datetime
bint coerce_numeric # coerce data to numeric
bint timedelta_ # seen_timedelta
bint datetimetz_ # seen_datetimetz
def __cinit__(self, bint coerce_numeric=0):
"""
Initialize a Seen instance.
Parameters
----------
coerce_numeric : bint, default 0
Whether or not to force conversion to a numeric data type if
initial methods to convert to numeric fail.
"""
self.int_ = 0
self.bool_ = 0
self.null_ = 0
self.uint_ = 0
self.sint_ = 0
self.float_ = 0
self.object_ = 0
self.complex_ = 0
self.datetime_ = 0
self.timedelta_ = 0
self.datetimetz_ = 0
self.coerce_numeric = coerce_numeric
cdef inline bint check_uint64_conflict(self) except -1:
"""
Check whether we can safely convert a uint64 array to a numeric dtype.
There are two cases when conversion to numeric dtype with a uint64
array is not safe (and will therefore not be performed)
1) A NaN element is encountered.
uint64 cannot be safely cast to float64 due to truncation issues
at the extreme ends of the range.
2) A negative number is encountered.
There is no numerical dtype that can hold both negative numbers
and numbers greater than INT64_MAX. Hence, at least one number
will be improperly cast if we convert to a numeric dtype.
Returns
-------
return_values : bool
Whether or not we should return the original input array to avoid
data truncation.
Raises
------
ValueError : uint64 elements were detected, and at least one of the
two conflict cases was also detected. However, we are
trying to force conversion to a numeric dtype.
"""
if self.uint_ and (self.null_ or self.sint_):
if not self.coerce_numeric:
return True
if self.null_:
msg = ("uint64 array detected, and such an "
"array cannot contain NaN.")
else: # self.sint_ = 1
msg = ("uint64 and negative values detected. "
"Cannot safely return a numeric array "
"without truncating data.")
raise ValueError(msg)
return False
cdef inline saw_null(self):
"""
Set flags indicating that a null value was encountered.
"""
self.null_ = 1
self.float_ = 1
cdef saw_int(self, object val):
"""
Set flags indicating that an integer value was encountered.
Parameters
----------
val : Python int
Value with which to set the flags.
"""
self.int_ = 1
self.sint_ = self.sint_ or (val < 0)
self.uint_ = self.uint_ or (val > oINT64_MAX)
@property
def numeric_(self):
return self.complex_ or self.float_ or self.int_
@property
def is_bool(self):
return not (self.datetime_ or self.numeric_ or self.timedelta_)
@property
def is_float_or_complex(self):
return not (self.bool_ or self.datetime_ or self.timedelta_)
cdef _try_infer_map(v):
""" if its in our map, just return the dtype """
cdef:
object attr, val
for attr in ['name', 'kind', 'base']:
val = getattr(v.dtype, attr)
if val in _TYPE_MAP:
return _TYPE_MAP[val]
return None
def infer_dtype(object value, bint skipna=False):
"""
Effeciently infer the type of a passed val, or list-like
array of values. Return a string describing the type.
Parameters
----------
value : scalar, list, ndarray, or pandas type
skipna : bool, default False
Ignore NaN values when inferring the type. The default of ``False``
will be deprecated in a later version of pandas.
.. versionadded:: 0.21.0
Returns
-------
string describing the common type of the input data.
Results can include:
- string
- unicode
- bytes
- floating
- integer
- mixed-integer
- mixed-integer-float
- decimal
- complex
- categorical
- boolean
- datetime64
- datetime
- date
- timedelta64
- timedelta
- time
- period
- mixed
Raises
------
TypeError if ndarray-like but cannot infer the dtype
Notes
-----
- 'mixed' is the catchall for anything that is not otherwise
specialized
- 'mixed-integer-float' are floats and integers
- 'mixed-integer' are integers mixed with non-integers
Examples
--------
>>> infer_dtype(['foo', 'bar'])
'string'
>>> infer_dtype(['a', np.nan, 'b'], skipna=True)
'string'
>>> infer_dtype(['a', np.nan, 'b'], skipna=False)
'mixed'
>>> infer_dtype([b'foo', b'bar'])
'bytes'
>>> infer_dtype([1, 2, 3])
'integer'
>>> infer_dtype([1, 2, 3.5])
'mixed-integer-float'
>>> infer_dtype([1.0, 2.0, 3.5])
'floating'
>>> infer_dtype(['a', 1])
'mixed-integer'
>>> infer_dtype([Decimal(1), Decimal(2.0)])
'decimal'
>>> infer_dtype([True, False])
'boolean'
>>> infer_dtype([True, False, np.nan])
'mixed'
>>> infer_dtype([pd.Timestamp('20130101')])
'datetime'
>>> infer_dtype([datetime.date(2013, 1, 1)])
'date'
>>> infer_dtype([np.datetime64('2013-01-01')])
'datetime64'
>>> infer_dtype([datetime.timedelta(0, 1, 1)])
'timedelta'
>>> infer_dtype(pd.Series(list('aabc')).astype('category'))
'categorical'
"""
cdef:
Py_ssize_t i, n
object val
ndarray values
bint seen_pdnat = False
bint seen_val = False
if isinstance(value, np.ndarray):
values = value
elif hasattr(value, 'dtype'):
# this will handle ndarray-like
# e.g. categoricals
try:
values = getattr(value, '_values', getattr(
value, 'values', value))
except:
value = _try_infer_map(value)
if value is not None:
return value
# its ndarray like but we can't handle
raise ValueError("cannot infer type for {0}".format(type(value)))
else:
if not isinstance(value, list):
value = list(value)
values = list_to_object_array(value)
values = getattr(values, 'values', values)
val = _try_infer_map(values)
if val is not None:
return val
if values.dtype != np.object_:
values = values.astype('O')
n = len(values)
if n == 0:
return 'empty'
# make contiguous
values = values.ravel()
# try to use a valid value
for i in range(n):
val = util.get_value_1d(values, i)
# do not use is_nul_datetimelike to keep
# np.datetime64('nat') and np.timedelta64('nat')
if util._checknull(val):
pass
elif val is NaT:
seen_pdnat = True
else:
seen_val = True
break
# if all values are nan/NaT
if seen_val is False and seen_pdnat is True:
return 'datetime'
# float/object nan is handled in latter logic
if util.is_datetime64_object(val):
if is_datetime64_array(values):
return 'datetime64'
elif is_timedelta_or_timedelta64_array(values):
return 'timedelta'
elif is_timedelta(val):
if is_timedelta_or_timedelta64_array(values):
return 'timedelta'
elif util.is_integer_object(val):
# a timedelta will show true here as well
if is_timedelta(val):
if is_timedelta_or_timedelta64_array(values):
return 'timedelta'
if is_integer_array(values):
return 'integer'
elif is_integer_float_array(values):
return 'mixed-integer-float'
elif is_timedelta_or_timedelta64_array(values):
return 'timedelta'
return 'mixed-integer'
elif is_datetime(val):
if is_datetime_array(values):
return 'datetime'
elif is_date(val):
if is_date_array(values, skipna=skipna):
return 'date'
elif is_time(val):
if is_time_array(values, skipna=skipna):
return 'time'
elif is_decimal(val):
return 'decimal'
elif util.is_float_object(val):
if is_float_array(values):
return 'floating'
elif is_integer_float_array(values):
return 'mixed-integer-float'
elif util.is_bool_object(val):
if is_bool_array(values, skipna=skipna):
return 'boolean'
elif PyString_Check(val):
if is_string_array(values, skipna=skipna):
return 'string'
elif PyUnicode_Check(val):
if is_unicode_array(values, skipna=skipna):
return 'unicode'
elif PyBytes_Check(val):
if is_bytes_array(values, skipna=skipna):
return 'bytes'
elif is_period(val):
if is_period_array(values):
return 'period'
elif is_interval(val):
if is_interval_array(values):
return 'interval'
for i in range(n):
val = util.get_value_1d(values, i)
if (util.is_integer_object(val) and
not util.is_timedelta64_object(val) and
not util.is_datetime64_object(val)):
return 'mixed-integer'
return 'mixed'
cpdef object infer_datetimelike_array(object arr):
"""
infer if we have a datetime or timedelta array
- date: we have *only* date and maybe strings, nulls
- datetime: we have *only* datetimes and maybe strings, nulls
- timedelta: we have *only* timedeltas and maybe strings, nulls
- nat: we do not have *any* date, datetimes or timedeltas, but do have
at least a NaT
- mixed: other objects (strings or actual objects)
Parameters
----------
arr : object array
Returns
-------
string: {datetime, timedelta, date, nat, mixed}
"""
cdef:
Py_ssize_t i, n = len(arr)
bint seen_timedelta = 0, seen_date = 0, seen_datetime = 0
bint seen_nat = 0
list objs = []
object v
for i in range(n):
v = arr[i]
if util.is_string_object(v):
objs.append(v)
if len(objs) == 3:
break
elif util._checknull(v):
# nan or None
pass
elif v is NaT:
seen_nat = 1
elif is_datetime(v) or util.is_datetime64_object(v):
# datetime, or np.datetime64
seen_datetime = 1
elif is_date(v):
seen_date = 1
elif is_timedelta(v) or util.is_timedelta64_object(v):
# timedelta, or timedelta64
seen_timedelta = 1
else:
return 'mixed'
if seen_date and not (seen_datetime or seen_timedelta):
return 'date'
elif seen_datetime and not seen_timedelta:
return 'datetime'
elif seen_timedelta and not seen_datetime:
return 'timedelta'
elif seen_nat:
return 'nat'
# short-circuit by trying to
# actually convert these strings
# this is for performance as we don't need to try
# convert *every* string array
if len(objs):
try:
tslib.array_to_datetime(objs, errors='raise')
return 'datetime'
except:
pass
# we are *not* going to infer from strings
# for timedelta as too much ambiguity
return 'mixed'
cdef inline bint is_null_datetimelike(v):
# determine if we have a null for a timedelta/datetime (or integer
# versions)
if util._checknull(v):
return True
elif v is NaT:
return True
elif util.is_timedelta64_object(v):
return v.view('int64') == iNaT
elif util.is_datetime64_object(v):
return v.view('int64') == iNaT
elif util.is_integer_object(v):
return v == iNaT
return False
cdef inline bint is_null_datetime64(v):
# determine if we have a null for a datetime (or integer versions),
# excluding np.timedelta64('nat')
if util._checknull(v):
return True
elif v is NaT:
return True
elif util.is_datetime64_object(v):
return v.view('int64') == iNaT
return False
cdef inline bint is_null_timedelta64(v):
# determine if we have a null for a timedelta (or integer versions),
# excluding np.datetime64('nat')
if util._checknull(v):
return True
elif v is NaT:
return True
elif util.is_timedelta64_object(v):
return v.view('int64') == iNaT
return False
cdef inline bint is_null_period(v):
# determine if we have a null for a Period (or integer versions),
# excluding np.datetime64('nat') and np.timedelta64('nat')
if util._checknull(v):
return True
elif v is NaT:
return True
return False
cdef inline bint is_datetime(object o):
return PyDateTime_Check(o)
cdef inline bint is_date(object o):
return PyDate_Check(o)
cdef inline bint is_time(object o):
return PyTime_Check(o)
cdef inline bint is_timedelta(object o):
return PyDelta_Check(o) or util.is_timedelta64_object(o)
cdef class Validator:
cdef:
Py_ssize_t n
np.dtype dtype
bint skipna
def __cinit__(
self,
Py_ssize_t n,
np.dtype dtype=np.dtype(np.object_),
bint skipna=False
):
self.n = n
self.dtype = dtype
self.skipna = skipna
cdef bint validate(self, object[:] values) except -1:
if not self.n:
return False
if self.is_array_typed():
return True
elif self.dtype.type_num == NPY_OBJECT:
if self.skipna:
return self._validate_skipna(values)
else:
return self._validate(values)
else:
return False
@cython.wraparound(False)
@cython.boundscheck(False)
cdef bint _validate(self, object[:] values) except -1:
cdef:
Py_ssize_t i
Py_ssize_t n = self.n
for i in range(n):
if not self.is_valid(values[i]):
return False
return self.finalize_validate()
@cython.wraparound(False)
@cython.boundscheck(False)
cdef bint _validate_skipna(self, object[:] values) except -1:
cdef:
Py_ssize_t i
Py_ssize_t n = self.n
for i in range(n):
if not self.is_valid_skipna(values[i]):
return False
return self.finalize_validate_skipna()
cdef bint is_valid(self, object value) except -1:
return self.is_value_typed(value)
cdef bint is_valid_skipna(self, object value) except -1:
return self.is_valid(value) or self.is_valid_null(value)
cdef bint is_value_typed(self, object value) except -1:
raise NotImplementedError(
'{} child class must define is_value_typed'.format(
type(self).__name__
)
)
cdef bint is_valid_null(self, object value) except -1:
return util._checknull(value)
cdef bint is_array_typed(self) except -1:
return False
cdef inline bint finalize_validate(self):
return True
cdef bint finalize_validate_skipna(self):
# TODO(phillipc): Remove the existing validate methods and replace them
# with the skipna versions upon full deprecation of skipna=False
return True
cdef class BoolValidator(Validator):
cdef inline bint is_value_typed(self, object value) except -1:
return util.is_bool_object(value)
cdef inline bint is_array_typed(self) except -1:
return issubclass(self.dtype.type, np.bool_)
cpdef bint is_bool_array(ndarray values, bint skipna=False):
cdef:
BoolValidator validator = BoolValidator(
len(values),
values.dtype,
skipna=skipna
)
return validator.validate(values)
cdef class IntegerValidator(Validator):
cdef inline bint is_value_typed(self, object value) except -1:
return util.is_integer_object(value)
cdef inline bint is_array_typed(self) except -1:
return issubclass(self.dtype.type, np.integer)
cpdef bint is_integer_array(ndarray values):
cdef:
IntegerValidator validator = IntegerValidator(
len(values),
values.dtype,
)
return validator.validate(values)
cdef class IntegerFloatValidator(Validator):
cdef inline bint is_value_typed(self, object value) except -1:
return util.is_integer_object(value) or util.is_float_object(value)
cdef inline bint is_array_typed(self) except -1:
return issubclass(self.dtype.type, np.integer)
cpdef bint is_integer_float_array(ndarray values):
cdef:
IntegerFloatValidator validator = IntegerFloatValidator(
len(values),
values.dtype,
)
return validator.validate(values)
cdef class FloatValidator(Validator):
cdef inline bint is_value_typed(self, object value) except -1:
return util.is_float_object(value)
cdef inline bint is_array_typed(self) except -1:
return issubclass(self.dtype.type, np.floating)
cpdef bint is_float_array(ndarray values):
cdef FloatValidator validator = FloatValidator(len(values), values.dtype)
return validator.validate(values)
cdef class StringValidator(Validator):
cdef inline bint is_value_typed(self, object value) except -1:
return PyString_Check(value)
cdef inline bint is_array_typed(self) except -1:
return issubclass(self.dtype.type, np.str_)
cpdef bint is_string_array(ndarray values, bint skipna=False):
cdef:
StringValidator validator = StringValidator(
len(values),
values.dtype,
skipna=skipna,
)
return validator.validate(values)
cdef class UnicodeValidator(Validator):
cdef inline bint is_value_typed(self, object value) except -1:
return PyUnicode_Check(value)
cdef inline bint is_array_typed(self) except -1:
return issubclass(self.dtype.type, np.unicode_)
cpdef bint is_unicode_array(ndarray values, bint skipna=False):
cdef:
UnicodeValidator validator = UnicodeValidator(
len(values),
values.dtype,
skipna=skipna,
)
return validator.validate(values)
cdef class BytesValidator(Validator):
cdef inline bint is_value_typed(self, object value) except -1:
return PyBytes_Check(value)
cdef inline bint is_array_typed(self) except -1:
return issubclass(self.dtype.type, np.bytes_)
cpdef bint is_bytes_array(ndarray values, bint skipna=False):
cdef:
BytesValidator validator = BytesValidator(
len(values),
values.dtype,
skipna=skipna
)
return validator.validate(values)
cdef class TemporalValidator(Validator):
cdef Py_ssize_t generic_null_count
def __cinit__(
self,
Py_ssize_t n,
np.dtype dtype=np.dtype(np.object_),
bint skipna=False
):
self.n = n
self.dtype = dtype
self.skipna = skipna
self.generic_null_count = 0
cdef inline bint is_valid(self, object value) except -1:
return self.is_value_typed(value) or self.is_valid_null(value)
cdef bint is_valid_null(self, object value) except -1:
raise NotImplementedError(
'{} child class must define is_valid_null'.format(
type(self).__name__
)
)
cdef inline bint is_valid_skipna(self, object value) except -1:
cdef:
bint is_typed_null = self.is_valid_null(value)
bint is_generic_null = util._checknull(value)
self.generic_null_count += is_typed_null and is_generic_null
return self.is_value_typed(value) or is_typed_null or is_generic_null
cdef inline bint finalize_validate_skipna(self):
return self.generic_null_count != self.n
cdef class DatetimeValidator(TemporalValidator):
cdef bint is_value_typed(self, object value) except -1:
return is_datetime(value)
cdef inline bint is_valid_null(self, object value) except -1:
return is_null_datetime64(value)
cpdef bint is_datetime_array(ndarray[object] values):
cdef:
DatetimeValidator validator = DatetimeValidator(
len(values),
skipna=True,
)
return validator.validate(values)
cdef class Datetime64Validator(DatetimeValidator):
cdef inline bint is_value_typed(self, object value) except -1:
return util.is_datetime64_object(value)
cpdef bint is_datetime64_array(ndarray values):
cdef:
Datetime64Validator validator = Datetime64Validator(
len(values),
skipna=True,
)
return validator.validate(values)
cpdef bint is_datetime_with_singletz_array(ndarray[object] values):
"""
Check values have the same tzinfo attribute.
Doesn't check values are datetime-like types.
"""
cdef Py_ssize_t i, j, n = len(values)
cdef object base_val, base_tz, val, tz
if n == 0:
return False
for i in range(n):
base_val = values[i]
if base_val is not NaT:
base_tz = get_timezone(getattr(base_val, 'tzinfo', None))
for j in range(i, n):
val = values[j]
if val is not NaT:
tz = getattr(val, 'tzinfo', None)
if base_tz != tz and base_tz != get_timezone(tz):
return False
break
return True
cdef class TimedeltaValidator(TemporalValidator):
cdef bint is_value_typed(self, object value) except -1:
return PyDelta_Check(value)
cdef inline bint is_valid_null(self, object value) except -1:
return is_null_timedelta64(value)
cpdef bint is_timedelta_array(ndarray values):
cdef:
TimedeltaValidator validator = TimedeltaValidator(
len(values),
skipna=True,
)
return validator.validate(values)
cdef class Timedelta64Validator(TimedeltaValidator):
cdef inline bint is_value_typed(self, object value) except -1:
return util.is_timedelta64_object(value)
cpdef bint is_timedelta64_array(ndarray values):
cdef:
Timedelta64Validator validator = Timedelta64Validator(
len(values),
skipna=True,
)
return validator.validate(values)
cdef class AnyTimedeltaValidator(TimedeltaValidator):
cdef inline bint is_value_typed(self, object value) except -1:
return is_timedelta(value)
cpdef bint is_timedelta_or_timedelta64_array(ndarray values):
""" infer with timedeltas and/or nat/none """
cdef:
AnyTimedeltaValidator validator = AnyTimedeltaValidator(
len(values),
skipna=True,
)
return validator.validate(values)
cdef class DateValidator(Validator):
cdef inline bint is_value_typed(self, object value) except -1:
return is_date(value)
cpdef bint is_date_array(ndarray[object] values, bint skipna=False):
cdef DateValidator validator = DateValidator(len(values), skipna=skipna)
return validator.validate(values)
cdef class TimeValidator(Validator):
cdef inline bint is_value_typed(self, object value) except -1:
return is_time(value)
cpdef bint is_time_array(ndarray[object] values, bint skipna=False):
cdef TimeValidator validator = TimeValidator(len(values), skipna=skipna)
return validator.validate(values)
cdef class PeriodValidator(TemporalValidator):
cdef inline bint is_value_typed(self, object value) except -1:
return is_period(value)
cdef inline bint is_valid_null(self, object value) except -1:
return is_null_period(value)
cpdef bint is_period_array(ndarray[object] values):
cdef PeriodValidator validator = PeriodValidator(len(values), skipna=True)
return validator.validate(values)