Skip to content

Commit 921bdfa

Browse files
authored
REF: implement MultiIndex._get_indexer_level_0 (#42480)
1 parent 9785f81 commit 921bdfa

File tree

1 file changed

+16
-12
lines changed

1 file changed

+16
-12
lines changed

pandas/core/indexes/multi.py

+16-12
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,6 @@
7373
from pandas.core.arrays import Categorical
7474
from pandas.core.arrays.categorical import factorize_from_iterables
7575
import pandas.core.common as com
76-
from pandas.core.indexers import is_empty_indexer
7776
import pandas.core.indexes.base as ibase
7877
from pandas.core.indexes.base import (
7978
Index,
@@ -2559,24 +2558,29 @@ def _convert_listlike_indexer(self, keyarr) -> np.ndarray | None:
25592558

25602559
# are we indexing a specific level
25612560
if len(keyarr) and not isinstance(keyarr[0], tuple):
2562-
_, indexer = self.reindex(keyarr, level=0)
2563-
2564-
# take all
2565-
if indexer is None:
2566-
indexer = np.arange(len(self), dtype=np.intp)
2567-
return indexer
2568-
2569-
check = self.levels[0].get_indexer(keyarr)
2570-
mask = check == -1
2561+
indexer = self._get_indexer_level_0(keyarr)
2562+
mask = indexer == -1
25712563
if mask.any():
2572-
raise KeyError(f"{keyarr[mask]} not in index")
2573-
elif is_empty_indexer(indexer, keyarr):
2564+
check = self.levels[0].get_indexer(keyarr)
2565+
cmask = check == -1
2566+
if cmask.any():
2567+
raise KeyError(f"{keyarr[cmask]} not in index")
25742568
# We get here when levels still contain values which are not
25752569
# actually in Index anymore
25762570
raise KeyError(f"{keyarr} not in index")
25772571

25782572
return indexer
25792573

2574+
def _get_indexer_level_0(self, target) -> np.ndarray:
2575+
"""
2576+
Optimized equivalent to `self.get_level_values(0).get_indexer_for(target)`.
2577+
"""
2578+
lev = self.levels[0]
2579+
codes = self._codes[0]
2580+
cat = Categorical.from_codes(codes=codes, categories=lev)
2581+
ci = Index(cat)
2582+
return ci.get_indexer_for(target)
2583+
25802584
def _get_partial_string_timestamp_match_key(self, key):
25812585
"""
25822586
Translate any partial string timestamp matches in key, returning the

0 commit comments

Comments
 (0)