通过for循环填充scipysparse.coo_matrix
Fill scipy sparse.coo_matrix by for loop
我想迭代填充一个scipy稀疏coo_matrix
# Constructing an empty matrix
import numpy as np
from scipy.sparse import coo_matrix
m = coo_matrix((3, 4), dtype=np.int8)
通过 for 循环和一些规则,例如所有的(我知道有一个带有数据的构造函数,但我不能使用它,因为规则更复杂)。我怎样才能做到这一点?我还没有找到任何关于它的文档。
可以不直接用for循环scipysparse.coo_matrix
您最好的选择是将 coo_matrix 转换为可以像字典一样进行索引的 dok_matrix,然后在需要时将其恢复为 coo_matrix。
import numpy as np
from scipy.sparse import coo_matrix
m = coo_matrix((3, 4), dtype=np.int8)
m = m.todok() # convert to dok
for i in xrange(10):
for j in xrange(5):
m[i, j] = i + j # update the matrix, note the particular access format
m = m.tocoo() # convert back to coo
这是最快的方法,如所述。
我想迭代填充一个scipy稀疏coo_matrix
# Constructing an empty matrix
import numpy as np
from scipy.sparse import coo_matrix
m = coo_matrix((3, 4), dtype=np.int8)
通过 for 循环和一些规则,例如所有的(我知道有一个带有数据的构造函数,但我不能使用它,因为规则更复杂)。我怎样才能做到这一点?我还没有找到任何关于它的文档。
可以不直接用for循环scipysparse.coo_matrix
您最好的选择是将 coo_matrix 转换为可以像字典一样进行索引的 dok_matrix,然后在需要时将其恢复为 coo_matrix。
import numpy as np
from scipy.sparse import coo_matrix
m = coo_matrix((3, 4), dtype=np.int8)
m = m.todok() # convert to dok
for i in xrange(10):
for j in xrange(5):
m[i, j] = i + j # update the matrix, note the particular access format
m = m.tocoo() # convert back to coo
这是最快的方法,如