Skip to content

Commit 7eb0db3

Browse files
jbrockmendeljreback
authored andcommitted
BUG: Index.get_loc raising incorrect error, closes #29189 (#29700)
1 parent 5e9bff6 commit 7eb0db3

File tree

4 files changed

+30
-3
lines changed

4 files changed

+30
-3
lines changed

doc/source/whatsnew/v1.0.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -562,7 +562,7 @@ Indexing
562562
- Bug in :meth:`Float64Index.astype` where ``np.inf`` was not handled properly when casting to an integer dtype (:issue:`28475`)
563563
- :meth:`Index.union` could fail when the left contained duplicates (:issue:`28257`)
564564
- :meth:`Index.get_indexer_non_unique` could fail with `TypeError` in some cases, such as when searching for ints in a string index (:issue:`28257`)
565-
-
565+
- Bug in :meth:`Float64Index.get_loc` incorrectly raising ``TypeError`` instead of ``KeyError`` (:issue:`29189`)
566566

567567
Missing
568568
^^^^^^^

pandas/_libs/index.pyx

+6-2
Original file line numberDiff line numberDiff line change
@@ -141,8 +141,12 @@ cdef class IndexEngine:
141141

142142
if self.is_monotonic_increasing:
143143
values = self._get_index_values()
144-
left = values.searchsorted(val, side='left')
145-
right = values.searchsorted(val, side='right')
144+
try:
145+
left = values.searchsorted(val, side='left')
146+
right = values.searchsorted(val, side='right')
147+
except TypeError:
148+
# e.g. GH#29189 get_loc(None) with a Float64Index
149+
raise KeyError(val)
146150

147151
diff = right - left
148152
if diff == 0:

pandas/tests/groupby/test_groupby.py

+10
Original file line numberDiff line numberDiff line change
@@ -1942,6 +1942,16 @@ def test_groupby_only_none_group():
19421942
tm.assert_series_equal(actual, expected)
19431943

19441944

1945+
def test_groupby_duplicate_index():
1946+
# GH#29189 the groupby call here used to raise
1947+
ser = pd.Series([2, 5, 6, 8], index=[2.0, 4.0, 4.0, 5.0])
1948+
gb = ser.groupby(level=0)
1949+
1950+
result = gb.mean()
1951+
expected = pd.Series([2, 5.5, 8], index=[2.0, 4.0, 5.0])
1952+
tm.assert_series_equal(result, expected)
1953+
1954+
19451955
@pytest.mark.parametrize("bool_agg_func", ["any", "all"])
19461956
def test_bool_aggs_dup_column_labels(bool_agg_func):
19471957
# 21668

pandas/tests/indexing/test_indexing.py

+13
Original file line numberDiff line numberDiff line change
@@ -1209,3 +1209,16 @@ def test_1tuple_without_multiindex():
12091209
result = ser[key]
12101210
expected = ser[key[0]]
12111211
tm.assert_series_equal(result, expected)
1212+
1213+
1214+
def test_duplicate_index_mistyped_key_raises_keyerror():
1215+
# GH#29189 float_index.get_loc(None) should raise KeyError, not TypeError
1216+
ser = pd.Series([2, 5, 6, 8], index=[2.0, 4.0, 4.0, 5.0])
1217+
with pytest.raises(KeyError):
1218+
ser[None]
1219+
1220+
with pytest.raises(KeyError):
1221+
ser.index.get_loc(None)
1222+
1223+
with pytest.raises(KeyError):
1224+
ser.index._engine.get_loc(None)

0 commit comments

Comments
 (0)