Skip to content

BUG: Raise KeyError when indexing a Series with MultiIndex #26155

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Apr 26, 2019
Merged
9 changes: 8 additions & 1 deletion pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -944,6 +944,8 @@ def _handle_lowerdim_multi_index_axis0(self, tup):
except TypeError:
# slices are unhashable
pass
except KeyError:
return None
except Exception as e1:
if isinstance(tup[0], (slice, Index)):
raise IndexingError("Handle elsewhere")
Expand Down Expand Up @@ -976,7 +978,12 @@ def _getitem_lowerdim(self, tup):
return result

if len(tup) > self.obj.ndim:
raise IndexingError("Too many indexers. handle elsewhere")
try:
self._get_label(tup, axis=self.axis)
except KeyError:
return self._get_label(tup, axis=self.axis)
except Exception:
raise IndexingError("Too many indexers. handle elsewhere")

# to avoid wasted computation
# df.ix[d1:d2, 0] -> columns first (True)
Expand Down
3 changes: 1 addition & 2 deletions pandas/tests/indexing/multiindex/test_getitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import pytest

from pandas import DataFrame, Index, MultiIndex, Series
from pandas.core.indexing import IndexingError
from pandas.util import testing as tm

# ----------------------------------------------------------------------------
Expand Down Expand Up @@ -85,7 +84,7 @@ def test_series_getitem_returns_scalar(
@pytest.mark.parametrize('indexer,expected_error,expected_error_msg', [
(lambda s: s.__getitem__((2000, 3, 4)), KeyError, r"^356L?$"),
(lambda s: s[(2000, 3, 4)], KeyError, r"^356L?$"),
(lambda s: s.loc[(2000, 3, 4)], IndexingError, 'Too many indexers'),
(lambda s: s.loc[(2000, 3, 4)], KeyError, r"^356L?$"),
(lambda s: s.__getitem__(len(s)), IndexError, 'index out of bounds'),
(lambda s: s[len(s)], IndexError, 'index out of bounds'),
(lambda s: s.iloc[len(s)], IndexError,
Expand Down