Search code examples
pythonlistnumpybooleanor-operator

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.


Solution

  • 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)