Compressed Sparse Row,CSR格式的列下標向量和數據值向量與COO格式(三元組)類似,在行下標表示上做了壓縮。根據數據的排列規則,只需要指定在哪個數據換到下一行就行。
>>> col_idx = np.array([0,3,1,2,3,0,1,3]) >>> values = np.array([4,2,1,5,7,6,3,8]) >>> row_ptr = np.array([0,2,3,5,8]) >>> csr_mat = scipy.sparse.csr_matrix((values,col_idx, row_ptr),shape=(4,4)).toarray() >>> csr_mat array([[4, 0, 0, 2], [0, 1, 0, 0], [0, 0, 5, 7], [6, 3, 0, 8]])
把非零數據排成一列,並從0開始建立索引,row_ptr指定在哪個索引位置進行換行。例如,稀疏矩陣的第二行是1,那么就在索引2處進行切割。