Skip to content

Commit 606e0fe

Browse files
BUG: Unexpected KeyError message when using .loc with MultiIndex in a possible edge-case (#52194)
1 parent 5c4cc4a commit 606e0fe

File tree

4 files changed

+19
-4
lines changed

4 files changed

+19
-4
lines changed

pandas/core/indexes/multi.py

+2
Original file line numberDiff line numberDiff line change
@@ -2841,6 +2841,8 @@ def _maybe_to_slice(loc):
28412841
# i.e. do we need _index_as_unique on that level?
28422842
try:
28432843
return self._engine.get_loc(key)
2844+
except KeyError as err:
2845+
raise KeyError(key) from err
28442846
except TypeError:
28452847
# e.g. test_partial_slicing_with_multiindex partial string slicing
28462848
loc, _ = self.get_loc_level(key, list(range(self.nlevels)))

pandas/tests/indexes/multi/test_drop.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -32,16 +32,16 @@ def test_drop(idx):
3232
tm.assert_index_equal(dropped, expected)
3333

3434
index = MultiIndex.from_tuples([("bar", "two")])
35-
with pytest.raises(KeyError, match=r"^15$"):
35+
with pytest.raises(KeyError, match=r"^\('bar', 'two'\)$"):
3636
idx.drop([("bar", "two")])
37-
with pytest.raises(KeyError, match=r"^15$"):
37+
with pytest.raises(KeyError, match=r"^\('bar', 'two'\)$"):
3838
idx.drop(index)
3939
with pytest.raises(KeyError, match=r"^'two'$"):
4040
idx.drop(["foo", "two"])
4141

4242
# partially correct argument
4343
mixed_index = MultiIndex.from_tuples([("qux", "one"), ("bar", "two")])
44-
with pytest.raises(KeyError, match=r"^15$"):
44+
with pytest.raises(KeyError, match=r"^\('bar', 'two'\)$"):
4545
idx.drop(mixed_index)
4646

4747
# error='ignore'

pandas/tests/indexes/multi/test_indexing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -565,7 +565,7 @@ class TestGetLoc:
565565
def test_get_loc(self, idx):
566566
assert idx.get_loc(("foo", "two")) == 1
567567
assert idx.get_loc(("baz", "two")) == 3
568-
with pytest.raises(KeyError, match=r"^15$"):
568+
with pytest.raises(KeyError, match=r"^\('bar', 'two'\)$"):
569569
idx.get_loc(("bar", "two"))
570570
with pytest.raises(KeyError, match=r"^'quux'$"):
571571
idx.get_loc("quux")

pandas/tests/indexing/multiindex/test_loc.py

+13
Original file line numberDiff line numberDiff line change
@@ -420,6 +420,19 @@ def test_loc_no_second_level_index(self):
420420
)
421421
tm.assert_frame_equal(res, expected)
422422

423+
def test_loc_multi_index_key_error(self):
424+
# GH 51892
425+
df = DataFrame(
426+
{
427+
(1, 2): ["a", "b", "c"],
428+
(1, 3): ["d", "e", "f"],
429+
(2, 2): ["g", "h", "i"],
430+
(2, 4): ["j", "k", "l"],
431+
}
432+
)
433+
with pytest.raises(KeyError, match=r"(1, 4)"):
434+
df.loc[0, (1, 4)]
435+
423436

424437
@pytest.mark.parametrize(
425438
"indexer, pos",

0 commit comments

Comments
 (0)