如何将值分配给scipy-csr类型的稀疏矩阵中的一个空位



我正在使用SciPy处理一个csr类型的巨大矩阵。稀疏,我想在创建矩阵时给一个从未使用或分配过的空位添加一个值,而不将其转换为密集矩阵。我有想要的行,col&数据值,但我只是不知道如何访问特定元素并将值添加到

更新:我尝试了这个方法,但我得到了一个奇怪的";内核错误";并且它不起作用,假设:(我们在第k行(

data(of row k) =np.insert(data,index,5)
col(indices of the row)=np.insert(col,index, colIndex)
row[k+1:] +=1

我不明白我做错了什么。

csr矩阵示例:

In [66]: M = (sparse.random(5,5,.2,'csr')*10).astype(int)
In [67]: M
Out[67]: 
<5x5 sparse matrix of type '<class 'numpy.int64'>'
with 5 stored elements in Compressed Sparse Row format>
In [69]: M.A
Out[69]: 
array([[0, 0, 4, 0, 0],
[2, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[3, 6, 0, 0, 0],
[0, 0, 0, 0, 0]])

看看它的属性:

In [70]: M.indptr
Out[70]: array([0, 1, 2, 3, 5, 5], dtype=int32)
In [71]: M.indices
Out[71]: array([2, 0, 2, 0, 1], dtype=int32)
In [72]: M.data
Out[72]: array([4, 2, 0, 3, 6])

现在使用索引创建一个新的非零值:

In [73]: M[2,3] = 12
/usr/local/lib/python3.8/dist-packages/scipy/sparse/_index.py:82: SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient.
self._set_intXint(row, col, x.flat[0])

看看新的属性-所有3个属性都已更改。

In [74]: M.indptr
Out[74]: array([0, 1, 2, 4, 6, 6], dtype=int32)
In [75]: M.indices
Out[75]: array([2, 0, 2, 3, 0, 1], dtype=int32)
In [76]: M.data
Out[76]: array([ 4,  2,  0, 12,  3,  6])

indptr中的值已更改,并且值已添加到indicesdata中。虽然我对正在发生的事情有一个大致的了解,但我还没有弄清楚细节。

正如警告所说,它更容易可视化,并执行对lil格式矩阵的添加:

In [88]: Ml = M.tolil()
In [89]: Ml.rows
Out[89]: 
array([list([2]), list([0, 1, 3, 4]), list([1, 2, 4]), list([0, 1, 3]),
list([])], dtype=object)
In [90]: Ml.data
Out[90]: 
array([list([5]), list([3, 0, 5, 1]), list([12, 1, 8]), list([7, 4, 8]),
list([])], dtype=object)
In [91]: Ml.rows[2].append(3)
In [92]: Ml.data[2].append(23)
In [93]: Ml.A
Out[93]: 
array([[ 0,  0,  5,  0,  0],
[ 3,  0,  0,  5,  1],
[ 0, 12,  1, 23,  8],
[ 7,  4,  0,  8,  0],
[ 0,  0,  0,  0,  0]])

最新更新