在 Python 中将 NumPy 数组内容写入文件 [英] Write NumPy array contents to a file in Python
本文介绍了在 Python 中将 NumPy 数组内容写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个要写入文件的 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
它将您的一维数组转换为一个元组并将其传递给格式语句,并为数组中的每个项目指定格式规范.
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.
这篇关于在 Python 中将 NumPy 数组内容写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文