Writing to csv, Python, different data types
I am new to Python and would like to write data of different types to columns of a csv file.
I have two lists and one ndarray. I would like to have them as three columns with the first row being the variable names.
Is there a way to do this in one line or does it need to be converted to arrays first?
len(all_docs.data)
Out[34]: 19916
In [35]: type(all_docs.data)
Out[35]: list
In [36]: len(all_docs.target)
Out[36]: 19916
In [37]: type(all_docs.target)
Out[37]: numpy.ndarray
In [38]: id = range(len(all_docs.target)
You can convert the whole thing to a numpy array and store it with savetxt
, but why not just do it directly?
You can iterate through an array in the same way as in a list. Just zip
them together.
with open('output.csv', 'w') as outfile:
outfile.write('Col1name, Col2name, Col3name\n')
for row in zip(col1, col2, col3):
outfile.write('{}, {}, {}\n'.format(a,b,c))
Or, if you prefer, you can use a module csv
. If you need to worry about speeding up ,
this is very useful.
import csv
with open('output.csv', 'w') as outfile:
writer = csv.writer(outfile)
outfile.write('Col1name, Col2name, Col3name\n')
for row in zip(col1, col2, col3):
writer.writerow(row)
source to share