假设我从计算中得到一个numpy矩阵。这是我的numpy矩阵“result1”:
result1=
[[ 1. 0. 0. 0.00375 -0.01072 -0. -1000. ]
[ 2. 3. 4. 0. -0.004 750. 0. ]
[ 3. 3. 0. 0. 0. -750. 1000. ]]
现在我想把这个矩阵写在一个名为'result.txt'的文本文件中。为此,我编写了以下代码:
np.savetxt('result.txt', result1, fmt='%.2e')
但它把矩阵的所有元素都放在一行。
1.00e+00 0.00e+00 0.00e+00 3.75e-03 -1.07e-02 -1.14e-13 -1.00e+032.00e+00 3.00e+00 4.00e+00 0.00e+00 -4.00e-03 7.50e+02 0.00e+003.00e+00 3.00e+00 0.00e+00 0.00e+00 0.00e+00 -7.50e+02 1.00e+03
我想以适当的矩阵格式在文本文件中写入矩阵。我该怎么做?我使用关键字newline='\n'或newline='',但结果相同。
提前谢谢。。。
=
这个编辑部分是给@Warren的
试试这个:
>>> import numpy as np
>>> mat=np.matrix([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
>>> mat
matrix([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> np.savetxt('text.txt',mat,fmt='%.2f')
在我的text.txt文件中,我得到:
1.00 2.00 3.004.00 5.00 6.007.00 8.00 9.00
如果只想使用
numpy
:然后
熊猫有^{} 方法:
它具有相同的输出:
要重新创建形状,需要在保存文件时保存形状。
尝试:
您可以将形状以某种形式保存在order文件中,以重新创建相同的形状。但是,请确保不要忘记文件开头的数据,因为与np.loadtxt不同,以
#
开头的行仍然被视为数据。就像Francesco Nazzaro的回答,但是要确保文件能够成功打开,请尝试:
相关问题 更多 >
编程相关推荐