如何将分类器预测结果写入CSV文件的指定label列
如何将分类器预测结果写入CSV的label列?
你说的这种场景太常见了,我之前处理分类任务时也经常碰到,给你两种实用的方法,看你习惯哪种工具:
方法一:用Pandas(推荐,操作最简便)
Pandas处理表格数据简直是利器,几步就能搞定:
- 先导入pandas库(如果没装的话先执行
pip install pandas) - 读取你的CSV文件
- 把预测结果直接赋值给
label列 - 保存回原文件(或者新文件,避免覆盖出错)
代码示例:
import pandas as pd import numpy as np # 假设你的预测结果是numpy数组 predictions = np.array([0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1., 0., 0., 0.]) # 读取CSV文件 df = pd.read_csv("your_file.csv") # 把预测结果赋值给label列 df["label"] = predictions # 保存回CSV,index=False是为了避免多出一列索引 df.to_csv("your_file.csv", index=False)
注意:要确保你的预测结果长度和CSV里的行数完全一致,不然会报长度不匹配的错误哦!
方法二:纯Python内置csv模块(不用装第三方库)
如果不想依赖Pandas,用Python自带的csv模块也能实现:
import csv predictions = [0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1., 0., 0., 0.] input_file = "your_file.csv" output_file = "your_file_with_label.csv" with open(input_file, 'r', newline='') as infile, open(output_file, 'w', newline='') as outfile: reader = csv.DictReader(infile) # 保留原表头 fieldnames = reader.fieldnames writer = csv.DictWriter(outfile, fieldnames=fieldnames) writer.writeheader() # 遍历每一行,对应填入预测结果 for idx, row in enumerate(reader): row["label"] = str(predictions[idx]) # 转成字符串避免格式问题 writer.writerow(row)
这个方法是逐行处理,适合数据量不大的情况,好处是不用额外安装库。
内容的提问来源于stack exchange,提问作者曾逸飞
相关产品推荐
相关产品推荐

