将矩阵保存到Python中的文件中

问题描述 投票:0回答:1

我想将矩阵保存到Python中的文件中,并在输出文件中保留矩阵结构。

例如:

#Program to test the output of an array to a file 
import numpy as np
from mpmath import mp,mpf,matrix
# Set precision to 32 digits
mp.dps=32

#Define array
out=matrix(3,2)
for j in range(3):
    out[j,0]=mpf(j+1)*mpf('1.73')
    out[j,1]=mp.sin(mpf(j))

filout="test_out.txt"
np.savetxt(filout,out,fmt='%32s')

我得到的是:

                               1.73
                                0.0
                               3.46
  0.8414709848078965066525023216303
                               5.19
 0.90929742682568169539601986591174

但是,我想要的是:

                       1.73                                0.0
                       3.46  0.8414709848078965066525023216303
                       5.19 0.90929742682568169539601986591174

有谁知道如何做到这一点(我尝试了各种方法来保留矩阵结构但无济于事)?

python matrix save structure
1个回答
0
投票
import numpy as np
from mpmath import mp, matrix

# Set precision to 32 digits
mp.dps = 32

# Create a 3x2 matrix and populate with values
out = matrix(3, 2)
for j in range(3):
    out[j, 0] = (j + 1) * 1.73
    out[j, 1] = mp.sin(j)

np.savetxt("test_out.txt", out, fmt='%32.30f', delimiter=' ')

这里的关键是保存时设置正确的格式

(fmt='%32.30f')
,并使用空格分隔列
(delimiter=' ')

© www.soinside.com 2019 - 2024. All rights reserved.