Reputation: 530
Is there a practical way to apply the same boolean operator (say or
) to all elements of an array without using a for
loop ?
I will clarify what I need with an example:
import numpy as np
a=np.array([[1,0,0],[1,0,0],[0,0,1]])
b=a[0] | a[1] | a[2]
print b
What is the synthetic way to apply the or
boolean operator to all arrays of a matrix as I have done above?
Upvotes: 0
Views: 1825
Reputation: 23
NOTE: I'm not a numby expert, so I am making an assumption below;
In your example, b is comparing the arrays with each other, so it is asking:
"Are there any items in a[0] OR any items in a1 OR any items in a2" is that your goal? in which case, you could use builtin any()
for example (changed numby to a simple list of lists):
a=[[1,0,0],[1,0,0],[0,0,1]]
b=any(a)
print b
b will be True
if however, you want to know if any element in it is true, so, for example, you want to know if a[0][0] OR a0 | a0 | a[1][0] | ...
you could use the builtin map command, so something like:
a=[[1,0,0],[1,0,0],[0,0,1]]
b=any(map(any, a)
print b
b will still be True
Note: below is based on looking at the NumPy docs, not actual experience.
For NumPy, you could also use the NumPy any() option something like
a=np.array([[1,0,0],[1,0,0],[0,0,1]])
b=a.any()
print b
or, if your doing all numbers anyway, you could sum the array and see if it != 0
Upvotes: 0
Reputation: 281381
The usual way to do this would be to apply numpy.any
along an axis:
numpy.any(a, axis=0)
That said, there is also a way to do this through the operator more directly. NumPy ufuncs have a reduce
method that can be used to apply them along an axis of an array, or across all elements of an array. Using numpy.logical_or.reduce
, we can express this as
numpy.logical_or.reduce(a, axis=0)
This doesn't come up much, because most ufuncs you'd want to call reduce
on already have equivalent helper functions defined. add
has sum
, multiply
has prod
, logical_and
has all
, logical_or
has any
, maximum
has amax
, and minimum
has amin
.
Upvotes: 3
Reputation: 4628
try either:
np.any(arr, axis=0)
or
np.apply_along_axis(any, 0, arr)
or if you want to use pandas for some reason,
df.any(axis=0)
Upvotes: 1
Reputation: 380
You can use reduce
function for that:
from functools import reduce
a = np.array([[1,0,0],[1,0,0],[0,0,1]])
reduce(np.bitwise_or, a)
Upvotes: 0