[英]writing to csv, Python, different data types
I'm new to Python and would like to write data of different types to the columns of a csv file. 我是Python的新手,想将不同类型的数据写入csv文件的列。
I have two lists and one ndarray. 我有两个列表和一个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)
You could convert it all over to a numpy array and save it with savetxt
, but why not just do it directly? 你可以把它全部转换成一个numpy数组并用savetxt
保存它,但为什么不直接做呢?
You can iterate through the array just like you'd iterate through a list. 您可以像遍历列表一样遍历数组。 Just zip
them together. 只是zip
在一起。
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. 或者,如果您愿意,可以使用csv
模块。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.