在这里,我们想为非零条目添加一个标量,而不管矩阵
稀疏性,即不要触及零条目。
来自fine Scipy docs(** emphasis **是我的):
Attributes
nnz Get the count of explicitly-stored values (nonzeros)
has_sorted_indices Determine whether the matrix has sorted indices
dtype (dtype) Data type of the matrix
shape (2-tuple) Shape of the matrix
ndim (int) Number of dimensions (this is always 2)
**data CSR format data array of the matrix**
indices CSR format index array of the matrix
indptr CSR format index pointer array of the matrix
所以我尝试了(第一部分是从参考文档中“偷来的”)
In [18]: from scipy import *
In [19]: from scipy.sparse import *
In [20]: row = array([0,0,1,2,2,2])
...: col = array([0,2,2,0,1,2])
...: data =array([1,2,3,4,5,6])
...: a = csr_matrix( (data,(row,col)), shape=(3,3))
...:
In [21]: a.todense()
Out[21]:
matrix([[1, 0, 2],
[0, 0, 3],
[4, 5, 6]], dtype=int64)
In [22]: a.data += 10
In [23]: a.todense()
Out[23]:
matrix([[11, 0, 12],
[ 0, 0, 13],
[14, 15, 16]], dtype=int64)
In [24]:
它有效。如果您保存原始矩阵,您可以使用构造函数
使用修改后的数据数组。
免责声明
这个答案解决了这个问题的解释
我有一个稀疏矩阵,我想向非零条目添加一个标量,同时保留矩阵及其编程表示的稀疏性。
我选择这种解释的原因是向所有条目添加一个标量会将稀疏矩阵变成一个非常密集的矩阵...
如果这是正确的解释,我不知道:一方面,OP 批准了我的回答(至少今天 2017-07-13),另一方面,在他们问题下方的 cmets 中,他们似乎有不同的意见。
然而,答案在稀疏矩阵表示的用例中很有用,例如,稀疏测量值并且您想要纠正测量偏差、减去平均值等,所以我将把它留在这里,即使它可以被认为是有争议的。