Join GitHub today
GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.Sign up
Wrong "Too many indexers" error message when indexing a Series with MultiIndex #14885
Code Sample, a copy-pastable example if possible
In : s = pd.Series(range(4), index=pd.MultiIndex.from_product([['a', 'b'], ['c', 'd']])) In : s.loc['a', 'e'] --------------------------------------------------------------------------- IndexingError Traceback (most recent call last) <ipython-input-3-042ed7ab0463> in <module>() ----> 1 s.loc['a', 'e'] /home/pietro/nobackup/repo/pandas/pandas/core/indexing.py in __getitem__(self, key) 1308 1309 if type(key) is tuple: -> 1310 return self._getitem_tuple(key) 1311 else: 1312 return self._getitem_axis(key, axis=0) /home/pietro/nobackup/repo/pandas/pandas/core/indexing.py in _getitem_tuple(self, tup) 799 800 # no multi-index, so validate all of the indexers --> 801 self._has_valid_tuple(tup) 802 803 # ugly hack for GH #836 /home/pietro/nobackup/repo/pandas/pandas/core/indexing.py in _has_valid_tuple(self, key) 148 for i, k in enumerate(key): 149 if i >= self.obj.ndim: --> 150 raise IndexingError('Too many indexers') 151 if not self._has_valid_type(k, i): 152 raise ValueError("Location based indexing can only have [%s] " IndexingError: Too many indexers
The raised error, and the message, seem wrong to me.
This is what I get if I I take a
By the way,
... and by the way, I would expect the following to raise an
... instead the tuple is interpreted as a list of labels rather than as a key, and hence it works "fine". Is this behavior desired? (looks a bit inconsistent to me, but I see that it is generalized, i.e.
So i'll mark this as a bug / error reporting for the 2 cases you have identified. PR's welcome.
It doesn't only look the same, it is actually exactly the same for getitem.
Some similar other cases where the multi-indexing gets it wrong (using the same example series):
In this case I would have expected the 'too many indexers' error.
Also when slicing the first levels, you get this error message:
which can be very misleading in a real-world use case with a large dataframe and points you in the wrong direction for trying to fix your code (encountered this last week).
Regarding the other example you give:
I don't think this should ever raise a "IndexingError: Too many indexers" as you actually have a length 2 indexer (so suits the multi-index). But you are correct the interpretation of the tuple here as a list may be a bit inconsistent.