Skip to content

ERR: Improve error message for Series.loc.getitem with too many dimensions #39372

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 3 commits into from
Jan 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ Other enhancements
- :meth:`DataFrame.apply` can now accept non-callable DataFrame properties as strings, e.g. ``df.apply("size")``, which was already the case for :meth:`Series.apply` (:issue:`39116`)
- :meth:`Series.apply` can now accept list-like or dictionary-like arguments that aren't lists or dictionaries, e.g. ``ser.apply(np.array(["sum", "mean"]))``, which was already the case for :meth:`DataFrame.apply` (:issue:`39140`)
- :meth:`.Styler.set_tooltips` allows on hover tooltips to be added to styled HTML dataframes.
- :meth:`Series.loc.__getitem__` and :meth:`Series.loc.__setitem__` with :class:`MultiIndex` now raising helpful error message when indexer has too many dimensions (:issue:`35349`)

.. ---------------------------------------------------------------------------

Expand Down
10 changes: 10 additions & 0 deletions pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -846,6 +846,11 @@ def _getitem_nested_tuple(self, tup: Tuple):
if self.name != "loc":
# This should never be reached, but lets be explicit about it
raise ValueError("Too many indices")
if isinstance(self.obj, ABCSeries) and any(
isinstance(k, tuple) for k in tup
):
# GH#35349 Raise if tuple in tuple for series
raise ValueError("Too many indices")
if self.ndim == 1 or not any(isinstance(x, slice) for x in tup):
# GH#10521 Series should reduce MultiIndex dimensions instead of
# DataFrame, IndexingError is not raised when slice(None,None,None)
Expand Down Expand Up @@ -1203,6 +1208,11 @@ def _convert_to_indexer(self, key, axis: int, is_setter: bool = False):
return {"key": key}

if is_nested_tuple(key, labels):
if isinstance(self.obj, ABCSeries) and any(
isinstance(k, tuple) for k in key
):
# GH#35349 Raise if tuple in tuple for series
raise ValueError("Too many indices")
return labels.get_locs(key)

elif is_list_like_indexer(key):
Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/indexing/test_loc.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
DataFrame,
DatetimeIndex,
Index,
IndexSlice,
MultiIndex,
Series,
SparseDtype,
Expand Down Expand Up @@ -2130,3 +2131,17 @@ def test_loc_iloc_setitem_with_listlike(self, size, array_fn):
ser = Series(0, index=list("abcde"), dtype=object)
ser.iloc[0] = arr
tm.assert_series_equal(ser, expected)

@pytest.mark.parametrize("indexer", [IndexSlice["A", :], ("A", slice(None))])
def test_loc_series_getitem_too_many_dimensions(self, indexer):
# GH#35349
ser = Series(
index=MultiIndex.from_tuples([("A", "0"), ("A", "1"), ("B", "0")]),
data=[21, 22, 23],
)
msg = "Too many indices"
with pytest.raises(ValueError, match=msg):
ser.loc[indexer, :]

with pytest.raises(ValueError, match=msg):
ser.loc[indexer, :] = 1