我正在尝试处理稀疏矩阵中的一些数据。一旦我创建了一个,我该如何添加/更改/更新其中的值?这看起来非常基本,但我无法在稀疏矩阵类的文档或网络上找到它。我想我遗漏了一些重要的东西。
这是我尝试以与普通数组相同的方式执行此操作的失败尝试。
>>> from scipy.sparse import bsr_matrix
>>> A = bsr_matrix((10,10))
>>> A[5][7] = 6
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
A[5][7] = 6
File "C:\Python27\lib\site-packages\scipy\sparse\bsr.py", line 296, in __getitem__
raise NotImplementedError
NotImplementedError
最佳答案
有几种稀疏矩阵格式。有些更适合索引。 lil_matrix
已经实现了它。
Al = A.tolil()
Al[5,7] = 6 # the normal 2d matrix indexing notation
print Al
print Al.A # aka Al.todense()
A1 = Al.tobsr() # if it must be in bsr format
每种格式的文档都说明了它的优点和缺点。但它没有一个清晰的列表,列出哪些操作定义了哪些操作。
Advantages of the LIL format
supports flexible slicing
changes to the matrix sparsity structure are efficient
...
Intended Usage
LIL is a convenient format for constructing sparse matrices
...
dok_matrix
也实现了索引。
coo_matrix
的底层数据结构很容易理解。它本质上是为coo_matrix((data, (i, j)), [shape=(M, N)])
定义的参数。要创建相同的矩阵,您可以使用:
sparse.coo_matrix(([6],([5],[7])), shape=(10,10))
如果你有更多的任务,构建更大的data
、i
、j
列表(或一维数组),并在完成后构造稀疏矩阵。
关于python - 如何使用 scipy 编辑稀疏矩阵中的单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24665269/