Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing to csv, Python, different data types

Tags:

python

csv

I'm new to Python and would like to write data of different types to the columns of a csv file.

I have two lists and one ndarray. I would like to have these as the three columns with the first row being the variable names.

Is there are a way to do this in one line or does one have to first convert to arrays?

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)

1 Answers

You could convert it all over to a numpy array and save it with savetxt, but why not just do it directly?

You can iterate through the array just like you'd iterate through 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'd prefer, you can use the csv module. If you have to worry about escaping ,'s, it's quite 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)
like image 199
Joe Kington Avatar answered Feb 22 '26 09:02

Joe Kington



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!