Question

To sum elements up, we have binary operator np.add, and moreover np.sum dealing with multiple elements. Likewise, we have np.multiply and np.product to do the multiplication.

But for np.logical_or, what's the corresponding multielement operator? Assuming I have the following array:

In [29]: a
Out[29]: 
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])

I want to have a method like np.logical_or(a, axis=0), so that I could get such an array [ True, True, True]. Now the only way I could come up with is:

In [31]: a.sum(0).astype(bool)
Out[31]: array([ True,  True,  True], dtype=bool)

But that's not a good way because it will fail on array like:

array([[-1, -1],
       [ 1,  1]])
Était-ce utile?

La solution

You're thinking of np.all (for logical_and) or np.any (for logical_or).

In [11]: a.any(axis=1)
Out[11]: array([ True,  True,  True], dtype=bool)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top