anderish
anderish

Reputation: 1759

Writing to a CSV File from Array

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:

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

Upvotes: 0

Views: 8093

Answers (1)

Ben G.
Ben G.

Reputation: 306

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:

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

Upvotes: 2

Related Questions