Skip to content

REF: Use _maybe_cast_indexer and dont override Categorical.get_loc #31681

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 3 commits into from
Feb 6, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
38 changes: 2 additions & 36 deletions pandas/core/indexes/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -439,44 +439,10 @@ def _to_safe_for_reshape(self):
""" convert to object if we are a categorical """
return self.astype("object")

def get_loc(self, key, method=None):
"""
Get integer location, slice or boolean mask for requested label.
Parameters
----------
key : label
method : {None}
* default: exact matches only.
Returns
-------
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'))
>>> unique_index.get_loc('b')
1
>>> monotonic_index = pd.CategoricalIndex(list('abbc'))
>>> monotonic_index.get_loc('b')
slice(1, 3, None)
>>> non_monotonic_index = pd.CategoricalIndex(list('abcb'))
>>> non_monotonic_index.get_loc('b')
array([False, True, False, True], dtype=bool)
"""
def _maybe_cast_indexer(self, key):
code = self.categories.get_loc(key)
code = self.codes.dtype.type(code)
try:
return self._engine.get_loc(code)
except KeyError:
raise KeyError(key)
return code

def get_value(self, series: "Series", key: Any):
"""
Expand Down
2 changes: 2 additions & 0 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -861,6 +861,8 @@ def __getitem__(self, key):

return result
except InvalidIndexError:
if not isinstance(self.index, MultiIndex):
raise
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this related to the rest of the PR? Is there a test that otherwise fails?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

woops, not related, thought i had reverted this

pass
except (KeyError, ValueError):
if isinstance(key, tuple) and isinstance(self.index, MultiIndex):
Expand Down
17 changes: 17 additions & 0 deletions pandas/tests/indexes/categorical/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,23 @@ def test_get_loc(self):
with pytest.raises(KeyError, match="'c'"):
i.get_loc("c")

def test_get_loc_unique(self):
cidx = pd.CategoricalIndex(list("abc"))
result = cidx.get_loc("b")
assert result == 1

def test_get_loc_monotonic_nonunique(self):
cidx = pd.CategoricalIndex(list("abbc"))
result = cidx.get_loc("b")
expected = slice(1, 3, None)
assert result == expected

def test_get_loc_nonmonotonic_nonunique(self):
cidx = pd.CategoricalIndex(list("abcb"))
result = cidx.get_loc("b")
expected = np.array([False, True, False, True], dtype=bool)
tm.assert_numpy_array_equal(result, expected)


class TestGetIndexer:
def test_get_indexer_base(self):
Expand Down