forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.pyx
1959 lines (1521 loc) · 48.7 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
# cython: profile=False
cimport numpy as np
cimport cython
import numpy as np
import sys
from numpy cimport *
np.import_array()
cdef extern from "numpy/arrayobject.h":
cdef enum NPY_TYPES:
NPY_intp "NPY_INTP"
from cpython cimport (PyDict_New, PyDict_GetItem, PyDict_SetItem,
PyDict_Contains, PyDict_Keys,
Py_INCREF, PyTuple_SET_ITEM,
PyList_Check, PyFloat_Check,
PyString_Check,
PyBytes_Check,
PyTuple_SetItem,
PyTuple_New,
PyObject_SetAttrString,
PyObject_RichCompareBool,
PyBytes_GET_SIZE,
PyUnicode_GET_SIZE)
try:
from cpython cimport PyString_GET_SIZE
except ImportError:
from cpython cimport PyUnicode_GET_SIZE as PyString_GET_SIZE
cdef extern from "Python.h":
Py_ssize_t PY_SSIZE_T_MAX
ctypedef struct PySliceObject:
pass
cdef int PySlice_GetIndicesEx(
PySliceObject* s, Py_ssize_t length,
Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step,
Py_ssize_t *slicelength) except -1
cimport cpython
isnan = np.isnan
cdef double NaN = <double> np.NaN
cdef double nan = NaN
cdef double NAN = nan
from datetime import datetime as pydatetime
# this is our tseries.pxd
from datetime cimport *
from tslib cimport (convert_to_tsobject, convert_to_timedelta64,
_check_all_nulls)
import tslib
from tslib import NaT, Timestamp, Timedelta
cdef int64_t NPY_NAT = util.get_nat()
ctypedef unsigned char UChar
cimport util
from util cimport (is_array, _checknull, _checknan, INT64_MAX,
INT64_MIN, UINT8_MAX)
cdef extern from "math.h":
double sqrt(double x)
double fabs(double)
# import datetime C API
PyDateTime_IMPORT
# initialize numpy
import_array()
import_ufunc()
def values_from_object(object o):
""" return my values or the object if we are say an ndarray """
cdef f
f = getattr(o, 'get_values', None)
if f is not None:
o = f()
return o
cpdef map_indices_list(list index):
"""
Produce a dict mapping the values of the input array to their respective
locations.
Example:
array(['hi', 'there']) --> {'hi' : 0 , 'there' : 1}
Better to do this with Cython because of the enormous speed boost.
"""
cdef Py_ssize_t i, length
cdef dict result = {}
length = len(index)
for i from 0 <= i < length:
result[index[i]] = i
return result
from libc.stdlib cimport malloc, free
def ismember_nans(float64_t[:] arr, set values, bint hasnans):
cdef:
Py_ssize_t i, n
ndarray[uint8_t] result
float64_t val
n = len(arr)
result = np.empty(n, dtype=np.uint8)
for i in range(n):
val = arr[i]
result[i] = val in values or hasnans and isnan(val)
return result.view(np.bool_)
def ismember(ndarray arr, set values):
"""
Checks whether
Parameters
----------
arr : ndarray
values : set
Returns
-------
ismember : ndarray (boolean dtype)
"""
cdef:
Py_ssize_t i, n
ndarray[uint8_t] result
object val
n = len(arr)
result = np.empty(n, dtype=np.uint8)
for i in range(n):
val = util.get_value_at(arr, i)
result[i] = val in values
return result.view(np.bool_)
def ismember_int64(ndarray[int64_t] arr, set values):
"""
Checks whether
Parameters
----------
arr : ndarray of int64
values : set
Returns
-------
ismember : ndarray (boolean dtype)
"""
cdef:
Py_ssize_t i, n
ndarray[uint8_t] result
int64_t v
n = len(arr)
result = np.empty(n, dtype=np.uint8)
for i in range(n):
result[i] = arr[i] in values
return result.view(np.bool_)
@cython.wraparound(False)
@cython.boundscheck(False)
def memory_usage_of_objects(ndarray[object, ndim=1] arr):
""" return the memory usage of an object array in bytes,
does not include the actual bytes of the pointers """
cdef Py_ssize_t i, n
cdef int64_t s = 0
n = len(arr)
for i from 0 <= i < n:
s += arr[i].__sizeof__()
return s
#----------------------------------------------------------------------
# datetime / io related
cdef int _EPOCH_ORD = 719163
from datetime import date as pydate
cdef inline int64_t gmtime(object date):
cdef int y, m, d, h, mn, s, days
y = PyDateTime_GET_YEAR(date)
m = PyDateTime_GET_MONTH(date)
d = PyDateTime_GET_DAY(date)
h = PyDateTime_DATE_GET_HOUR(date)
mn = PyDateTime_DATE_GET_MINUTE(date)
s = PyDateTime_DATE_GET_SECOND(date)
days = pydate(y, m, 1).toordinal() - _EPOCH_ORD + d - 1
return ((<int64_t> (((days * 24 + h) * 60 + mn))) * 60 + s) * 1000
cpdef object to_datetime(int64_t timestamp):
return pydatetime.utcfromtimestamp(timestamp / 1000.0)
cpdef object to_timestamp(object dt):
return gmtime(dt)
def array_to_timestamp(ndarray[object, ndim=1] arr):
cdef int i, n
cdef ndarray[int64_t, ndim=1] result
n = len(arr)
result = np.empty(n, dtype=np.int64)
for i from 0 <= i < n:
result[i] = gmtime(arr[i])
return result
def time64_to_datetime(ndarray[int64_t, ndim=1] arr):
cdef int i, n
cdef ndarray[object, ndim=1] result
n = len(arr)
result = np.empty(n, dtype=object)
for i from 0 <= i < n:
result[i] = to_datetime(arr[i])
return result
#----------------------------------------------------------------------
# isnull / notnull related
cdef double INF = <double> np.inf
cdef double NEGINF = -INF
cpdef checknull(object val):
if util.is_float_object(val) or util.is_complex_object(val):
return val != val # and val != INF and val != NEGINF
elif util.is_datetime64_object(val):
return get_datetime64_value(val) == NPY_NAT
elif val is NaT:
return True
elif util.is_timedelta64_object(val):
return get_timedelta64_value(val) == NPY_NAT
elif is_array(val):
return False
else:
return _checknull(val)
cpdef checknull_old(object val):
if util.is_float_object(val) or util.is_complex_object(val):
return val != val or val == INF or val == NEGINF
elif util.is_datetime64_object(val):
return get_datetime64_value(val) == NPY_NAT
elif val is NaT:
return True
elif util.is_timedelta64_object(val):
return get_timedelta64_value(val) == NPY_NAT
elif is_array(val):
return False
else:
return util._checknull(val)
cpdef isposinf_scalar(object val):
if util.is_float_object(val) and val == INF:
return True
else:
return False
cpdef isneginf_scalar(object val):
if util.is_float_object(val) and val == NEGINF:
return True
else:
return False
def isscalar(object val):
"""
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
"""
return (np.PyArray_IsAnyScalar(val)
# As of numpy-1.9, PyArray_IsAnyScalar misses bytearrays on Py3.
or PyBytes_Check(val)
# 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))
def item_from_zerodim(object val):
"""
If the value is a zerodim array, return the item it contains.
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])
"""
return util.unbox_if_zerodim(val)
@cython.wraparound(False)
@cython.boundscheck(False)
def isnullobj(ndarray arr):
cdef Py_ssize_t i, n
cdef object val
cdef ndarray[uint8_t] result
assert arr.ndim == 1, "'arr' must be 1-D."
n = len(arr)
result = np.empty(n, dtype=np.uint8)
for i from 0 <= i < n:
val = arr[i]
result[i] = _check_all_nulls(val)
return result.view(np.bool_)
@cython.wraparound(False)
@cython.boundscheck(False)
def isnullobj_old(ndarray arr):
cdef Py_ssize_t i, n
cdef object val
cdef ndarray[uint8_t] result
assert arr.ndim == 1, "'arr' must be 1-D."
n = len(arr)
result = np.zeros(n, dtype=np.uint8)
for i from 0 <= i < n:
val = arr[i]
result[i] = val is NaT or util._checknull_old(val)
return result.view(np.bool_)
@cython.wraparound(False)
@cython.boundscheck(False)
def isnullobj2d(ndarray arr):
cdef Py_ssize_t i, j, n, m
cdef object val
cdef ndarray[uint8_t, ndim=2] result
assert arr.ndim == 2, "'arr' must be 2-D."
n, m = (<object> arr).shape
result = np.zeros((n, m), dtype=np.uint8)
for i from 0 <= i < n:
for j from 0 <= j < m:
val = arr[i, j]
if checknull(val):
result[i, j] = 1
return result.view(np.bool_)
@cython.wraparound(False)
@cython.boundscheck(False)
def isnullobj2d_old(ndarray arr):
cdef Py_ssize_t i, j, n, m
cdef object val
cdef ndarray[uint8_t, ndim=2] result
assert arr.ndim == 2, "'arr' must be 2-D."
n, m = (<object> arr).shape
result = np.zeros((n, m), dtype=np.uint8)
for i from 0 <= i < n:
for j from 0 <= j < m:
val = arr[i, j]
if checknull_old(val):
result[i, j] = 1
return result.view(np.bool_)
@cython.wraparound(False)
@cython.boundscheck(False)
cpdef ndarray[object] list_to_object_array(list obj):
"""
Convert list to object ndarray. Seriously can\'t believe
I had to write this function.
"""
cdef:
Py_ssize_t i, n = len(obj)
ndarray[object] arr = np.empty(n, dtype=object)
for i in range(n):
arr[i] = obj[i]
return arr
@cython.wraparound(False)
@cython.boundscheck(False)
def fast_unique(ndarray[object] values):
cdef:
Py_ssize_t i, n = len(values)
list uniques = []
dict table = {}
object val, stub = 0
for i from 0 <= i < n:
val = values[i]
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 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 from 0 <= i < k:
buf = arrays[i]
n = len(buf)
for j from 0 <= j < 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):
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 from 0 <= i < k:
buf = lists[i]
n = len(buf)
for j from 0 <= j < 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_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 from 0 <= j < 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):
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):
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 convert_timestamps(ndarray values):
cdef:
object val, f, result
dict cache = {}
Py_ssize_t i, n = len(values)
ndarray[object] out
# for HDFStore, a bit temporary but...
from datetime import datetime
f = datetime.fromtimestamp
out = np.empty(n, dtype='O')
for i in range(n):
val = util.get_value_1d(values, i)
if val in cache:
out[i] = cache[val]
else:
cache[val] = out[i] = f(val)
return out
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 scalar_compare(ndarray[object] values, object val, object op):
import operator
cdef:
Py_ssize_t i, n = len(values)
ndarray[uint8_t, cast=True] result
bint isnull_val
int flag
object x
if op is operator.lt:
flag = cpython.Py_LT
elif op is operator.le:
flag = cpython.Py_LE
elif op is operator.gt:
flag = cpython.Py_GT
elif op is operator.ge:
flag = cpython.Py_GE
elif op is operator.eq:
flag = cpython.Py_EQ
elif op is operator.ne:
flag = cpython.Py_NE
else:
raise ValueError('Unrecognized operator')
result = np.empty(n, dtype=bool).view(np.uint8)
isnull_val = checknull(val)
if flag == cpython.Py_NE:
for i in range(n):
x = values[i]
if checknull(x):
result[i] = True
elif isnull_val:
result[i] = True
else:
try:
result[i] = cpython.PyObject_RichCompareBool(x, val, flag)
except (TypeError):
result[i] = True
elif flag == cpython.Py_EQ:
for i in range(n):
x = values[i]
if checknull(x):
result[i] = False
elif isnull_val:
result[i] = False
else:
try:
result[i] = cpython.PyObject_RichCompareBool(x, val, flag)
except (TypeError):
result[i] = False
else:
for i in range(n):
x = values[i]
if checknull(x):
result[i] = False
elif isnull_val:
result[i] = False
else:
result[i] = cpython.PyObject_RichCompareBool(x, val, flag)
return result.view(bool)
@cython.wraparound(False)
@cython.boundscheck(False)
cpdef bint array_equivalent_object(object[:] left, object[:] right):
""" 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, cpython.Py_EQ) or
_checknull(x) and _checknull(y)):
return False
return True
@cython.wraparound(False)
@cython.boundscheck(False)
def vec_compare(ndarray[object] left, ndarray[object] right, object op):
import operator
cdef:
Py_ssize_t i, n = len(left)
ndarray[uint8_t, cast=True] result
int flag
if n != len(right):
raise ValueError('Arrays were different lengths: %d vs %d'
% (n, len(right)))
if op is operator.lt:
flag = cpython.Py_LT
elif op is operator.le:
flag = cpython.Py_LE
elif op is operator.gt:
flag = cpython.Py_GT
elif op is operator.ge:
flag = cpython.Py_GE
elif op is operator.eq:
flag = cpython.Py_EQ
elif op is operator.ne:
flag = cpython.Py_NE
else:
raise ValueError('Unrecognized operator')
result = np.empty(n, dtype=bool).view(np.uint8)
if flag == cpython.Py_NE:
for i in range(n):
x = left[i]
y = right[i]
if checknull(x) or checknull(y):
result[i] = True
else:
result[i] = cpython.PyObject_RichCompareBool(x, y, flag)
else:
for i in range(n):
x = left[i]
y = right[i]
if checknull(x) or checknull(y):
result[i] = False
else:
result[i] = cpython.PyObject_RichCompareBool(x, y, flag)
return result.view(bool)
@cython.wraparound(False)
@cython.boundscheck(False)
def scalar_binop(ndarray[object] values, object val, object op):
cdef:
Py_ssize_t i, n = len(values)
ndarray[object] result
object x
result = np.empty(n, dtype=object)
if util._checknull(val):
result.fill(val)
return result
for i in range(n):
x = values[i]
if util._checknull(x):
result[i] = x
else:
result[i] = op(x, val)
return maybe_convert_bool(result)
@cython.wraparound(False)
@cython.boundscheck(False)
def vec_binop(ndarray[object] left, ndarray[object] right, object op):
cdef:
Py_ssize_t i, n = len(left)
ndarray[object] result
if n != len(right):
raise ValueError('Arrays were different lengths: %d vs %d'
% (n, len(right)))
result = np.empty(n, dtype=object)
for i in range(n):
x = left[i]
y = right[i]
try:
result[i] = op(x, y)
except TypeError:
if util._checknull(x):
result[i] = x
elif util._checknull(y):
result[i] = y
else:
raise
return maybe_convert_bool(result)
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:
# we can use the unsafe version because we know `result` is mutable
# since it was created from `np.empty`
util.set_value_at_unsafe(result, i, v)
return result
cpdef ndarray[object] astype_unicode(ndarray arr):
cdef:
Py_ssize_t i, n = arr.size
ndarray[object] result = np.empty(n, dtype=object)
for i in range(n):
# we can use the unsafe version because we know `result` is mutable
# since it was created from `np.empty`
util.set_value_at_unsafe(result, i, unicode(arr[i]))
return result
cpdef ndarray[object] astype_str(ndarray arr):
cdef:
Py_ssize_t i, n = arr.size