Search code examples
pythonpandasdataframetypeerrorrenaming

TypeError: cannot do label indexing on <class 'pandas.indexes.base.Index'> with these indexers


I face an error after renaming a pandas dataframe column:

B=pd.DataFrame(data=[[1,1,1],[2,2,2]],columns={'A','B','C'})
print(B.loc[0,'B'])
B = B.rename(index=str,columns={'B':'B_B'})
print(B.loc[0,'B_B'])

This code leads to folowing output:

> 1

>Traceback (most recent call last):
  File "C:\Users\FreieL01\AppData\Local\Continuum\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-29-6df9197203b9>", line 4, in <module>
    print(B.loc[0,'B_B'])
  File "C:\Users\FreieL01\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 1310, in __getitem__
    return self._getitem_tuple(key)
  File "C:\Users\FreieL01\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 796, in _getitem_tuple
    return self._getitem_lowerdim(tup)
  File "C:\Users\FreieL01\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 922, in _getitem_lowerdim
    section = self._getitem_axis(key, axis=i)
  File "C:\Users\FreieL01\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 1482, in _getitem_axis
    self._has_valid_type(key, axis)
  File "C:\Users\FreieL01\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 1409, in _has_valid_type
    key = self._convert_scalar_indexer(key, axis)
  File "C:\Users\FreieL01\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 196, in _convert_scalar_indexer
    return ax._convert_scalar_indexer(key, kind=self.name)
  File "C:\Users\FreieL01\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\indexes\base.py", line 1171, in _convert_scalar_indexer
    return self._invalid_indexer('label', key)
  File "C:\Users\FreieL01\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\indexes\base.py", line 1284, in _invalid_indexer
    kind=type(key)))
TypeError: cannot do label indexing on <class 'pandas.indexes.base.Index'> with these indexers [0] of <class 'int'>}

It seems that the renaming changes the type of my datafframe object ...


Solution

  • Running df.rename(index=str, ...) causes your dataframe indices to be typecast to string types, so they'd be strings. You can confirm this by printing them out.

    In [19]: B.index
    Out[19]: Index(['0', '1'], dtype='object')
    

    Consequently, this works:

    In [18]: print(B.loc['0', 'B_B'])
    1
    

    If you don't want this, just don't pass an index attribute when renaming your B column, like this:

    B = B.rename(columns={'B':'B_B'})