Skip to content

Commit 2b22c96

Browse files
committed
BUG: implement new engine for codes-based MultiIndex indexing
closes pandas-dev#18519 closes pandas-dev#18818 closes pandas-dev#18520 closes pandas-dev#18485 closes pandas-dev#15994 closes pandas-dev#19086
1 parent 250574e commit 2b22c96

File tree

3 files changed

+232
-12
lines changed

3 files changed

+232
-12
lines changed

doc/source/whatsnew/v0.23.0.txt

+5-1
Original file line numberDiff line numberDiff line change
@@ -476,7 +476,11 @@ MultiIndex
476476
- Bug in :func:`MultiIndex.get_level_values` which would return an invalid index on level of ints with missing values (:issue:`17924`)
477477
- Bug in :func:`MultiIndex.remove_unused_levels` which would fill nan values (:issue:`18417`)
478478
- Bug in :func:`MultiIndex.from_tuples`` which would fail to take zipped tuples in python3 (:issue:`18434`)
479-
-
479+
- Bug in :func:`MultiIndex.get_loc`` which would fail to automatically cast values between float and int (:issue:`18818`, :issue:`15994`)
480+
- Bug in :func:`MultiIndex.get_loc`` which would cast boolean to integer labels (:issue:`19086`)
481+
- Bug in :func:`MultiIndex.get_loc`` which would fail to locate keys containing ``NaN`` (:issue:`18485`)
482+
- Bug in :func:`MultiIndex.get_loc`` in large :class:`MultiIndex`, would fail when levels had different dtypes (:issue:`18520`)
483+
480484

481485
I/O
482486
^^^

pandas/_libs/index.pyx

+136
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ from hashtable cimport HashTable
2020
from pandas._libs import algos, hashtable as _hash
2121
from pandas._libs.tslibs import period as periodlib
2222
from pandas._libs.tslib import Timestamp, Timedelta
23+
from pandas._libs.missing import checknull
2324
from datetime import datetime, timedelta, date
2425

2526
from cpython cimport PyTuple_Check, PyList_Check
@@ -583,6 +584,141 @@ cpdef convert_scalar(ndarray arr, object value):
583584
return value
584585

585586

587+
cdef class BaseMultiIndexCodesEngine:
588+
"""
589+
Base class for MultiIndexUIntEngine and MultiIndexPyIntEngine, which
590+
represent each label in a MultiIndex as an integer, by juxtaposing the bits
591+
encoding each level, with appropriate offsets.
592+
593+
For instance: if 3 levels have respectively 3, 6 and 1 possible values,
594+
then their labels can be represented using respectively 2, 3 and 1 bits,
595+
as follows:
596+
_ _ _ _____ _ __ __ __
597+
|0|0|0| ... |0| 0|a1|a0| -> offset 0 (first level)
598+
— — — ————— — —— —— ——
599+
|0|0|0| ... |0|b2|b1|b0| -> offset 2 (bits required for first level)
600+
— — — ————— — —— —— ——
601+
|0|0|0| ... |0| 0| 0|c0| -> offset 5 (bits required for first two levels)
602+
‾ ‾ ‾ ‾‾‾‾‾ ‾ ‾‾ ‾‾ ‾‾
603+
and the resulting unsigned integer representation will be:
604+
_ _ _ ____ _ __ __ __ __ __ __
605+
|0|0|0| ...|0|c0|b2|b1|b0|a1|a0|
606+
‾ ‾ ‾ ‾‾‾‾ ‾ ‾‾ ‾‾ ‾‾ ‾‾ ‾‾ ‾‾
607+
608+
Offsets are calculated at initialization, labels are transformed by method
609+
_codes_to_ints.
610+
611+
Keys are located by first locating each component against the respective
612+
level, then locating (the integer representation of) codes.
613+
"""
614+
def __init__(self, object levels, object labels,
615+
ndarray[uint64_t, ndim=1] offsets):
616+
"""
617+
Parameters
618+
----------
619+
levels : list-like of numpy arrays
620+
Levels of the MultiIndex
621+
labels : list-like of numpy arrays of integer dtype
622+
Labels of the MultiIndex
623+
offsets : numpy array of uint64 dtype
624+
Pre-calculated offsets, one for each level of the index
625+
"""
626+
627+
self.levels = levels
628+
self.offsets = offsets
629+
630+
# Transform labels in a single array, and add 1 so that we are working
631+
# with positive integers (-1 for NaN becomes 0):
632+
codes = (np.array(labels, dtype='int64').T + 1).astype('uint64',
633+
copy=False)
634+
635+
# Map each codes combination in the index to an integer unambiguously
636+
# (no collisions possible), based on the "offsets", which describe the
637+
# number of bits to switch labels for each level:
638+
lab_ints = self._codes_to_ints(codes)
639+
640+
# Initialize underlying index (e.g. libindex.UInt64Engine) with
641+
# integers representing labels: we will use its get_loc and get_indexer
642+
self._base.__init__(self, lambda: lab_ints, len(lab_ints))
643+
644+
def _extract_level_codes(self, object target, object method=None):
645+
"""
646+
Map the requested list of (tuple) keys to their integer representations
647+
for searching in the underlying integer index.
648+
649+
Parameters
650+
----------
651+
target : list-like of keys
652+
Each key is a tuple, with a label for each level of the index.
653+
654+
Returns
655+
------
656+
int_keys : 1-dimensional array of dtype uint64 or object
657+
Integers representing one combination each
658+
"""
659+
660+
level_codes = [lev.get_indexer(codes) + 1 for lev, codes
661+
in zip(self.levels, zip(*target))]
662+
return self._codes_to_ints(np.array(level_codes, dtype='uint64').T)
663+
664+
def get_indexer(self, object target, object method=None,
665+
object limit=None):
666+
lab_ints = self._extract_level_codes(target)
667+
668+
# All methods (exact, backfill, pad) directly map to the respective
669+
# methods of the underlying (integers) index...
670+
if method is not None:
671+
# but underlying backfill and pad methods require index and keys
672+
# to be sorted. The index already is (checked in
673+
# Index._get_fill_indexer), sort (integer representations of) keys:
674+
order = np.argsort(lab_ints)
675+
lab_ints = lab_ints[order]
676+
indexer = (getattr(self._base, 'get_{}_indexer'.format(method))
677+
(self, lab_ints, limit=limit))
678+
indexer = indexer[order]
679+
else:
680+
indexer = self._base.get_indexer(self, lab_ints)
681+
682+
return indexer
683+
684+
def get_loc(self, object key):
685+
if is_definitely_invalid_key(key):
686+
raise TypeError("'{key}' is an invalid key".format(key=key))
687+
if not PyTuple_Check(key):
688+
raise KeyError(key)
689+
try:
690+
indices = [0 if checknull(v) else lev.get_loc(v) + 1
691+
for lev, v in zip(self.levels, key)]
692+
except KeyError:
693+
raise KeyError(key)
694+
695+
# ndmin=2 because codes_to_ints expects multiple labels:
696+
indices = np.array(indices, ndmin=2, dtype='uint64')
697+
# ... and returns a (length 1, in this case) array of integers:
698+
lab_int = self._codes_to_ints(indices)[0]
699+
700+
return self._base.get_loc(self, lab_int)
701+
702+
def get_indexer_non_unique(self, object target):
703+
# This needs to be overridden just because the default one works on
704+
# target._values, and target can be itself a MultiIndex.
705+
706+
lab_ints = self._extract_level_codes(target)
707+
indexer = self._base.get_indexer_non_unique(self, lab_ints)
708+
709+
return indexer
710+
711+
def __contains__(self, object val):
712+
# Default __contains__ looks in the underlying mapping, which in this
713+
# case only contains integer representations.
714+
try:
715+
self.get_loc(val)
716+
return True
717+
except (KeyError, TypeError, ValueError):
718+
return False
719+
720+
721+
586722
cdef class MultiIndexObjectEngine(ObjectEngine):
587723
"""
588724
provide the same interface as the MultiIndexEngine

pandas/core/indexes/multi.py

+91-11
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,77 @@
4545
target_klass='MultiIndex or list of tuples'))
4646

4747

48+
class MultiIndexUIntEngine(libindex.BaseMultiIndexCodesEngine,
49+
libindex.UInt64Engine):
50+
"""
51+
This class manages a MultiIndex by mapping label combinations to positive
52+
integers.
53+
"""
54+
_base = libindex.UInt64Engine
55+
56+
def _codes_to_ints(self, codes):
57+
"""
58+
Transform each row of a 2d array of uint64 in a uint64, in a strictly
59+
monotonic way (i.e. respecting the lexicographic order of integer
60+
combinations): see BaseMultiIndexCodesEngine documentation.
61+
62+
Parameters
63+
----------
64+
codes : 2-dimensional array of dtype uint64
65+
Combinations of integers (one per row)
66+
67+
Returns
68+
------
69+
int_keys : 1-dimensional array of dtype uint64
70+
Integers representing one combination each
71+
"""
72+
# Shift the representation of each level by the pre-calculated number
73+
# of bits:
74+
codes <<= self.offsets
75+
76+
# Now sum and OR are in fact interchangeable. This is a simple
77+
# composition of the (disjunct) significant bits of each level (i.e.
78+
# each column in "codes") in a single positive integer (per row):
79+
return np.bitwise_or.reduce(codes, axis=1)
80+
81+
82+
class MultiIndexPyIntEngine(libindex.BaseMultiIndexCodesEngine,
83+
libindex.ObjectEngine):
84+
"""
85+
This class manages those (extreme) cases in which the number of possible
86+
label combinations overflows the 64 bits integers, and uses an ObjectEngine
87+
containing Python integers.
88+
"""
89+
_base = libindex.ObjectEngine
90+
91+
def _codes_to_ints(self, codes):
92+
"""
93+
Transform each row of a 2d array of uint64 in a Python integer, in a
94+
strictly monotonic way (i.e. respecting the lexicographic order of
95+
integer combinations): see BaseMultiIndexCodesEngine documentation.
96+
97+
Parameters
98+
----------
99+
codes : 2-dimensional array of dtype uint64
100+
Combinations of integers (one per row)
101+
102+
Returns
103+
------
104+
int_keys : 1-dimensional array of dtype object
105+
Integers representing one combination each
106+
"""
107+
108+
# Shift the representation of each level by the pre-calculated number
109+
# of bits. Since this can overflow uint64, first make sure we are
110+
# working with Python integers:
111+
codes = codes.astype('object') << self.offsets
112+
113+
# Now sum and OR are in fact interchangeable. This is a simple
114+
# composition of the (disjunct) significant bits of each level (i.e.
115+
# each column in "codes") in a single positive integer (per row):
116+
return np.bitwise_or.reduce(codes, axis=1)
117+
118+
48119
class MultiIndex(Index):
49120
"""
50121
A multi-level, or hierarchical, index object for pandas objects
@@ -687,16 +758,25 @@ def _get_level_number(self, level):
687758

688759
@cache_readonly
689760
def _engine(self):
690-
691-
# choose our engine based on our size
692-
# the hashing based MultiIndex for larger
693-
# sizes, and the MultiIndexOjbect for smaller
694-
# xref: https://github.com/pandas-dev/pandas/pull/16324
695-
l = len(self)
696-
if l > 10000:
697-
return libindex.MultiIndexHashEngine(lambda: self, l)
698-
699-
return libindex.MultiIndexObjectEngine(lambda: self.values, l)
761+
# Calculate the number of bits needed to represent labels in each
762+
# level, as log2 of their sizes (including -1 for NaN):
763+
sizes = np.ceil(np.log2([len(l) + 1 for l in self.levels]))
764+
765+
# Sum bit counts, starting from the _right_....
766+
lev_bits = np.cumsum(sizes[::-1])[::-1]
767+
768+
# ... in order to obtain offsets such that sorting the combination of
769+
# shifted codes (one for each level, resulting in a unique integer) is
770+
# equivalent to sorting lexicographically the codes themselves. Notice
771+
# that each level needs to be shifted by the number of bits needed to
772+
# represent the _previous_ ones:
773+
offsets = np.concatenate([lev_bits[1:], [0]]).astype('uint64')
774+
775+
# Check the total number of bits needed for our representation:
776+
if lev_bits[0] > 64:
777+
# The levels would overflow a 64 bit uint - use Python integers:
778+
return MultiIndexPyIntEngine(self.levels, self.labels, offsets)
779+
return MultiIndexUIntEngine(self.levels, self.labels, offsets)
700780

701781
@property
702782
def values(self):
@@ -1885,7 +1965,7 @@ def get_indexer(self, target, method=None, limit=None, tolerance=None):
18851965
if tolerance is not None:
18861966
raise NotImplementedError("tolerance not implemented yet "
18871967
'for MultiIndex')
1888-
indexer = self._get_fill_indexer(target, method, limit)
1968+
indexer = self._engine.get_indexer(target, method, limit)
18891969
elif method == 'nearest':
18901970
raise NotImplementedError("method='nearest' not implemented yet "
18911971
'for MultiIndex; see GitHub issue 9365')

0 commit comments

Comments
 (0)