Home >Backend Development >Python Tutorial >How to Perform Numpy\'s Logical OR on More Than Two Arrays?
The logical_or function in Numpy typically operates on only two arrays. However, if you need to compute the union of more than two arrays, there are several approaches you can consider.
One method involves chaining multiple logical_or calls like so:
x = np.array([True, True, False, False]) y = np.array([True, False, True, False]) z = np.array([False, False, False, False]) result = np.logical_or(np.logical_or(x, y), z) # Union of arrays print(result) # Output: [ True True True False]
Another approach is to use the reduce function:
import numpy as np # Union using reduce result = np.logical_or.reduce((x, y, z)) # Union of arrays print(result) # Output: [ True True True False]
This method generalizes the chaining approach and can be used with multi-dimensional arrays as well.
Beyond the aforementioned methods, you can also consider:
import functools result = functools.reduce(np.logical_or, (x, y, z)) # Union of arrays print(result) # Output: [ True True True False]
result = np.any((x, y, z), axis=0) # Union of arrays print(result) # Output: [ True True True False]
For operations like logical exclusive or (logical_xor), NumPy does not provide an all/any-type function.
The above is the detailed content of How to Perform Numpy\'s Logical OR on More Than Two Arrays?. For more information, please follow other related articles on the PHP Chinese website!