[英]Writing multiple seperate numpy arrays to a single comma delimited text file
I would like to take multiple numpy arrays and write them to a text file that is comma delimited. 我想采取多个numpy数组并将它们写入以逗号分隔的文本文件。 Here is the example of my original data and the final data that I am trying to produce:
以下是我原始数据的示例以及我尝试生成的最终数据:
array([[1., 3., 0., 1.],
[2., 5., 3., 1.]].....
and so forth. 等等。 For multiple different arrays of four-column lengths.
适用于四列长度的多个不同阵列。 I can get an out put txt file using write() but I can't get the data into the format shown below:
我可以使用write()获取一个输出txt文件,但我无法将数据转换为如下所示的格式:
1., 3., 0., 1.
2., 5., 3., 1.
Also, I need to have the 0th column integers and the 1st through 3rd be floating point. 另外,我需要第0列整数,第1到第3列是浮点数。
Cheers. 干杯。
How about this? 这个怎么样?
data = array([[1., 3., 0., 1.],
[2., 5., 3., 1.]].....
with open('output.csv', 'w') as f:
for x in data:
f.write('%d,%f,%f,%f\n' % tuple(x))
This outputs 这输出
1,3.000000,0.000000,1.000000
2,5.000000,3.000000,1.000000
You can adjust the precision of the floating point output by changing %f
to %.2f
if you want two decimal places, for instance. 例如,如果您想要两个小数位,可以通过将
%f
更改为%.2f
来调整浮点输出的精度。
I would recommend using pandas for this: 我建议使用pandas:
import numpy
import pandas
data = numpy.array([[1., 3., 0., 1.],
[2., 5., 3., 1.]])
data = pandas.DataFrame(data,columns=['a','b','c','d'])
data['a'] = data['a'].astype(int)
data.to_csv('outfile.csv')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.