如何使用scipy编辑稀疏矩阵中的单元格? [英] How do you edit cells in a sparse matrix using scipy?
问题描述
我正在尝试处理稀疏矩阵中的某些数据.创建一个后,如何在其中添加/更改/更新值?这似乎很基础,但是我在稀疏矩阵类的文档中或在Web上找不到它.我想我缺少了一些关键的东西.
I'm trying to manipulate some data in a sparse matrix. Once I've created one, how do I add / alter / update values in it? This seems very basic, but I can't find it in the documentation for the sparse matrix classes, or on the web. I think I'm missing something crucial.
这是我尝试失败的尝试,与使用普通数组一样.
This is my failed attempt to do so the same way I would a normal array.
>>> 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
.
There several Sparse matrix formats. Some are better suited to indexing. One that has implemented it is 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
每种格式的文档都建议了它的优缺点.但是它没有一个清晰的列表,列出了哪些操作定义了哪些操作.
The documentation for each format suggests what it is good at, and where it is bad. But it does not have a neat list of which ones have which operations defined.
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)])
定义的参数.要创建相同的矩阵,您可以使用:
The underlying data structure for coo_matrix
is easy to understand. It is essentially the parameters for coo_matrix((data, (i, j)), [shape=(M, N)])
definition. To create the same matrix you could use:
sparse.coo_matrix(([6],([5],[7])), shape=(10,10))
如果分配的任务更多,请构建更大的data
,i
,j
列表(或一维数组),并在完成后构造稀疏矩阵.
If you have more assignments, build larger data
, i
, j
lists (or 1d arrays), and when complete construct the sparse matrix.
这篇关于如何使用scipy编辑稀疏矩阵中的单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!