从Array写入CSV文件

时间:2022-08-11 21:29:22

I am trying to use writer.writerow to present data from an array to an csv file. I have an array sum_balance and apparently I need to convert it into a numpy array before I can use the writer.writerow function. Heres my code:

我试图使用writer.writerow将数据从数组提供给csv文件。我有一个数组sum_balance,显然我需要将它转换为numpy数组才能使用writer.writerow函数。继承我的代码:

numpy_arr = array(sum_balance)
with open("output.csv", "wb") as csv_file:
    writer = csv.writer(csv_file, delimiter=',')
    for element in numpy_arr:
        writer.writerow(element)
csv_file.close()

But I still get the error: writer.writerow(element)_csv.Error: iterable expected, not numpy.float64

但我仍然得到错误:writer.writerow(element)_csv.Error:迭代预期,而不是numpy.float64

1 个解决方案

#1


2  

The numpy iterator seems to be iterating over elements, not rows, which is why you're getting an error. However, there's an even simpler way to achieve what you're trying to do: numpy has a routine savetxt that can write an ndarray to a csv file:

numpy迭代器似乎是迭代元素而不是行,这就是你得到错误的原因。但是,有一种更简单的方法来实现你想要做的事情:numpy有一个例程savetxt,可以将ndarray写入csv文件:

output_array = np.array(my_data)
np.savetxt("my_output_file.csv", output_array, delimiter=",")

#1


2  

The numpy iterator seems to be iterating over elements, not rows, which is why you're getting an error. However, there's an even simpler way to achieve what you're trying to do: numpy has a routine savetxt that can write an ndarray to a csv file:

numpy迭代器似乎是迭代元素而不是行,这就是你得到错误的原因。但是,有一种更简单的方法来实现你想要做的事情:numpy有一个例程savetxt,可以将ndarray写入csv文件:

output_array = np.array(my_data)
np.savetxt("my_output_file.csv", output_array, delimiter=",")