user3091669
user3091669

Reputation: 63

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?

Upvotes: 6

Views: 2499

Answers (1)

Warren Weckesser
Warren Weckesser

Reputation: 114946

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)

Upvotes: 2

Related Questions