[英]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 服务器。
To save numpy arrays, use numpy.save
(npy format) or numpy.savetxt
(CSV/plaintext), and to load numpy.load
or numpy.loadtxt
, see https://numpy.org/devdocs/user/how-to -io.html和https://numpy.org/doc/stable/reference/routines.io.76235FDC70D8EFC5
不过, numpy.savetxt
只能存储一维或二维 arrays。 And to store the datas as integer values instead of exponential notation, use fmt='%d'
as a keyword argument to numpy.savetxt
, eg 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>)
它将被写入磁盘)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.