7

I have a sparse matrix random matrix created as follows:

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

I want to iterate over the cells in a particular row and perform two calculations:

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
"""
2
  • 1
    Are you just looking for a solution or the an efficient one?
    – tooty44
    Jan 19, 2017 at 18:49
  • An efficient one, I'd rather not use "todense" for example.
    – gornvix
    Jan 19, 2017 at 18:52

1 Answer 1

3

Here's an approach -

# 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)])

Alternatively, as suggested in comments by @user2357112, we can simply use matrix-multiplication to get the second summation -

sum2 = sum((row1*row2.T).data)
4
  • 1
    It looks to me like you could use row1 * row2.T to simplify most of the sum2 calculation. Jan 19, 2017 at 19:54
  • @user2357112 Good idea! Added into post. Thanks!
    – Divakar
    Jan 19, 2017 at 20:07
  • I'm getting an intermittent error with (row1*row2.T).data[0]. Does this work if there are no collisions e.g. when the product is 0?
    – gornvix
    Jan 20, 2017 at 15:31
  • 1
    @tyebillion Yeah that was a bug indeed. Should be fixed now. Check it out!
    – Divakar
    Jan 20, 2017 at 16:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.