forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.pyx
1307 lines (1050 loc) · 41.4 KB
/
index.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
cimport cython
import numpy as np
cimport numpy as cnp
from numpy cimport (
int64_t,
intp_t,
ndarray,
uint8_t,
uint64_t,
)
cnp.import_array()
from pandas._libs cimport util
from pandas._libs.hashtable cimport HashTable
from pandas._libs.tslibs.nattype cimport c_NaT as NaT
from pandas._libs.tslibs.np_datetime cimport (
NPY_DATETIMEUNIT,
get_unit_from_dtype,
import_pandas_datetime,
)
import_pandas_datetime()
from pandas._libs.tslibs.period cimport is_period_object
from pandas._libs.tslibs.timedeltas cimport _Timedelta
from pandas._libs.tslibs.timestamps cimport _Timestamp
from pandas._libs import (
algos,
hashtable as _hash,
)
from pandas._libs.lib cimport eq_NA_compat
from pandas._libs.missing cimport (
C_NA,
checknull,
is_matching_na,
)
# Defines shift of MultiIndex codes to avoid negative codes (missing values)
multiindex_nulls_shift = 2
cdef bint is_definitely_invalid_key(object val):
try:
hash(val)
except TypeError:
return True
return False
cdef ndarray _get_bool_indexer(ndarray values, object val, ndarray mask = None):
"""
Return a ndarray[bool] of locations where val matches self.values.
If val is not NA, this is equivalent to `self.values == val`
"""
# Caller is responsible for ensuring _check_type has already been called
cdef:
ndarray[uint8_t, ndim=1, cast=True] indexer
Py_ssize_t i
object item
if values.descr.type_num == cnp.NPY_OBJECT:
assert mask is None # no mask for object dtype
# i.e. values.dtype == object
if not checknull(val):
indexer = eq_NA_compat(values, val)
else:
# We need to check for _matching_ NA values
indexer = np.empty(len(values), dtype=np.uint8)
for i in range(len(values)):
item = values[i]
indexer[i] = is_matching_na(item, val)
else:
if mask is not None:
if val is C_NA:
indexer = mask == 1
else:
indexer = (values == val) & ~mask
else:
if util.is_nan(val):
indexer = np.isnan(values)
else:
indexer = values == val
return indexer.view(bool)
# Don't populate hash tables in monotonic indexes larger than this
_SIZE_CUTOFF = 1_000_000
cdef _unpack_bool_indexer(ndarray[uint8_t, ndim=1, cast=True] indexer, object val):
"""
Possibly unpack a boolean mask to a single indexer.
"""
# Returns ndarray[bool] or int
cdef:
ndarray[intp_t, ndim=1] found
int count
found = np.where(indexer)[0]
count = len(found)
if count > 1:
return indexer
if count == 1:
return int(found[0])
raise KeyError(val)
@cython.freelist(32)
cdef class IndexEngine:
cdef readonly:
ndarray values
ndarray mask
HashTable mapping
bint over_size_threshold
cdef:
bint unique, monotonic_inc, monotonic_dec
bint need_monotonic_check, need_unique_check
object _np_type
def __init__(self, ndarray values):
self.values = values
self.mask = None
self.over_size_threshold = len(values) >= _SIZE_CUTOFF
self.clear_mapping()
self._np_type = values.dtype.type
def __contains__(self, val: object) -> bool:
hash(val)
try:
self.get_loc(val)
except KeyError:
return False
return True
cpdef get_loc(self, object val):
# -> Py_ssize_t | slice | ndarray[bool]
cdef:
Py_ssize_t loc
if is_definitely_invalid_key(val):
raise TypeError(f"'{val}' is an invalid key")
val = self._check_type(val)
if self.over_size_threshold and self.is_monotonic_increasing:
if not self.is_unique:
return self._get_loc_duplicates(val)
values = self.values
loc = self._searchsorted_left(val)
if loc >= len(values):
raise KeyError(val)
if values[loc] != val:
raise KeyError(val)
return loc
self._ensure_mapping_populated()
if not self.unique:
return self._get_loc_duplicates(val)
if self.mask is not None and val is C_NA:
return self.mapping.get_na()
try:
return self.mapping.get_item(val)
except OverflowError as err:
# GH#41775 OverflowError e.g. if we are uint64 and val is -1
# or if we are int64 and value is np.iinfo(np.int64).max+1
# (the uint64 with -1 case should actually be excluded by _check_type)
raise KeyError(val) from err
cdef Py_ssize_t _searchsorted_left(self, val) except? -1:
"""
See ObjectEngine._searchsorted_left.__doc__.
"""
# Caller is responsible for ensuring _check_type has already been called
loc = self.values.searchsorted(self._np_type(val), side="left")
return loc
cdef _get_loc_duplicates(self, object val):
# -> Py_ssize_t | slice | ndarray[bool]
cdef:
Py_ssize_t diff, left, right
if self.is_monotonic_increasing:
values = self.values
try:
left = values.searchsorted(val, side="left")
right = values.searchsorted(val, side="right")
except TypeError:
# e.g. GH#29189 get_loc(None) with a Float64Index
# 2021-09-29 Now only reached for object-dtype
raise KeyError(val)
diff = right - left
if diff == 0:
raise KeyError(val)
elif diff == 1:
return left
else:
return slice(left, right)
return self._maybe_get_bool_indexer(val)
cdef _maybe_get_bool_indexer(self, object val):
# Returns ndarray[bool] or int
cdef:
ndarray[uint8_t, ndim=1, cast=True] indexer
indexer = _get_bool_indexer(self.values, val, self.mask)
return _unpack_bool_indexer(indexer, val)
def sizeof(self, deep: bool = False) -> int:
""" return the sizeof our mapping """
if not self.is_mapping_populated:
return 0
return self.mapping.sizeof(deep=deep)
def __sizeof__(self) -> int:
return self.sizeof()
cpdef _update_from_sliced(self, IndexEngine other, reverse: bool):
self.unique = other.unique
self.need_unique_check = other.need_unique_check
if not other.need_monotonic_check and (
other.is_monotonic_increasing or other.is_monotonic_decreasing):
self.need_monotonic_check = other.need_monotonic_check
# reverse=True means the index has been reversed
self.monotonic_inc = other.monotonic_dec if reverse else other.monotonic_inc
self.monotonic_dec = other.monotonic_inc if reverse else other.monotonic_dec
@property
def is_unique(self) -> bool:
if self.need_unique_check:
self._do_unique_check()
return self.unique == 1
cdef _do_unique_check(self):
self._ensure_mapping_populated()
@property
def is_monotonic_increasing(self) -> bool:
if self.need_monotonic_check:
self._do_monotonic_check()
return self.monotonic_inc == 1
@property
def is_monotonic_decreasing(self) -> bool:
if self.need_monotonic_check:
self._do_monotonic_check()
return self.monotonic_dec == 1
cdef _do_monotonic_check(self):
cdef:
bint is_strict_monotonic
if self.mask is not None and np.any(self.mask):
self.monotonic_inc = 0
self.monotonic_dec = 0
else:
try:
values = self.values
self.monotonic_inc, self.monotonic_dec, is_strict_monotonic = \
self._call_monotonic(values)
except TypeError:
self.monotonic_inc = 0
self.monotonic_dec = 0
is_strict_monotonic = 0
self.need_monotonic_check = 0
# we can only be sure of uniqueness if is_strict_monotonic=1
if is_strict_monotonic:
self.unique = 1
self.need_unique_check = 0
cdef _call_monotonic(self, values):
return algos.is_monotonic(values, timelike=False)
cdef _make_hash_table(self, Py_ssize_t n):
raise NotImplementedError # pragma: no cover
cdef _check_type(self, object val):
hash(val)
return val
@property
def is_mapping_populated(self) -> bool:
return self.mapping is not None
cdef _ensure_mapping_populated(self):
# this populates the mapping
# if its not already populated
# also satisfies the need_unique_check
if not self.is_mapping_populated:
values = self.values
self.mapping = self._make_hash_table(len(values))
self.mapping.map_locations(values, self.mask)
if len(self.mapping) == len(values):
self.unique = 1
self.need_unique_check = 0
def clear_mapping(self):
self.mapping = None
self.need_monotonic_check = 1
self.need_unique_check = 1
self.unique = 0
self.monotonic_inc = 0
self.monotonic_dec = 0
def get_indexer(self, ndarray values) -> np.ndarray:
self._ensure_mapping_populated()
return self.mapping.lookup(values)
def get_indexer_non_unique(self, ndarray targets):
"""
Return an indexer suitable for taking from a non unique index
return the labels in the same order as the target
and a missing indexer into the targets (which correspond
to the -1 indices in the results
Returns
-------
indexer : np.ndarray[np.intp]
missing : np.ndarray[np.intp]
"""
cdef:
ndarray values
ndarray[intp_t] result, missing
set stargets, remaining_stargets, found_nas
dict d = {}
object val
Py_ssize_t count = 0, count_missing = 0
Py_ssize_t i, j, n, n_t, n_alloc, start, end
bint check_na_values = False
values = self.values
stargets = set(targets)
na_in_stargets = any(checknull(t) for t in stargets)
n = len(values)
n_t = len(targets)
if n > 10_000:
n_alloc = 10_000
else:
n_alloc = n
result = np.empty(n_alloc, dtype=np.intp)
missing = np.empty(n_t, dtype=np.intp)
# map each starget to its position in the index
if (
stargets and
len(stargets) < 5 and
not na_in_stargets and
self.is_monotonic_increasing
):
# if there are few enough stargets and the index is monotonically
# increasing, then use binary search for each starget
remaining_stargets = set()
for starget in stargets:
try:
start = values.searchsorted(starget, side="left")
end = values.searchsorted(starget, side="right")
except TypeError: # e.g. if we tried to search for string in int array
remaining_stargets.add(starget)
else:
if start != end:
d[starget] = list(range(start, end))
stargets = remaining_stargets
if stargets:
# otherwise, map by iterating through all items in the index
# short-circuit na check
if na_in_stargets:
check_na_values = True
# keep track of nas in values
found_nas = set()
for i in range(n):
val = values[i]
# GH#43870
# handle lookup for nas
# (ie. np.nan, float("NaN"), Decimal("NaN"), dt64nat, td64nat)
if check_na_values and checknull(val):
match = [na for na in found_nas if is_matching_na(val, na)]
# matching na not found
if not len(match):
found_nas.add(val)
# add na to stargets to utilize `in` for stargets/d lookup
match_stargets = [
x for x in stargets if is_matching_na(val, x)
]
if len(match_stargets):
# add our 'standardized' na
stargets.add(val)
# matching na found
else:
assert len(match) == 1
val = match[0]
if val in stargets:
if val not in d:
d[val] = []
d[val].append(i)
for i in range(n_t):
val = targets[i]
# ensure there are nas in values before looking for a matching na
if check_na_values and checknull(val):
match = [na for na in found_nas if is_matching_na(val, na)]
if len(match):
assert len(match) == 1
val = match[0]
# found
if val in d:
key = val
for j in d[key]:
# realloc if needed
if count >= n_alloc:
n_alloc += 10_000
result = np.resize(result, n_alloc)
result[count] = j
count += 1
# value not found
else:
if count >= n_alloc:
n_alloc += 10_000
result = np.resize(result, n_alloc)
result[count] = -1
count += 1
missing[count_missing] = i
count_missing += 1
return result[0:count], missing[0:count_missing]
cdef Py_ssize_t _bin_search(ndarray values, object val) except -1:
# GH#1757 ndarray.searchsorted is not safe to use with array of tuples
# (treats a tuple `val` as a sequence of keys instead of a single key),
# so we implement something similar.
# This is equivalent to the stdlib's bisect.bisect_left
cdef:
Py_ssize_t mid = 0, lo = 0, hi = len(values) - 1
object pval
if hi == 0 or (hi > 0 and val > values[hi]):
return len(values)
while lo < hi:
mid = (lo + hi) // 2
pval = values[mid]
if val < pval:
hi = mid
elif val > pval:
lo = mid + 1
else:
while mid > 0 and val == values[mid - 1]:
mid -= 1
return mid
if val <= values[mid]:
return mid
else:
return mid + 1
cdef class ObjectEngine(IndexEngine):
"""
Index Engine for use with object-dtype Index, namely the base class Index.
"""
cdef _make_hash_table(self, Py_ssize_t n):
return _hash.PyObjectHashTable(n)
cdef Py_ssize_t _searchsorted_left(self, val) except? -1:
# using values.searchsorted here would treat a tuple `val` as a sequence
# instead of a single key, so we use a different implementation
try:
loc = _bin_search(self.values, val)
except TypeError as err:
raise KeyError(val) from err
return loc
cdef class DatetimeEngine(Int64Engine):
cdef:
NPY_DATETIMEUNIT _creso
def __init__(self, ndarray values):
super().__init__(values.view("i8"))
self._creso = get_unit_from_dtype(values.dtype)
cdef int64_t _unbox_scalar(self, scalar) except? -1:
# NB: caller is responsible for ensuring tzawareness compat
# before we get here
if scalar is NaT:
return NaT._value
elif isinstance(scalar, _Timestamp):
if scalar._creso == self._creso:
return scalar._value
else:
# Note: caller is responsible for catching potential ValueError
# from _as_creso
return (
(<_Timestamp>scalar)._as_creso(self._creso, round_ok=False)._value
)
raise TypeError(scalar)
def __contains__(self, val: object) -> bool:
# We assume before we get here:
# - val is hashable
try:
self._unbox_scalar(val)
except ValueError:
return False
try:
self.get_loc(val)
return True
except KeyError:
return False
cdef _call_monotonic(self, values):
return algos.is_monotonic(values, timelike=True)
cpdef get_loc(self, object val):
# NB: the caller is responsible for ensuring that we are called
# with either a Timestamp or NaT (Timedelta or NaT for TimedeltaEngine)
cdef:
Py_ssize_t loc
if is_definitely_invalid_key(val):
raise TypeError(f"'{val}' is an invalid key")
try:
conv = self._unbox_scalar(val)
except (TypeError, ValueError) as err:
raise KeyError(val) from err
# Welcome to the spaghetti factory
if self.over_size_threshold and self.is_monotonic_increasing:
if not self.is_unique:
return self._get_loc_duplicates(conv)
values = self.values
loc = values.searchsorted(conv, side="left")
if loc == len(values) or values[loc] != conv:
raise KeyError(val)
return loc
self._ensure_mapping_populated()
if not self.unique:
return self._get_loc_duplicates(conv)
try:
return self.mapping.get_item(conv)
except KeyError:
raise KeyError(val)
cdef class TimedeltaEngine(DatetimeEngine):
cdef int64_t _unbox_scalar(self, scalar) except? -1:
if scalar is NaT:
return NaT._value
elif isinstance(scalar, _Timedelta):
if scalar._creso == self._creso:
return scalar._value
else:
# Note: caller is responsible for catching potential ValueError
# from _as_creso
return (
(<_Timedelta>scalar)._as_creso(self._creso, round_ok=False)._value
)
raise TypeError(scalar)
cdef class PeriodEngine(Int64Engine):
cdef int64_t _unbox_scalar(self, scalar) except? -1:
if scalar is NaT:
return scalar._value
if is_period_object(scalar):
# NB: we assume that we have the correct freq here.
return scalar.ordinal
raise TypeError(scalar)
cpdef get_loc(self, object val):
# NB: the caller is responsible for ensuring that we are called
# with either a Period or NaT
cdef:
int64_t conv
try:
conv = self._unbox_scalar(val)
except TypeError:
raise KeyError(val)
return Int64Engine.get_loc(self, conv)
cdef _call_monotonic(self, values):
return algos.is_monotonic(values, timelike=True)
cdef class BaseMultiIndexCodesEngine:
"""
Base class for MultiIndexUIntEngine and MultiIndexPyIntEngine, which
represent each label in a MultiIndex as an integer, by juxtaposing the bits
encoding each level, with appropriate offsets.
For instance: if 3 levels have respectively 3, 6 and 1 possible values,
then their labels can be represented using respectively 2, 3 and 1 bits,
as follows:
_ _ _ _____ _ __ __ __
|0|0|0| ... |0| 0|a1|a0| -> offset 0 (first level)
— — — ————— — —— —— ——
|0|0|0| ... |0|b2|b1|b0| -> offset 2 (bits required for first level)
— — — ————— — —— —— ——
|0|0|0| ... |0| 0| 0|c0| -> offset 5 (bits required for first two levels)
‾ ‾ ‾ ‾‾‾‾‾ ‾ ‾‾ ‾‾ ‾‾
and the resulting unsigned integer representation will be:
_ _ _ _____ _ __ __ __ __ __ __
|0|0|0| ... |0|c0|b2|b1|b0|a1|a0|
‾ ‾ ‾ ‾‾‾‾‾ ‾ ‾‾ ‾‾ ‾‾ ‾‾ ‾‾ ‾‾
Offsets are calculated at initialization, labels are transformed by method
_codes_to_ints.
Keys are located by first locating each component against the respective
level, then locating (the integer representation of) codes.
"""
def __init__(self, object levels, object labels,
ndarray[uint64_t, ndim=1] offsets):
"""
Parameters
----------
levels : list-like of numpy arrays
Levels of the MultiIndex.
labels : list-like of numpy arrays of integer dtype
Labels of the MultiIndex.
offsets : numpy array of uint64 dtype
Pre-calculated offsets, one for each level of the index.
"""
self.levels = levels
self.offsets = offsets
# Transform labels in a single array, and add 2 so that we are working
# with positive integers (-1 for NaN becomes 1). This enables us to
# differentiate between values that are missing in other and matching
# NaNs. We will set values that are not found to 0 later:
labels_arr = np.array(labels, dtype="int64").T + multiindex_nulls_shift
codes = labels_arr.astype("uint64", copy=False)
self.level_has_nans = [-1 in lab for lab in labels]
# Map each codes combination in the index to an integer unambiguously
# (no collisions possible), based on the "offsets", which describe the
# number of bits to switch labels for each level:
lab_ints = self._codes_to_ints(codes)
# Initialize underlying index (e.g. libindex.UInt64Engine) with
# integers representing labels: we will use its get_loc and get_indexer
self._base.__init__(self, lab_ints)
def _codes_to_ints(self, ndarray[uint64_t] codes) -> np.ndarray:
raise NotImplementedError("Implemented by subclass") # pragma: no cover
def _extract_level_codes(self, target) -> np.ndarray:
"""
Map the requested list of (tuple) keys to their integer representations
for searching in the underlying integer index.
Parameters
----------
target : MultiIndex
Returns
------
int_keys : 1-dimensional array of dtype uint64 or object
Integers representing one combination each
"""
zt = [target._get_level_values(i) for i in range(target.nlevels)]
level_codes = []
for i, (lev, codes) in enumerate(zip(self.levels, zt)):
result = lev.get_indexer_for(codes) + 1
result[result > 0] += 1
if self.level_has_nans[i] and codes.hasnans:
result[codes.isna()] += 1
level_codes.append(result)
return self._codes_to_ints(np.array(level_codes, dtype="uint64").T)
def get_indexer(self, target: np.ndarray) -> np.ndarray:
"""
Returns an array giving the positions of each value of `target` in
`self.values`, where -1 represents a value in `target` which does not
appear in `self.values`
Parameters
----------
target : np.ndarray
Returns
-------
np.ndarray[intp_t, ndim=1] of the indexer of `target` into
`self.values`
"""
return self._base.get_indexer(self, target)
def get_indexer_with_fill(self, ndarray target, ndarray values,
str method, object limit) -> np.ndarray:
"""
Returns an array giving the positions of each value of `target` in
`values`, where -1 represents a value in `target` which does not
appear in `values`
If `method` is "backfill" then the position for a value in `target`
which does not appear in `values` is that of the next greater value
in `values` (if one exists), and -1 if there is no such value.
Similarly, if the method is "pad" then the position for a value in
`target` which does not appear in `values` is that of the next smaller
value in `values` (if one exists), and -1 if there is no such value.
Parameters
----------
target: ndarray[object] of tuples
need not be sorted, but all must have the same length, which must be
the same as the length of all tuples in `values`
values : ndarray[object] of tuples
must be sorted and all have the same length. Should be the set of
the MultiIndex's values.
method: string
"backfill" or "pad"
limit: int or None
if provided, limit the number of fills to this value
Returns
-------
np.ndarray[intp_t, ndim=1] of the indexer of `target` into `values`,
filled with the `method` (and optionally `limit`) specified
"""
assert method in ("backfill", "pad")
cdef:
int64_t i, j, next_code
int64_t num_values, num_target_values
ndarray[int64_t, ndim=1] target_order
ndarray[object, ndim=1] target_values
ndarray[int64_t, ndim=1] new_codes, new_target_codes
ndarray[intp_t, ndim=1] sorted_indexer
target_order = np.argsort(target).astype("int64")
target_values = target[target_order]
num_values, num_target_values = len(values), len(target_values)
new_codes, new_target_codes = (
np.empty((num_values,)).astype("int64"),
np.empty((num_target_values,)).astype("int64"),
)
# `values` and `target_values` are both sorted, so we walk through them
# and memoize the (ordered) set of indices in the (implicit) merged-and
# sorted list of the two which belong to each of them
# the effect of this is to create a factorization for the (sorted)
# merger of the index values, where `new_codes` and `new_target_codes`
# are the subset of the factors which appear in `values` and `target`,
# respectively
i, j, next_code = 0, 0, 0
while i < num_values and j < num_target_values:
val, target_val = values[i], target_values[j]
if val <= target_val:
new_codes[i] = next_code
i += 1
if target_val <= val:
new_target_codes[j] = next_code
j += 1
next_code += 1
# at this point, at least one should have reached the end
# the remaining values of the other should be added to the end
assert i == num_values or j == num_target_values
while i < num_values:
new_codes[i] = next_code
i += 1
next_code += 1
while j < num_target_values:
new_target_codes[j] = next_code
j += 1
next_code += 1
# get the indexer, and undo the sorting of `target.values`
algo = algos.backfill if method == "backfill" else algos.pad
sorted_indexer = algo(new_codes, new_target_codes, limit=limit)
return sorted_indexer[np.argsort(target_order)]
def get_loc(self, object key):
if is_definitely_invalid_key(key):
raise TypeError(f"'{key}' is an invalid key")
if not isinstance(key, tuple):
raise KeyError(key)
try:
indices = [1 if checknull(v) else lev.get_loc(v) + multiindex_nulls_shift
for lev, v in zip(self.levels, key)]
except KeyError:
raise KeyError(key)
# Transform indices into single integer:
lab_int = self._codes_to_ints(np.array(indices, dtype="uint64"))
return self._base.get_loc(self, lab_int)
def get_indexer_non_unique(self, target: np.ndarray) -> np.ndarray:
indexer = self._base.get_indexer_non_unique(self, target)
return indexer
def __contains__(self, val: object) -> bool:
# We assume before we get here:
# - val is hashable
# Default __contains__ looks in the underlying mapping, which in this
# case only contains integer representations.
try:
self.get_loc(val)
return True
except (KeyError, TypeError, ValueError):
return False
# Generated from template.
include "index_class_helper.pxi"
cdef class BoolEngine(UInt8Engine):
cdef _check_type(self, object val):
if not util.is_bool_object(val):
raise KeyError(val)
return <uint8_t>val
cdef class MaskedBoolEngine(MaskedUInt8Engine):
cdef _check_type(self, object val):
if val is C_NA:
return val
if not util.is_bool_object(val):
raise KeyError(val)
return <uint8_t>val
@cython.internal
@cython.freelist(32)
cdef class SharedEngine:
cdef readonly:
object values # ExtensionArray
bint over_size_threshold
cdef:
bint unique, monotonic_inc, monotonic_dec
bint need_monotonic_check, need_unique_check
def __contains__(self, val: object) -> bool:
# We assume before we get here:
# - val is hashable
try:
self.get_loc(val)
return True
except KeyError:
return False
def clear_mapping(self):
# for compat with IndexEngine
pass
cpdef _update_from_sliced(self, ExtensionEngine other, reverse: bool):
self.unique = other.unique
self.need_unique_check = other.need_unique_check
if not other.need_monotonic_check and (
other.is_monotonic_increasing or other.is_monotonic_decreasing):
self.need_monotonic_check = other.need_monotonic_check
# reverse=True means the index has been reversed
self.monotonic_inc = other.monotonic_dec if reverse else other.monotonic_inc
self.monotonic_dec = other.monotonic_inc if reverse else other.monotonic_dec
@property
def is_unique(self) -> bool:
if self.need_unique_check:
arr = self.values.unique()
self.unique = len(arr) == len(self.values)
self.need_unique_check = False
return self.unique
cdef _do_monotonic_check(self):
raise NotImplementedError
@property
def is_monotonic_increasing(self) -> bool:
if self.need_monotonic_check:
self._do_monotonic_check()
return self.monotonic_inc == 1
@property
def is_monotonic_decreasing(self) -> bool:
if self.need_monotonic_check:
self._do_monotonic_check()
return self.monotonic_dec == 1
cdef _call_monotonic(self, values):
return algos.is_monotonic(values, timelike=False)
def sizeof(self, deep: bool = False) -> int:
""" return the sizeof our mapping """
return 0
def __sizeof__(self) -> int:
return self.sizeof()
cdef _check_type(self, object obj):
raise NotImplementedError
cpdef get_loc(self, object val):
# -> Py_ssize_t | slice | ndarray[bool]
cdef:
Py_ssize_t loc
if is_definitely_invalid_key(val):
raise TypeError(f"'{val}' is an invalid key")
self._check_type(val)
if self.over_size_threshold and self.is_monotonic_increasing:
if not self.is_unique:
return self._get_loc_duplicates(val)
values = self.values
loc = self._searchsorted_left(val)
if loc >= len(values):
raise KeyError(val)
if values[loc] != val:
raise KeyError(val)
return loc
if not self.unique:
return self._get_loc_duplicates(val)
return self._get_loc_duplicates(val)
cdef _get_loc_duplicates(self, object val):
# -> Py_ssize_t | slice | ndarray[bool]
cdef:
Py_ssize_t diff
if self.is_monotonic_increasing:
values = self.values
try:
left = values.searchsorted(val, side="left")
right = values.searchsorted(val, side="right")
except TypeError:
# e.g. GH#29189 get_loc(None) with a Float64Index