w3resource

NumPy: Find the union of two arrays


Union of Two Arrays

Write a NumPy program to find the union of two arrays. Union will return a unique, sorted array of values in each of the two input arrays.

Pictorial Presentation:

Python NumPy: Find the union of two arrays

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a NumPy array 'array1'
array1 = np.array([0, 10, 20, 40, 60, 80])

# Printing the contents of 'array1'
print("Array1: ", array1)

# Creating a Python list 'array2'
array2 = [10, 30, 40, 50, 70]

# Printing the contents of 'array2'
print("Array2: ", array2)

# Finding and printing the unique values that are in only one (not both) of the input arrays
print("Unique values that are in only one (not both) of the input arrays:")
print(np.union1d(array1, array2))

Sample Output:

Array1:  [ 0 10 20 40 60 80]                                           
Array2:  [10, 30, 40, 50, 70]                                          
Unique sorted array of values that are in either of the two input array
s:                                                                     
[ 0 10 20 30 40 50 60 70 80]

Explanation:

In the above code –

array1 = np.array([0, 10, 20, 40, 60, 80]): Creates a NumPy array with elements 0, 10, 20, 40, 60, and 80.

array2 = [10, 30, 40, 50, 70]: Creates a Python list with elements 10, 30, 40, 50, and 70.

print(np.union1d(array1, array2)): The np.union1d function returns the sorted union of the two input arrays, which consists of all unique elements from both ‘array1’ and ‘array2’. In this case, the union is [0, 10, 20, 30, 40, 50, 60, 70, 80], so the output will be [ 0 10 20 30 40 50 60 70 80].


For more Practice: Solve these Related Problems:

  • Compute the union of two arrays using np.union1d and check that the result is unique and sorted.
  • Create a function that merges two arrays and removes duplicates without using np.union1d.
  • Compare the union operation on arrays with overlapping and non-overlapping values.
  • Validate that the union of two arrays contains every distinct element from both inputs.

Go to:


PREV : Set Exclusive-Or of Arrays
NEXT : Test All Elements are True


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.