将NumPy数组内容写入Python中的文件 [英] Write NumPy array contents to a file in Python
本文介绍了将NumPy数组内容写入Python中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个要写入文件的NumPy数组
I have a NumPy array that I'm trying to write to a file
outfile.write(str(myarray))
但是,我得到的东西看起来像这样:
But, I get something that looks like this:
[ 4.275000000e01 2.345000000e01 3.2135000000e-02 ]
我的要求是:
- 将数据写入数组(而不是数组大括号[])
- 以一定数量的尾随小数位(例如6)写入数据
通常,#2 并不难,但是我不确定如何与#1 结合使用.
Normally, #2 would not be that hard, but I'm not sure how to handle it in conjunction with #1.
我也想将数组写成一行.像这样:
I also want to write the array on one line as a row. like this:
4.27500000 2.34500000 0.03213500000
推荐答案
savetxt
等效于:
In [631]: x=np.array([4.275000000e01, 2.345000000e01, 3.2135000000e-02])
In [632]: '%10.6f %10.6f %10.6f'%tuple(x)
Out[632]: ' 42.750000 23.450000 0.032135'
In [642]: outfile.write((' '.join(['%10.6f ']*x.size)+'\n\n') % tuple(x))
42.750000 23.450000 0.032135
它将一维数组变成一个元组,并将其传递给format语句,并为数组中的每个项目指定格式.
It turns your one-dimensional array into a tuple and passes it off to the format statement, with a format specification for each item in the array.
这篇关于将NumPy数组内容写入Python中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文