Numpy's logical_or
function takes no more than two arrays to compare. How can I find the union of more than two arrays? (The same question could be asked with regard to Numpy's logical_and
and obtaining the intersection of more than two arrays.)
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
As boolean algebras are both commutative and associative by definition, the following statements or equivalent for boolean values of a, b and c.
a or b or c
(a or b) or c
a or (b or c)
(b or a) or c
So if you have a "logical_or" which is dyadic and you need to pass it three arguments (a, b, and c), you can call
logical_or(logical_or(a, b), c)
logical_or(a, logical_or(b, c))
logical_or(c, logical_or(b, a))
or whatever permutation you like.
Back to python, if you want to test whether a condition (yielded by a function
test
that takes a testee and returns a boolean value) applies to a or b or c or any element of list L, you normally useI use this workaround which can be extended to n arrays:
using the sum function:
Building on abarnert's answer for n-dimensional case:
TL;DR:
np.logical_or.reduce(np.array(list))
If you're asking about
numpy.logical_or
, then no, as the docs explicitly say, the only parameters arex1, x2
, and optionallyout
:You can of course chain together multiple
logical_or
calls like this:The way to generalize this kind of chaining in NumPy is with
reduce
:And of course this will also work if you have one multi-dimensional array instead of separate arrays—in fact, that's how it's meant to be used:
But a tuple of three equal-length 1D arrays is an array_like in NumPy terms, and can be used as a 2D array.
Outside of NumPy, you can also use Python's
reduce
:However, unlike NumPy's
reduce
, Python's is not often needed. For most cases, there's a simpler way to do things—e.g., to chain together multiple Pythonor
operators, don'treduce
overoperator.or_
, just useany
. And when there isn't, it's usually more readable to use an explicit loop.And in fact NumPy's
any
can be used for this case as well, although it's not quite as trivial; if you don't explicitly give it an axis, you'll end up with a scalar instead of an array. So:As you might expect,
logical_and
is similar—you can chain it,np.reduce
it,functools.reduce
it, or substituteall
with an explicitaxis
.What about other operations, like
logical_xor
? Again, same deal… except that in this case there is noall
/any
-type function that applies. (What would you call it?odd
?)In case someone still need this - Say you have three Boolean arrays
a
,b
,c
with the same shape, this givesand
element-wise:this gives
or
:Is this what you want? Stacking a lot of
logical_and
orlogical_or
is not practical.