Skip to content

Commit e6ea4da

Browse files
committed
BUG: Index.get_loc raising incorrect error, closes pandas-dev#29189
1 parent e246c3b commit e6ea4da

File tree

3 files changed

+29
-2
lines changed

3 files changed

+29
-2
lines changed

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
@@ -1951,3 +1951,13 @@ def test_groupby_only_none_group():
19511951
expected = pd.Series([np.nan], name="x")
19521952

19531953
tm.assert_series_equal(actual, expected)
1954+
1955+
1956+
def test_groupby_duplicate_index():
1957+
# GH#29189 the groupby call here used to raise
1958+
ser = pd.Series([2, 5, 6, 8], index=[2.0, 4.0, 4.0, 5.0])
1959+
gb = ser.groupby(level=0)
1960+
1961+
result = gb.mean()
1962+
expected = pd.Series([2, 5.5, 8], index=[2., 4., 5.])
1963+
tm.assert_series_equal(result, expected)

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)