scipy.sparse.

save_npz#

scipy.sparse.save_npz(file, matrix, compressed=True)[源代码][源代码]#

使用 .npz 格式将稀疏矩阵或数组保存到文件中。

参数:
文件str 或类文件对象

数据将保存到的文件名(字符串)或已打开的文件(类文件对象)。如果 file 是字符串,如果文件名还没有 .npz 扩展名,则会附加该扩展名。

矩阵: spmatrix 或 sparray

要保存的稀疏矩阵或数组。支持的格式:csccsrbsrdiacoo

压缩bool, 可选

允许压缩文件。默认值: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)