簡體   English   中英

如何在 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_n的第 i行的非零列。

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM