Skip to content

Commit

Permalink
REF: simplify Float64Index.get_loc (pandas-dev#31123)
Browse files Browse the repository at this point in the history
  • Loading branch information
jbrockmendel authored and jreback committed Jan 18, 2020
1 parent 52c22b2 commit a446979
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 13 deletions.
23 changes: 12 additions & 11 deletions pandas/core/indexes/numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -488,17 +488,18 @@ def __contains__(self, other) -> bool:

@Appender(_index_shared_docs["get_loc"])
def get_loc(self, key, method=None, tolerance=None):
try:
if np.all(np.isnan(key)) or is_bool(key):
nan_idxs = self._nan_idxs
try:
return nan_idxs.item()
except ValueError:
if not len(nan_idxs):
raise KeyError(key)
return nan_idxs
except (TypeError, NotImplementedError):
pass
if is_bool(key):
# Catch this to avoid accidentally casting to 1.0
raise KeyError(key)

if is_float(key) and np.isnan(key):
nan_idxs = self._nan_idxs
if not len(nan_idxs):
raise KeyError(key)
elif len(nan_idxs) == 1:
return nan_idxs[0]
return nan_idxs

return super().get_loc(key, method=method, tolerance=tolerance)

@cache_readonly
Expand Down
3 changes: 2 additions & 1 deletion pandas/tests/indexes/multi/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,8 @@ def test_get_loc_missing_nan():
idx.get_loc(3)
with pytest.raises(KeyError, match=r"^nan$"):
idx.get_loc(np.nan)
with pytest.raises(KeyError, match=r"^\[nan\]$"):
with pytest.raises(TypeError, match=r"'\[nan\]' is an invalid key"):
# listlike/non-hashable raises TypeError
idx.get_loc([np.nan])


Expand Down
3 changes: 2 additions & 1 deletion pandas/tests/indexes/test_numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,8 @@ def test_get_loc_missing_nan(self):
idx.get_loc(3)
with pytest.raises(KeyError, match="^nan$"):
idx.get_loc(np.nan)
with pytest.raises(KeyError, match=r"^\[nan\]$"):
with pytest.raises(TypeError, match=r"'\[nan\]' is an invalid key"):
# listlike/non-hashable raises TypeError
idx.get_loc([np.nan])

def test_contains_nans(self):
Expand Down

0 comments on commit a446979

Please sign in to comment.