Introduction
We use np.union1d() to combine two lists or arrays and get all unique items from both. It helps us find everything that appears in either list without repeats.
Jump into concepts and practice - no test required
We use np.union1d() to combine two lists or arrays and get all unique items from both. It helps us find everything that appears in either list without repeats.
np.union1d(array1, array2)
array1 and array2 can be lists or numpy arrays.
The result is a sorted numpy array of unique elements from both inputs.
import numpy as np arr1 = [1, 2, 3] arr2 = [3, 4, 5] result = np.union1d(arr1, arr2) print(result)
import numpy as np arr1 = np.array(['apple', 'banana']) arr2 = np.array(['banana', 'cherry']) result = np.union1d(arr1, arr2) print(result)
This program finds all unique numbers from two lists and prints them sorted.
import numpy as np # Two lists of numbers list1 = [10, 20, 30, 40] list2 = [30, 40, 50, 60] # Find union of unique elements union_result = np.union1d(list1, list2) print("Union of list1 and list2:", union_result)
The output is always sorted in ascending order.
Input arrays can be of different types but should be compatible (e.g., both numbers or both strings).
np.union1d() combines two arrays and returns unique sorted elements.
It is useful to merge data without duplicates.
Works with numbers, strings, or any comparable data types.
np.union1d() do when applied to two arrays?a and b using numpy?np.union1d() with parentheses.import numpy as np x = np.array([1, 3, 5]) y = np.array([3, 4, 5, 6]) result = np.union1d(x, y) print(result)
import numpy as np arr1 = [1, 2, 3] arr2 = [3, 4, 5] result = np.union1d(arr1 arr2) print(result)
np.union1d(arr1 arr2) is missing a comma between arguments.dataset1 = np.array([101, 102, 103, 104]) dataset2 = np.array([103, 104, 105, 106])