csv 根据标签将图像数据集分离到不同的文件夹中

huus2vyu  于 2023-05-04  发布在  其他
关注(0)|答案(1)|浏览(195)

我有一个标签。csv文件与3类和我的数据集是一个完整的文件,这是不分开的,我想我的数据集分为3个不同的文件夹,每个文件夹应该是每个类,请帮助我的代码,我卡住了

# Create an empty dictionary to store the separate classes
classes = {}

# Iterate over each row in the dataframe and add it to the appropriate class based on its label
for index, row in df.iterrows():
    label = row[]
    if label not in classes:
        classes[label] = pd.DataFrame()
    classes[label] = classes[label].append(row)

# Print out the separate classes
for label, data in classes.items():
    print(f"Class {label}:")
    print(data)

我的.csv文件有两列:第一列具有图像名称,而第二列具有表示类别1的类别标签,类别1被标记为1,类别2被标记为2,类别3被标记为3。请帮帮我。

z9smfwbn

z9smfwbn1#

您可以用途:

import os
import shutil

# create class directories
for label in label_df['class'].unique().astype(str):
    if not os.path.exists(label):
        os.mkdir(label)

# set the destination target
label_df['path'] = label_df['class'].astype(str) + os.path.sep + label_df['image']

# copy or move files
for _, row in label_df.iterrows():
    # shutil.copy(row['image'], row['path'])
    shutil.move(row['image'], row['path'])

输入 Dataframe :

data = {"image": ["image1.png", "image2.png", "image3.png", "image4.png"],
        "class": [1, 2, 3, 1],     }
label_df = pd.DataFrame(data)

相关问题