hegdep
hegdep

Reputation: 596

Element-wise boolean operation between row of sparse matrix and list

I want to carry out an element wise logical operation between a row of a sparse matrix and another list.

from scipy.sparse import lil_matrix
a=lil_matrix((3,3), dtype=bool)
b=[True,False,True]
a[2,:]=a[2,:] or b

However, this returns:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

There is already one very good explanation for why the error occurs here

However, a.any() or a.all() will return only one truth value and not perform something element wise. Also, np.logical_or(a[2,:],b) returns the same error.

Upvotes: 0

Views: 293

Answers (2)

Paul Panzer
Paul Panzer

Reputation: 53089

You need to do two things:

Cast the list to np.ndarray and use + instead of or. For reasons I do not know the bitwise_or operator | (which one would use for arrays) does not work here.

a[2] += np.array(b)

Upvotes: 1

Prune
Prune

Reputation: 77880

Vectorized or is a numpy operation; there is no direct equivalent for a common list. The most effective and readable way to do this is to convert your Boolean list to an np_array and then apply the operation, letting numpy's processing to rule the process.

Upvotes: 0

Related Questions