如何对 Python 中的稀疏矩阵中的整列进行加法运算
How to do addition to a whole column in a sparse matrix in Python
我在 Python 中有一个稀疏矩阵 A
,我想将 14 添加到第一列。
A[:,0] + 14
但是,我收到一条错误消息:
NotImplementedError: adding a nonzero scalar to a sparse matrix is not supported
您可以像这样添加显式列:
A[:, 0] = np.ones((A.shape[0], 1))*14 + A[:, 0]
我 运行 遇到了类似的情况(如您的问题标题中所述),经过一番研究,我发现您可以 manually change the shape of your matrix but then, this doesn't look like the best solution, for this reason, I started a discussion here 我的最终解决方案是手动创建稀疏矩阵( ìndices
、indptr
和 data
列表)所以我可以添加新的列、行并随意更改矩阵稀疏性。
您的问题描述暗示了一个不同的问题,您不想添加新列,而是要更改矩阵中某个元素的值。如果这会改变矩阵稀疏性,我建议您拥有自己的 ìndices
、indptr
和 data
列表。如果你想修改一个non-zero元素,那么你可以直接修改它,没有进一步的问题。
此外,this 可能值得一读
我在 Python 中有一个稀疏矩阵 A
,我想将 14 添加到第一列。
A[:,0] + 14
但是,我收到一条错误消息:
NotImplementedError: adding a nonzero scalar to a sparse matrix is not supported
您可以像这样添加显式列:
A[:, 0] = np.ones((A.shape[0], 1))*14 + A[:, 0]
我 运行 遇到了类似的情况(如您的问题标题中所述),经过一番研究,我发现您可以 manually change the shape of your matrix but then, this doesn't look like the best solution, for this reason, I started a discussion here 我的最终解决方案是手动创建稀疏矩阵( ìndices
、indptr
和 data
列表)所以我可以添加新的列、行并随意更改矩阵稀疏性。
您的问题描述暗示了一个不同的问题,您不想添加新列,而是要更改矩阵中某个元素的值。如果这会改变矩阵稀疏性,我建议您拥有自己的 ìndices
、indptr
和 data
列表。如果你想修改一个non-zero元素,那么你可以直接修改它,没有进一步的问题。
此外,this 可能值得一读