Home »
Python »
Python Programs
Find the union of more than two NumPy arrays
In this tutorial, we will learn how to find the union of more than two NumPy arrays in Python?
By IncludeHelp Last updated : September 19, 2023
In the last tutorial, we discussed how to find the union of two NumPy arrays. Here, we will learn to find the union of more than two arrays.
Problem statement
Let's suppose there are three NumPy arrays arr1, arr2, and arr3. We have to find their union and print the union result.
Example
Consider the below example with sample input and output:
Input:
arr1: [-1, 0, 1]
arr2: [-2, 0, 2]
arr3: [-4, 2, 1]
Output:
[-4, -2, -1, 0, 1, 2]
Finding the union of more than two NumPy arrays
To find the union of more than two NumPy arrays, use functools.reduce() method by passing the numpy.union1d and input arrays i.e., the array of arrays. It performs the union operation on the input arrays and returns the unique, sorted array. Consider the below code:
reduce(np.union1d, (arr1,arr2, arr3))
Note
To use reduce() method, you need to write the below import statement:
from functools import reduce
Let's understand with an example.
Python program to find the union of more than two NumPy arrays
# Import numpy
from functools import reduce
import numpy as np
# Creating numpy arrays
arr1 = np.array([-1, 0, 1])
arr2 = np.array([-2, 0, 2])
arr3 = np.array([-4, 2, 1])
# Display original arrays
print("Original array 1:\n", arr1, "\n")
print("Original array 2:\n", arr2, "\n")
print("Original array 3:\n", arr2, "\n")
# Find the union of arr1, arr2, and arr3
res = reduce(np.union1d, (arr1, arr2, arr3))
# Display result
print("Result:\n", res, "\n")
Output
Original array 1:
[-1 0 1]
Original array 2:
[-2 0 2]
Original array 3:
[-2 0 2]
Result:
[-4 -2 -1 0 1 2]
Python NumPy Programs »