Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two scipy.sparse matrices in python

I work on a program that deals with large networks and therefore I have to use sparse matrices (preferrably scipy.sparse.csr). Now I would like to write a function that takes two sparse boolean matrices A and B and returns B without those entries that are set in A. Here is a pseudo-code example.

def f(A, B):
    return B and (not A)

How can this be done with scipy.sparse matrices?

like image 509
user3091669 Avatar asked Nov 02 '22 09:11

user3091669


1 Answers

Here's one way to implement your function:

def f(a, b):
    return b - b.multiply(a)

b.multiply(a) is effectively an element-wise and operation.

Here's an example. a and b are sparse matrices:

In [134]: b.A
Out[134]: array([[False, False,  True,  True]], dtype=bool)

In [135]: a.A
Out[135]: array([[False,  True, False,  True]], dtype=bool)

In [136]: f(a,b).A
Out[136]: array([[False, False,  True, False]], dtype=bool)
like image 51
Warren Weckesser Avatar answered Nov 09 '22 05:11

Warren Weckesser