簡體   English   中英

scipy.sparse.csr_matrix如果不為零,則替換值

[英]scipy.sparse.csr_matrix replace values if not zero

我有以下情況:

我有兩個形狀相等的csr_matrices(以矢量的形式),並且如果矢量v的對應值不為零,我想替換矢量u的值。

所以:

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

當然,我可以遍歷整個過程,但是我認為應該對此有一個更Python的解決方案,這也可以加快整個過程的速度。

謝謝

我認為您可能會得到最好的結果,但是這不會給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]

抱歉,來回有點,所以如果還有不對的地方。 我有點希望有一個更整潔的解決方案...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM