Skip to main content
 首页 » 编程设计

python之scipy.sparse.csr_matrix 如果不为零则替换值

2025年05月04日11zhujiabin

我有以下情况:

我有两个形状相同的 csr_matrices(以向量的形式),如果向量 v 的对应值不为零,我想替换向量 u 的值。

所以:

u[i,0] = v[i,0] iff v[i,0] is not zero 

当然我可以遍历整个事情,但我认为应该有一个更 pythonic 的解决方案来解决这个问题,这也会加快整个事情的速度。

谢谢

请您参考如下方法:

我认为你会得到的最好的可能是这个,但是这不会为 u 的稀疏模式添加新值,只是当且仅当 (u[i,j]非零)和(v[i,j] != 0)!

if not isinstance(u, csr_matrix): 
    raise ValueError 
# make sure that data is as expected. I hope this is all thats necessary. Not sure when it is necessary: 
u.sum_duplicates() 
 
col = np.arange(u.shape[0]).repeat(np.diff(u.indptr)) 
row = u.indices 
# You could mask out specific rows/columns here too I guess 
 
new_data = v[row, col] 
new_data = np.asarray(new_data).squeeze() # probably not necessary, but doesn't hurt too 
mask = new_data != 0 
np.putmask(u.data, mask, new_data) 
 
# or if you prefere, but a bit slower for the putmask call: 
u.data[mask] = new_data[mask] 

不好意思,来回说了一些,如果还有不对的地方。我有点希望有一个更简洁的解决方案...