如何将数据插入到csv文件的所需列中?

pvabu6sv  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(110)

下面显示的代码创建一个带有我想要的列标题的.csv文件,从文件夹中读取日期,然后在这些文件上运行机器学习模型。这样做的目的是让我看到每天发生多少次检测。我的问题是,我不能得到第二次插入的数据进入第二列下的标题。不管我怎么努力,它似乎总是粘贴在第一列下的其他数据。
我尝试了columns([''])命令,但得到一个KeyError。

# Creates .csv file.
    with open(fr"/home/lm/anaconda3/envs/yolov8_rotiferdetect/CSV_files/exp_{lifespan_number}.csv", 'w') as csvfile:
        filewriter = csv.writer(csvfile, delimiter=',',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
        filewriter.writerow(['Date','Rotifer Count'])
# Load Original Images
    org_images_path = fr"/wormbot/{lifespan_number}"
    # Establish Prefix for Files
    file_prefix = "frame"
    # Sort Images
    img_list = sorted(os.listdir(org_images_path))
    # Filter Sorted Images by Prefix
    img_list = [img_name for img_name in img_list if img_name if  img_name.startswith(file_prefix)]
    # Loop through every other file in the folder
    for index, img_name in enumerate(img_list):
        if index % 2 ==0:
            # Open Image
            image_path = os.path.join(org_images_path, img_name)
            # Get Date and Time
            get_image = os.path.getmtime(image_path)
            # Filter to Just Date Number
            date_number = datetime.datetime.fromtimestamp(get_image).day
            # Output Date Number
            number_day = (date_number)
            # Create Data Frame
            df = pd.DataFrame([number_day])
            # Input Into .csv File
            df.to_csv(fr"/home/lm/anaconda3/envs/yolov8_rotiferdetect/CSV_files/exp_{lifespan_number}.csv", index=False, header=False, mode='a')
# Loop through all files in the folder
for image in sorted(os.listdir(output_crop)):
    if image.endswith('.jpg'):
        image_path = os.path.join(output_crop, image)
        img = Image.open(image_path)
        # Run Model with however much confidence on image.
        results = model(img, conf=.19,verbose=False, max_det=5)
        counts = {}
        for result in results:
            boxes = result.boxes.cpu().numpy()
            for box in boxes:
                cls = int(box.cls[0])
                if not cls in counts.keys():
                    counts[cls] = 1
                else:
                    counts[cls] += 1
            try:
                alive = (str(counts[key]))
            except KeyError:
                alive = ('0')
            # creates data frame of current frame and count.
            df = pd.DataFrame([alive])
            # Add data frame to next open row in csv file, change accordingly.
            df.to_csv(fr"/home/lm/anaconda3/envs/yolov8_rotiferdetect/CSV_files/exp_{lifespan_number}.csv", index=False, header=False, mode='a')
            # Adds 1 to current_frame to count.
            current_frame +=1
            # Close current image
            img.close()
uz75evzq

uz75evzq1#

我相信你可以通过创建两个系列来简化这一点,然后将它们合并到你的dataframe中并将它们写为CSV。
类似下面的东西应该可以工作,但可能错过了你想要完成的事情的本质:

# Load Original Images
# Dates list
dates = []
org_images_path = fr"/wormbot/{lifespan_number}"
# Establish Prefix for Files
file_prefix = "frame"
# Sort Images
img_list = sorted(os.listdir(org_images_path))
# Filter Sorted Images by Prefix
img_list = [img_name for img_name in img_list if img_name if  img_name.startswith(file_prefix)]
# Loop through every other file in the folder
for index, img_name in enumerate(img_list):
    if index % 2 ==0:
        # Open Image
        image_path = os.path.join(org_images_path, img_name)
        # Get Date and Time
        get_image = os.path.getmtime(image_path)
        # Filter to Just Date Number
        date_number = datetime.datetime.fromtimestamp(get_image).day
        # Output Date Number
        number_day = (date_number)
        # Append number_day to dates list
        dates.append(number_day)

字符串
然后我们将处理您的计数:

# Loop through all files in the folder
rotifier_counts = []
for image in sorted(os.listdir(output_crop)):
    if image.endswith('.jpg'):
        image_path = os.path.join(output_crop, image)
        img = Image.open(image_path)
        # Run Model with however much confidence on image.
        results = model(img, conf=.19,verbose=False, max_det=5)
        counts = {}
        for result in results:
            boxes = result.boxes.cpu().numpy()
            for box in boxes:
                cls = int(box.cls[0])
                if not cls in counts.keys():
                    counts[cls] = 1
                else:
                    counts[cls] += 1
            try:
                alive = (str(counts[key]))
                rotifier_counts.append(alive)
            except KeyError:
                alive = ('0')
                rotifier_counts.append(alive)
        # Adds 1 to current_frame to count.
        current_frame +=1
        # Close current image
        img.close()


最后,我们可以从我们的日期和rotifier_counts列表中创建一个系列,并建立数据框并写入CSV。

# Create series of dates to create data frame
s1 = pd.Series(dates, name="Dates")
s2 = pd.Series(rotifier_counts, name="Rotifer Counts")
# Create dataframe with column names
df = pd.concat([s1, s2], axis=1)
# Write df out to CSV
df.to_csv(fr"/home/lm/anaconda3/envs/yolov8_rotiferdetect/CSV_files/exp_{lifespan_number}.csv", index=False, header=True)

相关问题