diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index abe4a00e0b813..0f010da02472e 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -2841,6 +2841,8 @@ def _maybe_to_slice(loc): # i.e. do we need _index_as_unique on that level? try: return self._engine.get_loc(key) + except KeyError as err: + raise KeyError(key) from err except TypeError: # e.g. test_partial_slicing_with_multiindex partial string slicing loc, _ = self.get_loc_level(key, list(range(self.nlevels))) diff --git a/pandas/tests/indexes/multi/test_drop.py b/pandas/tests/indexes/multi/test_drop.py index 4bfba07332313..f069cdbedabf0 100644 --- a/pandas/tests/indexes/multi/test_drop.py +++ b/pandas/tests/indexes/multi/test_drop.py @@ -32,16 +32,16 @@ def test_drop(idx): tm.assert_index_equal(dropped, expected) index = MultiIndex.from_tuples([("bar", "two")]) - with pytest.raises(KeyError, match=r"^15$"): + with pytest.raises(KeyError, match=r"^\('bar', 'two'\)$"): idx.drop([("bar", "two")]) - with pytest.raises(KeyError, match=r"^15$"): + with pytest.raises(KeyError, match=r"^\('bar', 'two'\)$"): idx.drop(index) with pytest.raises(KeyError, match=r"^'two'$"): idx.drop(["foo", "two"]) # partially correct argument mixed_index = MultiIndex.from_tuples([("qux", "one"), ("bar", "two")]) - with pytest.raises(KeyError, match=r"^15$"): + with pytest.raises(KeyError, match=r"^\('bar', 'two'\)$"): idx.drop(mixed_index) # error='ignore' diff --git a/pandas/tests/indexes/multi/test_indexing.py b/pandas/tests/indexes/multi/test_indexing.py index 31c5ab333ecfa..2b75efd130aa2 100644 --- a/pandas/tests/indexes/multi/test_indexing.py +++ b/pandas/tests/indexes/multi/test_indexing.py @@ -565,7 +565,7 @@ class TestGetLoc: def test_get_loc(self, idx): assert idx.get_loc(("foo", "two")) == 1 assert idx.get_loc(("baz", "two")) == 3 - with pytest.raises(KeyError, match=r"^15$"): + with pytest.raises(KeyError, match=r"^\('bar', 'two'\)$"): idx.get_loc(("bar", "two")) with pytest.raises(KeyError, match=r"^'quux'$"): idx.get_loc("quux") diff --git a/pandas/tests/indexing/multiindex/test_loc.py b/pandas/tests/indexing/multiindex/test_loc.py index d95b27574cd82..3bf8c2eaa7e94 100644 --- a/pandas/tests/indexing/multiindex/test_loc.py +++ b/pandas/tests/indexing/multiindex/test_loc.py @@ -420,6 +420,19 @@ def test_loc_no_second_level_index(self): ) tm.assert_frame_equal(res, expected) + def test_loc_multi_index_key_error(self): + # GH 51892 + df = DataFrame( + { + (1, 2): ["a", "b", "c"], + (1, 3): ["d", "e", "f"], + (2, 2): ["g", "h", "i"], + (2, 4): ["j", "k", "l"], + } + ) + with pytest.raises(KeyError, match=r"(1, 4)"): + df.loc[0, (1, 4)] + @pytest.mark.parametrize( "indexer, pos",