Home >Backend Development >Python Tutorial >How to Efficiently Perform Multi-Array Union Operations with NumPy\'s `logical_or`?

How to Efficiently Perform Multi-Array Union Operations with NumPy\'s `logical_or`?

Barbara Streisand
Barbara StreisandOriginal
2024-12-07 15:15:14327browse

How to Efficiently Perform Multi-Array Union Operations with NumPy's `logical_or`?

Numpy logical_or for Multi-Array Union Operations

Numpy's logical_or function operates on pairs of arrays, leading to the question of how to efficiently combine multiple arrays for union operations (likewise for logical_and and intersections).

While logical_or itself accepts only two arguments, it can be chained together:

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)
# result: [ True,  True,  True,  False]

A more generalized approach involves using reduce:

result = np.logical_or.reduce((x, y, z))
# result: [ True,  True,  True,  False]

This method can be applied to both multi-dimensional arrays and tuples of 1D arrays. Additionally, Python's functools.reduce can be used in similar fashion:

result = functools.reduce(np.logical_or, (x, y, z))
# result: [ True,  True,  True,  False]

For convenience, Numpy provides any, which essentially performs a logical OR reduction along an axis:

result = np.any((x, y, z), axis=0)
# result: [ True,  True,  True,  False]

Similar principles apply to logical_and and other logical operators, except for logical_xor, which lacks a corresponding all/any-type function.

The above is the detailed content of How to Efficiently Perform Multi-Array Union Operations with NumPy\'s `logical_or`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn