2

我有以下情况:

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

所以:

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

当然我可以遍历整个事情,但我在想应该有一个更pythonic的解决方案,这也可以加快整个事情。

谢谢

4

1 回答 1

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]

对不起,有点来回,所以如果还有什么不太对劲。我有点希望有一个更整洁的解决方案......

于 2012-10-16T22:42:33.073 回答