scipy.sparse.

save_npz#

scipy.sparse.save_npz(file, matrix, compressed=True)[source]#

使用 .npz 格式將稀疏矩陣或陣列保存到檔案。

參數:
filestr 或 類檔案物件

檔案名稱 (字串) 或開啟的檔案 (類檔案物件),資料將儲存於此。如果 file 是字串,則 .npz 副檔名將附加到檔案名稱,如果它還不存在。

matrix: spmatrix 或 sparray

要儲存的稀疏矩陣或陣列。支援的格式:csc, csr, bsr, diacoo

compressedbool,可選

允許壓縮檔案。預設值:True

另請參閱

scipy.sparse.load_npz

使用 .npz 格式從檔案載入稀疏矩陣。

numpy.savez

將多個陣列儲存到 .npz 封存檔中。

numpy.savez_compressed

將多個陣列儲存到壓縮的 .npz 封存檔中。

範例

將稀疏矩陣儲存到磁碟,然後再次載入

>>> import numpy as np
>>> import scipy as sp
>>> sparse_matrix = sp.sparse.csc_matrix([[0, 0, 3], [4, 0, 0]])
>>> sparse_matrix
<Compressed Sparse Column sparse matrix of dtype 'int64'
    with 2 stored elements and shape (2, 3)>
>>> sparse_matrix.toarray()
array([[0, 0, 3],
       [4, 0, 0]], dtype=int64)
>>> sp.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix)
>>> sparse_matrix = sp.sparse.load_npz('/tmp/sparse_matrix.npz')
>>> sparse_matrix
<Compressed Sparse Column sparse matrix of dtype 'int64'
    with 2 stored elements and shape (2, 3)>
>>> sparse_matrix.toarray()
array([[0, 0, 3],
       [4, 0, 0]], dtype=int64)