If you are familiar with the Python programming language and its scientific computing ecosystem, you must have come across numpy
. NumPy is a powerful library that provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays.
In this blog post, we will explore one of the handy functions offered by NumPy called union1d
. The union1d
function allows us to find the unique elements that are present in both of the input arrays. It returns a sorted array of unique values from both arrays.
Let’s dive into some code examples to better understand how to use the union1d
function.
Syntax
The union1d
function has the following syntax:
numpy.union1d(ar1, ar2)
ar1
andar2
are the two input arrays on which you want to perform the operation.
Example 1: Finding the union of two arrays
Let’s start with a simple example. Suppose we have two arrays, arr1
and arr2
, as follows:
import numpy as np
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([4, 5, 6, 7, 8])
To find the union of these two arrays, we can use the union1d
function. Here’s how you would do it:
result = np.union1d(arr1, arr2)
print(result)
The output will be:
[1 2 3 4 5 6 7 8]
The union1d
function returns a sorted array that contains unique values from both arr1
and arr2
.
Example 2: Union of arrays with duplicate values
Now, let’s consider a case where both input arrays have duplicate values. Consider the following example:
arr3 = np.array([1, 2, 2, 3, 4, 5])
arr4 = np.array([4, 5, 5, 6, 7, 8])
If we apply the union1d
function to these two arrays, we will get the following output:
result = np.union1d(arr3, arr4)
print(result)
The output will be:
[1 2 3 4 5 6 7 8]
As you can see, the union1d
function handles duplicate values by returning only the unique elements from both arrays.
Conclusion
The union1d
function in NumPy is a useful tool for finding the union of two arrays and obtaining a sorted array of unique values. It simplifies the process of combining arrays and eliminating duplicates. Incorporate this function into your Python code to streamline your data manipulation tasks and enhance your programming efficiency.
I hope this blog post has provided you with a good understanding of the union1d
function in NumPy. Feel free to explore more of NumPy’s extensive functionality for working with arrays and matrices. Happy coding!