如果您可以将输入数据分离为一系列行索引,一系列列索引和相应的值索引序列,则可以使用csr_matrix
文档字符串中显示的第四个选项来创建矩阵。
例如,假设您已将数据存储在单个数组中,其中前两列是索引,第三列保存值。例如。
In [213]: data
Out[213]:
array([[ 0, 0, 10],
[ 0, 1, 5],
[ 1, 0, 3],
[ 1, 1, 4]])
然后你就可以创建一个CSR矩阵如下:
In [214]: a = csr_matrix((data[:, 2], (data[:, 0], data[:, 1])))
In [215]: a
Out[215]:
<2x2 sparse matrix of type '<type 'numpy.int64'>'
with 4 stored elements in Compressed Sparse Row format>
In [216]: a.A
Out[216]:
array([[10, 5],
[ 3, 4]])
根据您的资料,您可能需要显式地指定的形状。例如,我在这里使用相同的数据,但在一个3x3矩阵:
In [217]: b = csr_matrix((data[:, 2], (data[:, 0], data[:, 1])), shape=(3, 3))
In [218]: b
Out[218]:
<3x3 sparse matrix of type '<type 'numpy.int64'>'
with 4 stored elements in Compressed Sparse Row format>
In [219]: b.A
Out[219]:
array([[10, 5, 0],
[ 3, 4, 0],
[ 0, 0, 0]])
这里的想法:首先建立一个'coo'矩阵,然后通过'tocsr'转换。 – cel