【发布时间】:2018-06-19 22:19:36
【问题描述】:
我在 Python 中有一个稀疏矩阵 A,我想将 14 添加到第一列。
A[:,0] + 14
但是,我收到一条错误消息:
NotImplementedError: adding a nonzero scalar to a sparse matrix is not supported
【问题讨论】:
标签: python scipy sparse-matrix
我在 Python 中有一个稀疏矩阵 A,我想将 14 添加到第一列。
A[:,0] + 14
但是,我收到一条错误消息:
NotImplementedError: adding a nonzero scalar to a sparse matrix is not supported
【问题讨论】:
标签: python scipy sparse-matrix
您可以像这样添加一个显式列:
A[:, 0] = np.ones((A.shape[0], 1))*14 + A[:, 0]
【讨论】:
csr_matrix 并且第一列有零,然后您尝试使用给定的方法,您会得到SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient.
我遇到了类似的情况(如您的问题标题中所述),经过一些研究,我发现您可以manually change the shape of your matrix 但是,这看起来不是最好的解决方案,因此,我开始了讨论here,我的最终解决方案是手动创建稀疏矩阵(ìndices、indptr 和data 列表),以便我可以添加新的列、行并随意更改矩阵稀疏度。
您的问题描述提出了一个不同的问题,您不想添加新列,而是要更改矩阵中元素的值。如果这会改变矩阵稀疏性,我建议你有自己的 ìndices、indptr 和 data 列表。如果你想修改一个非零元素,那么你可以直接改变它,没有进一步的问题。
另外,this 可能值得一读
【讨论】: