Skip to content

KeyError when retrieving columns with lists of incomplete tuples from MultiIndex #12369

Closed
@toobaz

Description

@toobaz

Sorry in advance if this was already reported - I searched a bit but didn't know exactly what to search.

In [2]: df = pd.DataFrame(0, index=range(1), columns=pd.MultiIndex.from_product([['a', 'b'], ['c']]))

In [3]: cols = [('a',), ('b',)]

In [4]: df[cols[0]]
Out[4]: 
   c
0  0

In [5]: df[cols[1]]
Out[5]: 
   c
0  0

In [6]: df[cols]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-6-957cf8a677a9> in <module>()
----> 1 df[cols]

/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)
   2019             return self.take(indexer, axis=0, convert=False)
   2020         else:
-> 2021             indexer = self.ix._convert_to_indexer(key, axis=1)
   2022             return self.take(indexer, axis=1, convert=True)
   2023 

/home/pietro/nobackup/repo/pandas/pandas/core/indexing.pyc in _convert_to_indexer(self, obj, axis, is_setter)
   1203                 mask = check == -1
   1204                 if mask.any():
-> 1205                     raise KeyError('%s not in index' % objarr[mask])
   1206 
   1207                 return _values_from_object(indexer)

KeyError: "[('a',) ('b',)] not in index"

Notice that df[[c[0] for c in cols]] works just fine... but still we probably want to consider as valid a list of valid keys.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions