Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write data from two lists into columns in a csv?

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

like image 459
Nathan Thomas Avatar asked Oct 10 '13 17:10

Nathan Thomas


1 Answers

The original Python 2 answer

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))

The code adapted for Python 3

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))
like image 194
Ludwik Trammer Avatar answered Oct 12 '22 22:10

Ludwik Trammer