将 numpy 数组的每一行保存到文件的单独行而不是将其分开

Save each row of a numpy array to a separate row of a file instead of separating it

我有以下 numpy 数组:

matrix = numpy.zeros([30, 30], dtype = numpy.int32)

我稍后更改此数组的值并将其保存到文件中,如下所示:

conf_mat = open("conf_mat.txt", "w")
conf_mat.write(str(matrix))

但是文件中的结果是这样的

[[    0     0     0     8   161     0    18     0     0     0     0     0
     13     0     1     0   140     2     0     0     8     0    14     0
      0     0     0     0     0     0]
 [    0     0     0    41    31     0    39     0     0     0     0     0
     44     0     0     0    21    39     0     0    39     0   105     0
      0     0     0     0     0     0]
 [    0     0     0    71   162     0   155     0     0     1     0     0
      6     0     0     0   350   110     0     0     8     0    21     0
      0     0     0     0     0     0]
 ...

如您所见,矩阵的 1 行在文档中分为 3 行。 如何在文件的一行中写入整行矩阵?

PS:我不知道这是否有区别,但我正在通过 ssh 连接使用远程 linux 服务器。

要保存 numpy 数组,请使用 numpy.save(npy 格式)或 numpy.savetxt(CSV/plaintext),并加载 numpy.loadnumpy.loadtxt,请参阅https://numpy.org/devdocs/user/how-to-io.html and https://numpy.org/doc/stable/reference/routines.io.html

但是,

numpy.savetxt 只能存储一维或二维数组。要将数据存储为整数值而不是指数表示法,请使用 fmt='%d' 作为 numpy.savetxt 的关键字参数,例如numpy.savetxt("foo", matrix, fmt='%d')。有关格式标志的更多信息,请查看 https://numpy.org/doc/stable/reference/generated/numpy.savetxt.html

稍微跑题了:你也可以使用pandas来保存numpy矩阵:

>>> import pandas as pd
>>> import numpy as np
>>> pd.DataFrame(np.zeros([4, 2])).to_csv()
',0,1\n0,0.0,0.0\n1,0.0,0.0\n2,0.0,0.0\n3,0.0,0.0\n'
>>> 

(如果您使用 to_csv(<filename>) 它将改为写入磁盘)