如何在python中的文本文件中写入稀疏矩阵?
How to write a sparse matrix in a text file in python?
我有一个稀疏矩阵 A_n。 A_n 的类型是 "scipy.sparse.csc.csc_matrix"。
例如,A_n是:
(16, 0) 1.0
(71, 1) 1.0
(74, 3) 1.0
(72, 12) 1.0
. .
. .
(32, 17) 1.0
(64, 17) 1.0
(53, 19) 1.0
(73, 20) 1.0
(52, 21) 1.0
(52, 22) 1.0
(44, 26) 1.0
(53, 26) 1.0
(87, 26) 1.0
我想将 A_n 的所有内容写入 python 的文本文件中,如下所示:
16 0 1.0
71 1 1.0
74 3 1.0
.
.
或
(16, 0) 1.0
(71, 1) 1.0
(74, 3) 1.0
.
.
如能指导我将不胜感激
您可以使用 str(sparse_matrix)
将备用矩阵对象简单地转换为字符串,然后在将 maxprint 属性更改为 spare_matrix.shape[0].
后将其写入文件
sparse_matrix.maxprint = sparse_matrix.shape[0]
with open("spare_matrix.txt","w") as file:
file.write(str(sparse_matrix))
file.close()
此处 'i' 将遍历矩阵的行 A_n 并且 'j' 将仅遍历 A_ni-th 行的 non-zero 列 A_n.
file = open('sparse_matrix.txt','w')
for i in range(A_n.shape[0]):
for j in A_n[i].nonzero()[1]:
file.write(str(i)+' ' +str(j)+' '+str(A_n[i,j])+'\n')
file.close()
我有一个稀疏矩阵 A_n。 A_n 的类型是 "scipy.sparse.csc.csc_matrix"。
例如,A_n是:
(16, 0) 1.0
(71, 1) 1.0
(74, 3) 1.0
(72, 12) 1.0
. .
. .
(32, 17) 1.0
(64, 17) 1.0
(53, 19) 1.0
(73, 20) 1.0
(52, 21) 1.0
(52, 22) 1.0
(44, 26) 1.0
(53, 26) 1.0
(87, 26) 1.0
我想将 A_n 的所有内容写入 python 的文本文件中,如下所示:
16 0 1.0
71 1 1.0
74 3 1.0
.
.
或
(16, 0) 1.0
(71, 1) 1.0
(74, 3) 1.0
.
.
如能指导我将不胜感激
您可以使用 str(sparse_matrix)
将备用矩阵对象简单地转换为字符串,然后在将 maxprint 属性更改为 spare_matrix.shape[0].
sparse_matrix.maxprint = sparse_matrix.shape[0]
with open("spare_matrix.txt","w") as file:
file.write(str(sparse_matrix))
file.close()
此处 'i' 将遍历矩阵的行 A_n 并且 'j' 将仅遍历 A_ni-th 行的 non-zero 列 A_n.
file = open('sparse_matrix.txt','w')
for i in range(A_n.shape[0]):
for j in A_n[i].nonzero()[1]:
file.write(str(i)+' ' +str(j)+' '+str(A_n[i,j])+'\n')
file.close()