Home > Back-end >  iloc error: IndexError: single positional indexer is out-of-bounds
iloc error: IndexError: single positional indexer is out-of-bounds

Time:06-03

I'm trying to write code which loops through a dir using os.dir and which adds all the file names in the pd.dataframe first column which is named filename. however , i get the following error.

error: 
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
/tmp/ipykernel_18849/3125259842.py in <module>
     11     for k,j in enumerate(os.listdir('/home/ubuntu/imageTrain_dobby/SKJEWELLERY/BC4U/google_version/v1.1/lingyau_lee/output/test' '/' i)):
     12         #print(k)
---> 13         dfTest.iloc[k]['filename']= j
     14 
     15 

~/anaconda3/envs/myenv/lib/python3.7/site-packages/pandas/core/indexing.py in __getitem__(self, key)
    877 
    878             maybe_callable = com.apply_if_callable(key, self.obj)
--> 879             return self._getitem_axis(maybe_callable, axis=axis)
    880 
    881     def _is_scalar_access(self, key: Tuple):

~/anaconda3/envs/myenv/lib/python3.7/site-packages/pandas/core/indexing.py in _getitem_axis(self, key, axis)
   1494 
   1495             # validate the location
-> 1496             self._validate_integer(key, axis)
   1497 
   1498             return self.obj._ixs(key, axis=axis)

~/anaconda3/envs/myenv/lib/python3.7/site-packages/pandas/core/indexing.py in _validate_integer(self, key, axis)
   1435         len_axis = len(self.obj._get_axis(axis))
   1436         if key >= len_axis or key < -len_axis:
-> 1437             raise IndexError("single positional indexer is out-of-bounds")
   1438 
   1439     # -------------------------------------------------------------------

IndexError: single positional indexer is out-of-bounds
import os
import pandas as pd
    
dfTest = pd.DataFrame(columns = ['filename', 'class'])
TrainList, TestList =[],[]
TrainDic, TestDic = {},{}
    
     
for i in os.listdir('/home/ubuntu/imageTrain_dobby/SKJEWELLERY/BC4U/google_version/v1.1/lingyau_lee/output/test'):
    for k,j in enumerate(os.listdir('/home/ubuntu/imageTrain_dobby/SKJEWELLERY/BC4U/google_version/v1.1/lingyau_lee/output/test' '/' i)): 
            
        dfTest.iloc[k]['filename']= j

CodePudding user response:

Since your dataframe is empty and you want to add row to it, you can use loc. You cann't use iloc since i is out of the dataframe length.

for i in os.listdir('/home/ubuntu/imageTrain_dobby/SKJEWELLERY/BC4U/google_version/v1.1/lingyau_lee/output/test'):
    for k,j in enumerate(os.listdir('/home/ubuntu/imageTrain_dobby/SKJEWELLERY/BC4U/google_version/v1.1/lingyau_lee/output/test' '/' i)): 
        dfTest.loc[k, 'filename'] = j
  • Related