forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.pyx
2309 lines (1830 loc) · 63.2 KB
/
lib.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
# -*- coding: utf-8 -*-
from decimal import Decimal
import sys
import cython
from cython import Py_ssize_t
from cpython cimport (Py_INCREF, PyTuple_SET_ITEM,
PyTuple_New,
Py_EQ,
PyObject_RichCompareBool)
from cpython.datetime cimport (PyDateTime_Check, PyDate_Check,
PyTime_Check, PyDelta_Check,
PyDateTime_IMPORT)
PyDateTime_IMPORT
import numpy as np
cimport numpy as cnp
from numpy cimport (ndarray, PyArray_NDIM, PyArray_GETITEM,
PyArray_ITER_DATA, PyArray_ITER_NEXT, PyArray_IterNew,
flatiter, NPY_OBJECT,
int64_t,
float32_t, float64_t,
uint8_t, uint64_t,
complex128_t)
cnp.import_array()
cdef extern from "numpy/arrayobject.h":
# cython's numpy.dtype specification is incorrect, which leads to
# errors in issubclass(self.dtype.type, np.bool_), so we directly
# include the correct version
# https://github.com/cython/cython/issues/2022
ctypedef class numpy.dtype [object PyArray_Descr]:
# Use PyDataType_* macros when possible, however there are no macros
# for accessing some of the fields, so some are defined. Please
# ask on cython-dev if you need more.
cdef int type_num
cdef int itemsize "elsize"
cdef char byteorder
cdef object fields
cdef tuple names
cdef extern from "src/parse_helper.h":
int floatify(object, double *result, int *maybe_int) except -1
cimport util
from util cimport (is_nan,
UINT8_MAX, UINT64_MAX, INT64_MAX, INT64_MIN)
from tslib import array_to_datetime
from tslibs.nattype import NaT
from tslibs.conversion cimport convert_to_tsobject
from tslibs.timedeltas cimport convert_to_timedelta64
from tslibs.timezones cimport get_timezone, tz_compare
from missing cimport (checknull, isnaobj,
is_null_datetime64, is_null_timedelta64, is_null_period)
# constants that will be compared to potentially arbitrarily large
# python int
cdef object oINT64_MAX = <int64_t>INT64_MAX
cdef object oINT64_MIN = <int64_t>INT64_MIN
cdef object oUINT64_MAX = <uint64_t>UINT64_MAX
cdef int64_t NPY_NAT = util.get_nat()
iNaT = util.get_nat()
cdef bint PY2 = sys.version_info[0] == 2
cdef double nan = <double>np.NaN
def values_from_object(object obj):
""" return my values or the object if we are say an ndarray """
cdef func # TODO: Does declaring this without a type accomplish anything?
func = getattr(obj, 'get_values', None)
if func is not None:
obj = func()
return obj
@cython.wraparound(False)
@cython.boundscheck(False)
def memory_usage_of_objects(arr: object[:]) -> int64_t:
""" return the memory usage of an object array in bytes,
does not include the actual bytes of the pointers """
i: Py_ssize_t
n: Py_ssize_t
size: int64_t
size = 0
n = len(arr)
for i in range(n):
size += arr[i].__sizeof__()
return size
# ----------------------------------------------------------------------
def is_scalar(val: object) -> bint:
"""
Return True if given value is scalar.
This includes:
- numpy array scalar (e.g. np.int64)
- Python builtin numerics
- Python builtin byte arrays and strings
- None
- instances of datetime.datetime
- instances of datetime.timedelta
- Period
- instances of decimal.Decimal
- Interval
- DateOffset
"""
return (cnp.PyArray_IsAnyScalar(val)
# As of numpy-1.9, PyArray_IsAnyScalar misses bytearrays on Py3.
or isinstance(val, bytes)
# We differ from numpy (as of 1.10), which claims that None is
# not scalar in np.isscalar().
or val is None
or PyDate_Check(val)
or PyDelta_Check(val)
or PyTime_Check(val)
or util.is_period_object(val)
or is_decimal(val)
or is_interval(val)
or util.is_offset_object(val))
def item_from_zerodim(val: object) -> object:
"""
If the value is a zerodim array, return the item it contains.
Parameters
----------
val : object
Returns
-------
result : object
Examples
--------
>>> item_from_zerodim(1)
1
>>> item_from_zerodim('foobar')
'foobar'
>>> item_from_zerodim(np.array(1))
1
>>> item_from_zerodim(np.array([1]))
array([1])
"""
if cnp.PyArray_IsZeroDim(val):
return cnp.PyArray_ToScalar(cnp.PyArray_DATA(val), val)
return val
@cython.wraparound(False)
@cython.boundscheck(False)
def fast_unique_multiple(list arrays):
cdef:
ndarray[object] buf
Py_ssize_t k = len(arrays)
Py_ssize_t i, j, n
list uniques = []
dict table = {}
object val, stub = 0
for i in range(k):
buf = arrays[i]
n = len(buf)
for j in range(n):
val = buf[j]
if val not in table:
table[val] = stub
uniques.append(val)
try:
uniques.sort()
except Exception:
pass
return uniques
@cython.wraparound(False)
@cython.boundscheck(False)
def fast_unique_multiple_list(list lists, bint sort=True):
cdef:
list buf
Py_ssize_t k = len(lists)
Py_ssize_t i, j, n
list uniques = []
dict table = {}
object val, stub = 0
for i in range(k):
buf = lists[i]
n = len(buf)
for j in range(n):
val = buf[j]
if val not in table:
table[val] = stub
uniques.append(val)
if sort:
try:
uniques.sort()
except Exception:
pass
return uniques
@cython.wraparound(False)
@cython.boundscheck(False)
def fast_unique_multiple_list_gen(object gen, bint sort=True):
"""
Generate a list of unique values from a generator of lists.
Parameters
----------
gen : generator object
A generator of lists from which the unique list is created
sort : boolean
Whether or not to sort the resulting unique list
Returns
-------
unique_list : list of unique values
"""
cdef:
list buf
Py_ssize_t j, n
list uniques = []
dict table = {}
object val, stub = 0
for buf in gen:
n = len(buf)
for j in range(n):
val = buf[j]
if val not in table:
table[val] = stub
uniques.append(val)
if sort:
try:
uniques.sort()
except Exception:
pass
return uniques
@cython.wraparound(False)
@cython.boundscheck(False)
def dicts_to_array(list dicts, list columns):
cdef:
Py_ssize_t i, j, k, n
ndarray[object, ndim=2] result
dict row
object col, onan = np.nan
k = len(columns)
n = len(dicts)
result = np.empty((n, k), dtype='O')
for i in range(n):
row = dicts[i]
for j in range(k):
col = columns[j]
if col in row:
result[i, j] = row[col]
else:
result[i, j] = onan
return result
def fast_zip(list ndarrays):
"""
For zipping multiple ndarrays into an ndarray of tuples
"""
cdef:
Py_ssize_t i, j, k, n
ndarray[object] result
flatiter it
object val, tup
k = len(ndarrays)
n = len(ndarrays[0])
result = np.empty(n, dtype=object)
# initialize tuples on first pass
arr = ndarrays[0]
it = <flatiter> PyArray_IterNew(arr)
for i in range(n):
val = PyArray_GETITEM(arr, PyArray_ITER_DATA(it))
tup = PyTuple_New(k)
PyTuple_SET_ITEM(tup, 0, val)
Py_INCREF(val)
result[i] = tup
PyArray_ITER_NEXT(it)
for j in range(1, k):
arr = ndarrays[j]
it = <flatiter> PyArray_IterNew(arr)
if len(arr) != n:
raise ValueError('all arrays must be same length')
for i in range(n):
val = PyArray_GETITEM(arr, PyArray_ITER_DATA(it))
PyTuple_SET_ITEM(result[i], j, val)
Py_INCREF(val)
PyArray_ITER_NEXT(it)
return result
def get_reverse_indexer(ndarray[int64_t] indexer, Py_ssize_t length):
"""
Reverse indexing operation.
Given `indexer`, make `indexer_inv` of it, such that::
indexer_inv[indexer[x]] = x
.. note:: If indexer is not unique, only first occurrence is accounted.
"""
cdef:
Py_ssize_t i, n = len(indexer)
ndarray[int64_t] rev_indexer
int64_t idx
rev_indexer = np.empty(length, dtype=np.int64)
rev_indexer.fill(-1)
for i in range(n):
idx = indexer[i]
if idx != -1:
rev_indexer[idx] = i
return rev_indexer
def has_infs_f4(ndarray[float32_t] arr) -> bint:
cdef:
Py_ssize_t i, n = len(arr)
float32_t inf, neginf, val
inf = np.inf
neginf = -inf
for i in range(n):
val = arr[i]
if val == inf or val == neginf:
return True
return False
def has_infs_f8(ndarray[float64_t] arr) -> bint:
cdef:
Py_ssize_t i, n = len(arr)
float64_t inf, neginf, val
inf = np.inf
neginf = -inf
for i in range(n):
val = arr[i]
if val == inf or val == neginf:
return True
return False
def maybe_indices_to_slice(ndarray[int64_t] indices, int max_len):
cdef:
Py_ssize_t i, n = len(indices)
int k, vstart, vlast, v
if n == 0:
return slice(0, 0)
vstart = indices[0]
if vstart < 0 or max_len <= vstart:
return indices
if n == 1:
return slice(vstart, vstart + 1)
vlast = indices[n - 1]
if vlast < 0 or max_len <= vlast:
return indices
k = indices[1] - indices[0]
if k == 0:
return indices
else:
for i in range(2, n):
v = indices[i]
if v - indices[i - 1] != k:
return indices
if k > 0:
return slice(vstart, vlast + 1, k)
else:
if vlast == 0:
return slice(vstart, None, k)
else:
return slice(vstart, vlast - 1, k)
def maybe_booleans_to_slice(ndarray[uint8_t] mask):
cdef:
Py_ssize_t i, n = len(mask)
Py_ssize_t start, end
bint started = 0, finished = 0
for i in range(n):
if mask[i]:
if finished:
return mask.view(np.bool_)
if not started:
started = 1
start = i
else:
if finished:
continue
if started:
end = i
finished = 1
if not started:
return slice(0, 0)
if not finished:
return slice(start, None)
else:
return slice(start, end)
@cython.wraparound(False)
@cython.boundscheck(False)
def array_equivalent_object(left: object[:], right: object[:]) -> bint:
""" perform an element by element comparion on 1-d object arrays
taking into account nan positions """
cdef:
Py_ssize_t i, n = left.shape[0]
object x, y
for i in range(n):
x = left[i]
y = right[i]
# we are either not equal or both nan
# I think None == None will be true here
if not (PyObject_RichCompareBool(x, y, Py_EQ) or
(x is None or is_nan(x)) and (y is None or is_nan(y))):
return False
return True
@cython.wraparound(False)
@cython.boundscheck(False)
def astype_intsafe(ndarray[object] arr, new_dtype):
cdef:
Py_ssize_t i, n = len(arr)
object v
bint is_datelike
ndarray result
# on 32-bit, 1.6.2 numpy M8[ns] is a subdtype of integer, which is weird
is_datelike = new_dtype in ['M8[ns]', 'm8[ns]']
result = np.empty(n, dtype=new_dtype)
for i in range(n):
v = arr[i]
if is_datelike and checknull(v):
result[i] = NPY_NAT
else:
result[i] = v
return result
@cython.wraparound(False)
@cython.boundscheck(False)
def astype_unicode(arr: ndarray,
skipna: bool=False) -> ndarray[object]:
"""
Convert all elements in an array to unicode.
Parameters
----------
arr : ndarray
The array whose elements we are casting.
skipna : bool, default False
Whether or not to coerce nulls to their stringified form
(e.g. NaN becomes 'nan').
Returns
-------
casted_arr : ndarray
A new array with the input array's elements casted.
"""
cdef:
object arr_i
Py_ssize_t i, n = arr.size
ndarray[object] result = np.empty(n, dtype=object)
for i in range(n):
arr_i = arr[i]
if not (skipna and checknull(arr_i)):
arr_i = unicode(arr_i)
result[i] = arr_i
return result
@cython.wraparound(False)
@cython.boundscheck(False)
def astype_str(arr: ndarray,
skipna: bool=False) -> ndarray[object]:
"""
Convert all elements in an array to string.
Parameters
----------
arr : ndarray
The array whose elements we are casting.
skipna : bool, default False
Whether or not to coerce nulls to their stringified form
(e.g. NaN becomes 'nan').
Returns
-------
casted_arr : ndarray
A new array with the input array's elements casted.
"""
cdef:
object arr_i
Py_ssize_t i, n = arr.size
ndarray[object] result = np.empty(n, dtype=object)
for i in range(n):
arr_i = arr[i]
if not (skipna and checknull(arr_i)):
arr_i = str(arr_i)
result[i] = arr_i
return result
@cython.wraparound(False)
@cython.boundscheck(False)
def clean_index_list(list obj):
"""
Utility used in pandas.core.index.ensure_index
"""
cdef:
Py_ssize_t i, n = len(obj)
object v
bint all_arrays = 1
for i in range(n):
v = obj[i]
if not (isinstance(v, list) or
util.is_array(v) or hasattr(v, '_data')):
all_arrays = 0
break
if all_arrays:
return obj, all_arrays
# don't force numpy coerce with nan's
inferred = infer_dtype(obj)
if inferred in ['string', 'bytes', 'unicode', 'mixed', 'mixed-integer']:
return np.asarray(obj, dtype=object), 0
elif inferred in ['integer']:
# TODO: we infer an integer but it *could* be a unint64
try:
return np.asarray(obj, dtype='int64'), 0
except OverflowError:
return np.asarray(obj, dtype='object'), 0
return np.asarray(obj), 0
# ------------------------------------------------------------------------------
# Groupby-related functions
# TODO: could do even better if we know something about the data. eg, index has
# 1-min data, binner has 5-min data, then bins are just strides in index. This
# is a general, O(max(len(values), len(binner))) method.
@cython.boundscheck(False)
@cython.wraparound(False)
def generate_bins_dt64(ndarray[int64_t] values, ndarray[int64_t] binner,
object closed='left', bint hasnans=0):
"""
Int64 (datetime64) version of generic python version in groupby.py
"""
cdef:
Py_ssize_t lenidx, lenbin, i, j, bc, vc
ndarray[int64_t] bins
int64_t l_bin, r_bin, nat_count
bint right_closed = closed == 'right'
nat_count = 0
if hasnans:
mask = values == iNaT
nat_count = np.sum(mask)
values = values[~mask]
lenidx = len(values)
lenbin = len(binner)
if lenidx <= 0 or lenbin <= 0:
raise ValueError("Invalid length for values or for binner")
# check binner fits data
if values[0] < binner[0]:
raise ValueError("Values falls before first bin")
if values[lenidx - 1] > binner[lenbin - 1]:
raise ValueError("Values falls after last bin")
bins = np.empty(lenbin - 1, dtype=np.int64)
j = 0 # index into values
bc = 0 # bin count
# linear scan
if right_closed:
for i in range(0, lenbin - 1):
r_bin = binner[i + 1]
# count values in current bin, advance to next bin
while j < lenidx and values[j] <= r_bin:
j += 1
bins[bc] = j
bc += 1
else:
for i in range(0, lenbin - 1):
r_bin = binner[i + 1]
# count values in current bin, advance to next bin
while j < lenidx and values[j] < r_bin:
j += 1
bins[bc] = j
bc += 1
if nat_count > 0:
# shift bins by the number of NaT
bins = bins + nat_count
bins = np.insert(bins, 0, nat_count)
return bins
@cython.boundscheck(False)
@cython.wraparound(False)
def row_bool_subset(ndarray[float64_t, ndim=2] values,
ndarray[uint8_t, cast=True] mask):
cdef:
Py_ssize_t i, j, n, k, pos = 0
ndarray[float64_t, ndim=2] out
n, k = (<object> values).shape
assert (n == len(mask))
out = np.empty((mask.sum(), k), dtype=np.float64)
for i in range(n):
if mask[i]:
for j in range(k):
out[pos, j] = values[i, j]
pos += 1
return out
@cython.boundscheck(False)
@cython.wraparound(False)
def row_bool_subset_object(ndarray[object, ndim=2] values,
ndarray[uint8_t, cast=True] mask):
cdef:
Py_ssize_t i, j, n, k, pos = 0
ndarray[object, ndim=2] out
n, k = (<object> values).shape
assert (n == len(mask))
out = np.empty((mask.sum(), k), dtype=object)
for i in range(n):
if mask[i]:
for j in range(k):
out[pos, j] = values[i, j]
pos += 1
return out
@cython.boundscheck(False)
@cython.wraparound(False)
def get_level_sorter(ndarray[int64_t, ndim=1] label,
ndarray[int64_t, ndim=1] starts):
"""
argsort for a single level of a multi-index, keeping the order of higher
levels unchanged. `starts` points to starts of same-key indices w.r.t
to leading levels; equivalent to:
np.hstack([label[starts[i]:starts[i+1]].argsort(kind='mergesort')
+ starts[i] for i in range(len(starts) - 1)])
"""
cdef:
int64_t l, r
Py_ssize_t i
ndarray[int64_t, ndim=1] out = np.empty(len(label), dtype=np.int64)
for i in range(len(starts) - 1):
l, r = starts[i], starts[i + 1]
out[l:r] = l + label[l:r].argsort(kind='mergesort')
return out
@cython.boundscheck(False)
@cython.wraparound(False)
def count_level_2d(ndarray[uint8_t, ndim=2, cast=True] mask,
ndarray[int64_t, ndim=1] labels,
Py_ssize_t max_bin,
int axis):
cdef:
Py_ssize_t i, j, k, n
ndarray[int64_t, ndim=2] counts
assert (axis == 0 or axis == 1)
n, k = (<object> mask).shape
if axis == 0:
counts = np.zeros((max_bin, k), dtype='i8')
with nogil:
for i in range(n):
for j in range(k):
counts[labels[i], j] += mask[i, j]
else: # axis == 1
counts = np.zeros((n, max_bin), dtype='i8')
with nogil:
for i in range(n):
for j in range(k):
counts[i, labels[j]] += mask[i, j]
return counts
def generate_slices(ndarray[int64_t] labels, Py_ssize_t ngroups):
cdef:
Py_ssize_t i, group_size, n, start
int64_t lab
object slobj
ndarray[int64_t] starts, ends
n = len(labels)
starts = np.zeros(ngroups, dtype=np.int64)
ends = np.zeros(ngroups, dtype=np.int64)
start = 0
group_size = 0
for i in range(n):
lab = labels[i]
if lab < 0:
start += 1
else:
group_size += 1
if i == n - 1 or lab != labels[i + 1]:
starts[lab] = start
ends[lab] = start + group_size
start += group_size
group_size = 0
return starts, ends
def indices_fast(object index, ndarray[int64_t] labels, list keys,
list sorted_labels):
cdef:
Py_ssize_t i, j, k, lab, cur, start, n = len(labels)
dict result = {}
object tup
k = len(keys)
if n == 0:
return result
start = 0
cur = labels[0]
for i in range(1, n):
lab = labels[i]
if lab != cur:
if lab != -1:
tup = PyTuple_New(k)
for j in range(k):
val = util.get_value_at(keys[j],
sorted_labels[j][i - 1])
PyTuple_SET_ITEM(tup, j, val)
Py_INCREF(val)
result[tup] = index[start:i]
start = i
cur = lab
tup = PyTuple_New(k)
for j in range(k):
val = util.get_value_at(keys[j],
sorted_labels[j][n - 1])
PyTuple_SET_ITEM(tup, j, val)
Py_INCREF(val)
result[tup] = index[start:]
return result
# core.common import for fast inference checks
def is_float(obj: object) -> bint:
return util.is_float_object(obj)
def is_integer(obj: object) -> bint:
return util.is_integer_object(obj)
def is_bool(obj: object) -> bint:
return util.is_bool_object(obj)
def is_complex(obj: object) -> bint:
return util.is_complex_object(obj)
cpdef bint is_decimal(object obj):
return isinstance(obj, Decimal)
cpdef bint is_interval(object obj):
return getattr(obj, '_typ', '_typ') == 'interval'
def is_period(val: object) -> bint:
""" 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.
"""
return (self.uint_ and (self.null_ or self.sint_)
and not self.coerce_numeric)
cdef inline saw_null(self):
"""
Set flags indicating that a null value was encountered.
"""