python - 如何使用 scipy 编辑稀疏矩阵中的单元格?

标签 python matrix scipy sparse-matrix

我正在尝试处理稀疏矩阵中的一些数据。一旦我创建了一个,我该如何添加/更改/更新其中的值?这看起来非常基本,但我无法在稀疏矩阵类的文档或网络上找到它。我想我遗漏了一些重要的东西。

这是我尝试以与普通数组相同的方式执行此操作的失败尝试。

>>> 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))

如果你有更多的任务,构建更大的dataij 列表(或一维数组),并在完成后构造稀疏矩阵。

关于python - 如何使用 scipy 编辑稀疏矩阵中的单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24665269/

相关文章:

python - 在 Python 中将列表对转换为键值对

python - NumPy:查找子矩阵/ block 和相应行、列索引中的最小值

algorithm - 任意矩阵乘法的复杂性

python - 将距离对转换为距离矩阵以用于层次聚类

python - 如何在不影响其余部分的情况下延迟程序的一部分?

python - Heroku 在 Virtual Env 上安装 PIL 依赖时出错

python - 根据概率向量选择 numpy 矩阵的索引

c++ - 如何将 XMMATRIX 和 XMVECTOR (DirectX11) 相乘?

python - 重新排序 CSR 矩阵中的行和列

python - 导入 scipy.sparse._sparsetools 时出错