我有以下情况:
我有两个相同形状的csr_matrices(以向量的形式),如果向量v的对应值不为零,我想替换向量u的值。
所以:
u[i,0] = v[i,0] iff v[i,0] is not zero
当然,我可以完成整个过程,但我认为应该有更多的pythonic解决方案来加速整个事情。
由于
答案 0 :(得分:0)
我认为你得到的最好的可能就是这个,但这不会为u
的稀疏模式添加新的值,只有iff (u[i,j] is nonzero) and (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]
抱歉,有点来回,所以如果还有一些不太正确的话。我有点希望有一个更简洁的解决方案...