0
0
NumPydata~5 mins

np.union1d() for union in NumPy

Choose your learning style9 modes available
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.

You have two lists of customer IDs and want to find all unique customers.
You want to combine two sets of survey answers and see all different responses.
You have two lists of product codes and want a list of all products available.
You want to merge two arrays of dates and get all unique dates without duplicates.
Syntax
NumPy
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.

Examples
This combines two lists and prints all unique numbers sorted.
NumPy
import numpy as np

arr1 = [1, 2, 3]
arr2 = [3, 4, 5]
result = np.union1d(arr1, arr2)
print(result)
This works with arrays of strings, showing all unique fruits.
NumPy
import numpy as np

arr1 = np.array(['apple', 'banana'])
arr2 = np.array(['banana', 'cherry'])
result = np.union1d(arr1, arr2)
print(result)
Sample Program

This program finds all unique numbers from two lists and prints them sorted.

NumPy
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)
OutputSuccess
Important Notes

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).

Summary

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.