如何将预测结果循环写入一个csv文件中

如何将预测结果循环写入一个csv文件中,将每一个Y[j]写入到同一个csv文件中

Y= []
tmp_x1 = X_train.copy()
tmp_x2 = X_test.copy()
for j in range(100):  
    for i in range(6585): 
        tmp_x1['X1'][i] = X1[j]
        tmp_Y1 = list(M.predict(tmp_x1))
    for i in range(1966): 
        tmp_x2['X1'][i] = X1[j]
        tmp_Y2 = list(M.predict(tmp_x2))
    Y.append(tmp_Y1 + tmp_Y2)

可以尝试用该链接中的方式,去实现:https://blog.csdn.net/qq_41915623/article/details/125834267

    os.makedirs(os.path.join('..', 'data'), exist_ok=True)  # 创建数据文件夹
    data_file = os.path.join('..', 'data', 'loss.csv')
    with open(data_file, 'w', encoding='utf-8', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(['epoch', 'batch_index', 'loss'])


https://www.cnblogs.com/yuanyuzhou/p/15885841.html

先写入头部,然后按行写入字典
像下面这样:

    # newline='' 去掉存进csv文件内容之间的空行
    with open("贴吧.csv", "w", encoding="utf-8",newline='') as csvfile:
        fieldnames = ["title", "link"]
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        for el in el_list:
            temp = {}
            temp['title'] = el.xpath("./text()")[0]
            #给链接拼接域名
            temp['link'] = 'https://tieba.baidu.com'+el.xpath("./@href")[0]
            print(temp)
            writer.writerow(temp)
    print("爬取完毕!")

有帮助的话采纳一下哦!

参考下这个链接
https://www.cnblogs.com/yuanyuzhou/p/15885841.html