Skip to content

Commit 39f90fe

Browse files
committed
BUG: loc misbehaves when Period is at start of 3-level MultiIndex
(#20684) If index is MultiIndex and level of 0 is PeriodIndex, loc function raise exception if all input of loc does not match index values
1 parent 96bf661 commit 39f90fe

File tree

4 files changed

+21
-2
lines changed

4 files changed

+21
-2
lines changed

doc/source/whatsnew/v1.0.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ Missing
174174
MultiIndex
175175
^^^^^^^^^^
176176

177-
-
177+
- Bug in :meth:`DataFrame.loc` where :class:`PeriodIndex` is in level of 0 raise exception if entire key is not matched (:issue:`20684`)
178178
-
179179

180180
I/O

pandas/_libs/tslibs/parsing.pyx

+1-1
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,7 @@ def parse_time_string(arg, freq=None, dayfirst=None, yearfirst=None):
254254
if not isinstance(arg, (str, unicode)):
255255
# Note: cython recognizes `unicode` in both py2/py3, optimizes
256256
# this check into a C call.
257-
return arg
257+
raise TypeError
258258

259259
if getattr(freq, "_typ", None) == "dateoffset":
260260
freq = freq.rule_code

pandas/tests/indexes/period/test_period.py

+9
Original file line numberDiff line numberDiff line change
@@ -617,6 +617,15 @@ def test_insert(self):
617617
result = period_range("2017Q1", periods=4, freq="Q").insert(1, na)
618618
tm.assert_index_equal(result, expected)
619619

620+
def test_contains_raise_key_error(self):
621+
# issue 20684
622+
df = DataFrame(
623+
{"A": [Period("2019")], "B": ["x"], "C": ["y"], "V": [10]}
624+
).set_index(["A", "B", "C"])
625+
msg = r"Period\('2019', 'A-DEC'\), 'foo', 'bar'"
626+
with pytest.raises(KeyError, match=msg):
627+
df.loc[(Period("2019"), "foo", "bar")]
628+
620629

621630
def test_maybe_convert_timedelta():
622631
pi = PeriodIndex(["2000", "2001"], freq="D")

pandas/tests/tslibs/test_parsing.py

+10
Original file line numberDiff line numberDiff line change
@@ -209,3 +209,13 @@ def test_try_parse_dates():
209209

210210
expected = np.array([parse(d, dayfirst=True) for d in arr])
211211
tm.assert_numpy_array_equal(result, expected)
212+
213+
214+
def test_check_instance_type():
215+
# issue 20684
216+
with pytest.raises(TypeError):
217+
parse_time_string((1, 2, 3))
218+
219+
result = parse_time_string("2019")
220+
expected = (datetime(2019, 1, 1), datetime(2019, 1, 1), "year")
221+
assert result == expected

0 commit comments

Comments
 (0)