【问题标题】:How to save your results from screen output to csv file in 2 columns on python?如何将屏幕输出的结果保存到 python 上 2 列中的 csv 文件?
【发布时间】:2019-03-11 16:24:27
【问题描述】:
import pandas as pd
import numpy as np
import csv

with open('predictions.csv', 'r') as f:
    csvreader = csv.reader(f)
    next(csvreader)
    for r in csvreader:
        df = r[:-1]
        a = float(str(df[:][0]))
        b = float(str(df[:][1]))
        if a > b :
            print(1, 0)
        else:
            print(0, 1)

0 1
0 1
0 1
0 1
0 1
0 1

我从 predictions.csv 文件中打印了我的结果,并尝试将显示为 0 和 1 的结果保存到 CSV 文件的 2 列中。那么如何将结果保存到显示的 2 列 CSV 文件中?

【问题讨论】:

标签: python python-3.x csv


【解决方案1】:

您不必保存打印的输出 - 您可以在循环打印时直接将数据保存到 CSV,如下所示:

with open('new_file.csv', mode='a', newline='') as file:
    csv_writer = csv.writer(file)
    if a > b :
        print(1, 0)
        csv_writer.writerow(['1', '0'])
    else:
        print(0, 1)
        csv_writer.writerow(['0', '1'])

【讨论】:

    【解决方案2】:
    %%capture cap --no-stderr
    with open('predictions.csv', 'r') as f:
        csvreader = csv.reader(f)
        next(csvreader)
        for r in csvreader:
            df = r[:-1]
            a = float(str(df[:][0]))
            b = float(str(df[:][1]))
            with open('output.csv', 'w') as writer:
                if a > b :
                    print(1,',',0)
                else:
                    print(0,',',1)
                writer.write(cap.stdout)
    

    【讨论】:

      猜你喜欢
      • 2014-09-21
      • 2015-03-29
      • 1970-01-01
      • 1970-01-01
      • 2012-12-21
      • 2011-03-21
      • 1970-01-01
      • 2022-01-13
      相关资源
      最近更新 更多