Skip to content

ENH: Better Exception when trying to set on Series with tuple-index. #4837

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
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
2 changes: 2 additions & 0 deletions doc/source/release.rst
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ Improvements to existing features
thanks @lgautier
- DataFrame constructor now accepts a numpy masked record array (:issue:`3478`),
thanks @jnothman
- ``__getitem__`` with ``tuple`` key (e.g., ``[:, 2]``) on ``Series``
without ``MultiIndex`` raises ``ValueError`` (:issue:`4759`, :issue:`4837`)

API Changes
~~~~~~~~~~~
Expand Down
2 changes: 2 additions & 0 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -1050,6 +1050,8 @@ def __setitem__(self, key, value):
return

except TypeError as e:
if isinstance(key, tuple) and not isinstance(self.index, MultiIndex):
raise ValueError("Can only tuple-index with a MultiIndex")
# python 3 type errors should be raised
if 'unorderable' in str(e): # pragma: no cover
raise IndexError(key)
Expand Down
8 changes: 4 additions & 4 deletions pandas/tests/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -1025,10 +1025,10 @@ def test_setslice(self):

def test_basic_getitem_setitem_corner(self):
# invalid tuples, e.g. self.ts[:, None] vs. self.ts[:, 2]
self.assertRaises(Exception, self.ts.__getitem__,
(slice(None, None), 2))
self.assertRaises(Exception, self.ts.__setitem__,
(slice(None, None), 2), 2)
with tm.assertRaisesRegexp(ValueError, 'tuple-index'):
self.ts[:, 2]
with tm.assertRaisesRegexp(ValueError, 'tuple-index'):
self.ts[:, 2] = 2

# weird lists. [slice(0, 5)] will work but not two slices
result = self.ts[[slice(None, 5)]]
Expand Down