Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Numpy union1d() Function



The Numpy union1d() function is used to compute the union of two arrays. It returns a sorted array of unique elements that are present in either of the input arrays. This function is useful for combining two arrays and removing duplicates.

We can also use the union1d() function to combine arrays of different dimensions into a single sorted array containing unique elements.

In general, the union1d() function is similar to the union operation in set theory, where A B represents all elements that are in either set A or set B, including their intersection.

Syntax

Following is the syntax of the Numpy union1d() function −

numpy.union1d(ar1, ar2)  

Parameters

Following are the parameters of the Numpy union1d() function −

  • ar1: The first input array.
  • ar2: The second input array.

Return Type

This function returns a sorted 1D array containing unique elements that are present in either of the input arrays.

Example

Following is a basic example of finding the union of two arrays using the Numpy union1d() function −

import numpy as np  
my_Array1 = np.array([10, 20, 30, 40])  
my_Array2 = np.array([30, 40, 50, 60])  
result = np.union1d(my_Array1, my_Array2)  
print("Union:", result) 

Output

Following is the output of the above code −

Union: [10 20 30 40 50 60]  

Example: String Arrays as Arguments

The union1d() function can also be used with string arrays. In the following example, we have performed the union operation between two arrays of strings datatype −

import numpy as np  
array1 = np.array(["apple", "banana", "cherry"])  
array2 = np.array(["banana", "date", "orange"])  
result = np.union1d(array1, array2)  
print("Union:", result)  

Output

Following is the output of the above code −

Union: ['apple' 'banana' 'cherry' 'date' 'orange'] 

Example: Combining Different Input Datatypes

We can also use the union1d() function to combine arrays with mixed data types (e.g., integers and strings).

Here, the integer array is first converted to a string array using the astype() function. Then, the union operation is performed between the converted string array and the second string array, resulting in a combined array with unique elements −

import numpy as np
int_Array1 = np.array([1, 2, 3])
str_Array2 = np.array(["2", "4", "6"])
result = np.union1d(int_Array1.astype(str), str_Array2)
print("Union:", result)

Output

Following is the output of the above code −

Union: ['1' '2' '3' '4' '6']
numpy_array_manipulation.htm
Advertisements