I want to write data that I have to create a histogram into a csv file. I have my 'bins' list and I have my 'frequencies' list. Can someone give me some help to write them into a csv in their respective columns?
ie bins in the first column and frequency in the second column
This example uses izip
(instead of zip
) to avoid creating a new list and having to keep it in the memory. It also makes use of Python's built in csv module, which ensures proper escaping. As an added bonus it also avoids using any loops, so the code is short and concise.
import csv
from itertools import izip
with open('some.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerows(izip(bins, frequencies))
In Python 3, you don't need izip
anymore—the builtin zip
now does what izip
used to do. You also don't need to open the file in binary mode:
import csv
with open('some.csv', 'w') as f:
writer = csv.writer(f)
writer.writerows(zip(bins, frequencies))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With