Skip to content

Wrong behaviour/error when indexing MultiIndex with list #12416

Closed
@toobaz

Description

@toobaz
In [2]: df = pd.DataFrame(index=range(2), columns=pd.MultiIndex.from_product([[10,20], ['a', 'b']]))

In [3]: df[[20]]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-3-8422ebb3f356> in <module>()
----> 1 df[[20]]

/home/pietro/nobackup/repo/pandas/pandas/core/frame.pyc in __getitem__(self, key)
   1975         if isinstance(key, (Series, np.ndarray, Index, list)):
   1976             # either boolean or fancy integer index
-> 1977             return self._getitem_array(key)
   1978         elif isinstance(key, DataFrame):
   1979             return self._getitem_frame(key)

/home/pietro/nobackup/repo/pandas/pandas/core/frame.pyc in _getitem_array(self, key)
   2020         else:
   2021             indexer = self.ix._convert_to_indexer(key, axis=1)
-> 2022             return self.take(indexer, axis=1, convert=True)
   2023 
   2024     def _getitem_multilevel(self, key):

/home/pietro/nobackup/repo/pandas/pandas/core/generic.pyc in take(self, indices, axis, convert, is_copy)
   1590         new_data = self._data.take(indices,
   1591                                    axis=self._get_block_manager_axis(axis),
-> 1592                                    convert=True, verify=True)
   1593         result = self._constructor(new_data).__finalize__(self)
   1594 

/home/pietro/nobackup/repo/pandas/pandas/core/internals.pyc in take(self, indexer, axis, verify, convert)
   3617         n = self.shape[axis]
   3618         if convert:
-> 3619             indexer = maybe_convert_indices(indexer, n)
   3620 
   3621         if verify:

/home/pietro/nobackup/repo/pandas/pandas/core/indexing.pyc in maybe_convert_indices(indices, n)
   1803     mask = (indices >= n) | (indices < 0)
   1804     if mask.any():
-> 1805         raise IndexError("indices are out-of-bounds")
   1806     return indices
   1807 

IndexError: indices are out-of-bounds

and

In [4]: df[[1]]
Out[4]: 
    10
     b
0  NaN
1  NaN

should both raise KeyError (see #12369 (comment) )

Metadata

Metadata

Assignees

No one assigned

    Labels

    IndexingRelated to indexing on series/frames, not to indexes themselvesMultiIndex

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions