gpt4 book ai didi

python - 如何迭代 SciPy 稀疏矩阵中的一行?

转载 作者:太空狗 更新时间:2023-10-30 01:26:48 24 4
gpt4 key购买 nike

我有一个稀疏矩阵随机矩阵创建如下:

import numpy as np
from scipy.sparse import rand
foo = rand(100, 100, density=0.1, format='csr')

我想遍历特定行中的单元格并执行两个计算:

row1 = foo.getrow(bar1)
row2 = foo.getrow(bar2)

"""
Like the following:
sum1 = 0
sum2 = 0
for each cell x in row1:
sum1 += x
if the corresponding cell (in the same column) in row2 y is non-zero:
sum2 += x*y
"""

最佳答案

这是一种方法-

# Get first row summation by simply using sum method of sparse matrix
sum1 = row1.sum()

# Get the non-zero indices of first row
idx1 = row1.indices
data1 = row1.data # Or get sum1 here with : `data1.sum()`.

# Get the non-zero indices of second row and corresponding data
idx2 = row2.indices
data2 = row2.data

# Get mask of overlap from row1 nonzeros on row2 nonzeros.
# Select those from data2 and sum those up for the second summation o/p.
sum2 = data1[np.in1d(idx1,idx2)].dot(data2[np.in1d(idx2,idx1)])

或者,按照 comments by @user2357112 中的建议, 我们可以简单地使用 matrix-multiplication 得到第二个求和 -

sum2 = sum((row1*row2.T).data)

关于python - 如何迭代 SciPy 稀疏矩阵中的一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41749347/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com