diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index 03ad8ed162c95..ffa65032e6aae 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -945,6 +945,7 @@ Indexing - Bug in :meth:`Series.__setitem__` when assigning boolean series with boolean indexer will raise ``LossySetitemError`` (:issue:`57338`) - Bug in printing :attr:`Index.names` and :attr:`MultiIndex.levels` would not escape single quotes (:issue:`60190`) - Bug in reindexing of :class:`DataFrame` with :class:`PeriodDtype` columns in case of consolidated block (:issue:`60980`, :issue:`60273`) +- Bug in :meth:`Index.__getitem__` incorrectly raising with a 0-dim ``np.ndarray`` key (:issue:`55601`) Missing ^^^^^^^ diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 59ac122e4f9ea..2ec774af15934 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -5219,6 +5219,7 @@ def __getitem__(self, key): """ getitem = self._data.__getitem__ + key = lib.item_from_zerodim(key) if is_integer(key) or is_float(key): # GH#44051 exclude bool, which would return a 2d ndarray key = com.cast_scalar_indexer(key) diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 016b30e215d02..0290fae46c9a1 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -2235,6 +2235,7 @@ def __reduce__(self): # -------------------------------------------------------------------- def __getitem__(self, key): + key = lib.item_from_zerodim(key) if is_scalar(key): key = com.cast_scalar_indexer(key) diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index a3b173d297253..4560d3cc3479a 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -1175,6 +1175,7 @@ def __getitem__(self, key): """ Conserve RangeIndex type for scalar and slice keys. """ + key = lib.item_from_zerodim(key) if key is Ellipsis: key = slice(None) if isinstance(key, slice): diff --git a/pandas/tests/indexes/test_any_index.py b/pandas/tests/indexes/test_any_index.py index be15bce8bb82f..69ebfc50530e4 100644 --- a/pandas/tests/indexes/test_any_index.py +++ b/pandas/tests/indexes/test_any_index.py @@ -117,6 +117,15 @@ def test_pickle_preserves_name(self, index): class TestIndexing: + def test_getitem_0d_ndarray(self, index): + # GH#55601 + if len(index) == 0: + pytest.skip(reason="Test assumes non-empty index") + key = np.array(0) + result = index[key] + + assert result == index[0] + def test_get_loc_listlike_raises_invalid_index_error(self, index): # and never TypeError key = np.array([0, 1], dtype=np.intp)