Skip to content

Commit bdd5d4c

Browse files
authored
BUG: PeriodIndex.get_loc incorrectly raising ValueError instead of KeyError (#36015)
1 parent 4f2251c commit bdd5d4c

File tree

4 files changed

+21
-5
lines changed

4 files changed

+21
-5
lines changed

doc/source/whatsnew/v1.2.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ Interval
217217

218218
Indexing
219219
^^^^^^^^
220-
220+
- Bug in :meth:`PeriodIndex.get_loc` incorrectly raising ``ValueError`` on non-datelike strings instead of ``KeyError``, causing similar errors in :meth:`Series.__geitem__`, :meth:`Series.__contains__`, and :meth:`Series.loc.__getitem__` (:issue:`34240`)
221221
-
222222
-
223223

pandas/core/groupby/grouper.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -755,9 +755,9 @@ def is_in_obj(gpr) -> bool:
755755
return False
756756
try:
757757
return gpr is obj[gpr.name]
758-
except (KeyError, IndexError, ValueError):
759-
# TODO: ValueError: Given date string not likely a datetime.
760-
# should be KeyError?
758+
except (KeyError, IndexError):
759+
# IndexError reached in e.g. test_skip_group_keys when we pass
760+
# lambda here
761761
return False
762762

763763
for i, (gpr, level) in enumerate(zip(keys, levels)):

pandas/core/indexes/period.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -504,7 +504,7 @@ def get_loc(self, key, method=None, tolerance=None):
504504

505505
try:
506506
asdt, reso = parse_time_string(key, self.freq)
507-
except DateParseError as err:
507+
except (ValueError, DateParseError) as err:
508508
# A string with invalid format
509509
raise KeyError(f"Cannot interpret '{key}' as period") from err
510510

pandas/tests/indexes/period/test_indexing.py

+16
Original file line numberDiff line numberDiff line change
@@ -359,6 +359,22 @@ def test_get_loc2(self):
359359
],
360360
)
361361

362+
def test_get_loc_invalid_string_raises_keyerror(self):
363+
# GH#34240
364+
pi = pd.period_range("2000", periods=3, name="A")
365+
with pytest.raises(KeyError, match="A"):
366+
pi.get_loc("A")
367+
368+
ser = pd.Series([1, 2, 3], index=pi)
369+
with pytest.raises(KeyError, match="A"):
370+
ser.loc["A"]
371+
372+
with pytest.raises(KeyError, match="A"):
373+
ser["A"]
374+
375+
assert "A" not in ser
376+
assert "A" not in pi
377+
362378

363379
class TestGetIndexer:
364380
def test_get_indexer(self):

0 commit comments

Comments
 (0)