Skip to content

PERF: RangeIndex.get_loc #30930

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 6 commits into from
Jan 15, 2020
Merged
Show file tree
Hide file tree
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
15 changes: 9 additions & 6 deletions pandas/core/indexes/range.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from pandas.core.dtypes.common import (
ensure_platform_int,
ensure_python_int,
is_float,
is_integer,
is_integer_dtype,
is_list_like,
Expand Down Expand Up @@ -344,12 +345,14 @@ def __contains__(self, key: Union[int, np.integer]) -> bool:

@Appender(_index_shared_docs["get_loc"])
def get_loc(self, key, method=None, tolerance=None):
if is_integer(key) and method is None and tolerance is None:
new_key = int(key)
try:
return self._range.index(new_key)
except ValueError:
raise KeyError(key)
if method is None and tolerance is None:
if is_integer(key) or (is_float(key) and key.is_integer()):
Copy link
Member

Choose a reason for hiding this comment

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

Does the extra condition here imply any behavioral changes?

Copy link
Member Author

Choose a reason for hiding this comment

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

No, intlike floats go through here now instead of going through the _maybe_cast_indexer path in Index.get_loc.

new_key = int(key)
try:
return self._range.index(new_key)
except ValueError:
raise KeyError(key)
raise KeyError(key)
return super().get_loc(key, method=method, tolerance=tolerance)

@Appender(_index_shared_docs["get_indexer"])
Expand Down
7 changes: 4 additions & 3 deletions pandas/tests/indexes/ranges/test_range.py
Original file line number Diff line number Diff line change
Expand Up @@ -735,8 +735,9 @@ def test_engineless_lookup(self):

assert "_engine" not in idx._cache

# The engine is still required for lookup of a different dtype scalar:
# Different types of scalars can be excluded immediately, no need to
# use the _engine
with pytest.raises(KeyError, match="'a'"):
assert idx.get_loc("a") == -1
idx.get_loc("a")

assert "_engine" in idx._cache
assert "_engine" not in idx._cache