如何使用 panda 加载具有文件夹名称和图像名称但不包含 python 中的 id 的数据集文件?

How do I load a dataset file that has folder name and image name but does not contain an id in python using panda?

我正在使用的文件是一个文本文件,并且是这种格式(如下)。 第一列代表文件夹名称。 这是一个示例。

0010[=12=]10_01_05_03_115.jpg
0010[=12=]10_01_05_03_121.jpg
0010[=12=]10_01_05_03_125.jpg

如何将它加载到我的程序中,因为出现此错误:

img=image.load_img('TrainImages/' +TrainImages['id'][i].astype('str')+'.png', target_size=(2, 8, 28, 1),grayscale=False) File "C:\Anaconda\lib\site-packages\pandas\core\frame.py", line 2927, in getitem indexer = self.columns.get_loc(key) File "C:\Anaconda\lib\site-packages\pandas\core\indexes\base.py", line 2659, in get_loc return self._engine.get_loc(self._maybe_cast_indexer(key)) File "pandas/_libs/index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc File "pandas/_libs/index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc File "pandas/_libs/hashtable_class_helper.pxi", line 1601, in pandas._libs.hashtable.PyObjectHashTable.get_item File "pandas/_libs/hashtable_class_helper.pxi", line 1608, in pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: 'id'

我实际上是在尝试通过读取文件并在执行其余操作之前对其进行一些预处理来创建训练数据集。

这是我试过的代码,我不确定它是否正确:

TrainImages=pd.read_csv('client_train_raw.txt')
train_image =[]
for i in tqdm(range(TrainImages.shape[0])):
    img=image.load_img('TrainImages/' +TrainImages['id'] 
      [i].astype('str')+'.png', target_size=(2, 8, 28, 1),grayscale=False)
    img = image.img_to_array(img)

你还没有告诉你的数据框 'id' 是什么意思。看起来你的数据文件只有一列,文件路径由 '\' 分隔。您应该可以通过以下方式解决此问题:

train_images = pd.read_csv('client_train_raw.txt', header=False, names=['id'])

这会将数据框中的单列标记为 'id',并且您将不再收到 that 错误。我认为您处理文件路径的方式仍然存在一些问题,而且我不确定 TrainImages['id'][i].astype('str') 中的 [i] 是否按照您的想法行事。

此外,您可能不需要使用 Pandas 进行阅读。由于文件中的每一行都是图像的路径,因此您可以使用:

with open('client_train_raw.txt', 'r') as a_file:
    for idx, line in enumerate(a_file):
        # Each line will be a path to a data file.
        img = image.load_img('TrainImages/' + line + idx + '.png', ...)
        img = image.img_to_array(img)

之类的,但我不确定这里的 idx 应该做什么。