Skip to content

clean CategoricalIndex.get_loc and improve error message #23091

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions pandas/core/indexes/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,10 @@ def get_loc(self, key, method=None):
-------
loc : int if unique index, slice if monotonic index, else mask

Raises
------
KeyError : if the key is not in the index

Examples
---------
>>> unique_index = pd.CategoricalIndex(list('abc'))
Expand All @@ -440,10 +444,11 @@ def get_loc(self, key, method=None):
>>> non_monotonic_index.get_loc('b')
array([False, True, False, True], dtype=bool)
"""
codes = self.categories.get_loc(key)
if (codes == -1):
code = self.categories.get_loc(key)
try:
return self._engine.get_loc(code)
except KeyError:
raise KeyError(key)
return self._engine.get_loc(codes)

def get_value(self, series, key):
"""
Expand Down