from scipy.sparse import csr_matrix import numpy as np indptr = np.array([0, 2, 3, 6]) indices = np.array([0, 2, 2, 0, 1, 2]) data = np.array([1, 2, 3, 4, 5, 6]) #表示要构建稀疏矩阵的数据 #按照行来压缩, #方法:第i行(本例中i=0,1,2), #非零数据列的索引为indices[indptr[i]:indptr[i+1]] #非零数据列的数据为 data[indptr[i]:indptr[i+1]] csr_matrix((data, indices, indptr),shape=(3, 3)).toarray()
array([[1, 0, 2], [0, 0, 3], [4, 5, 6]])
from scipy.sparse import csc_matrix #按照列来压缩, #方法:第i列(本例中i=0,1,2), #非零数据行的索引为indices[indptr[i]:indptr[i+1]] #非零数据行的数据为 data[indptr[i]:indptr[i+1]] csc_matrix((data, indices, indptr), shape=(3, 3)).toarray() #和上面的例子正好是转置
array([[1, 0, 4], [0, 0, 5], [2, 3, 6]])