
- NumPy - Home
- NumPy - Introduction
- NumPy - Environment
- NumPy Arrays
- NumPy - Ndarray Object
- NumPy - Data Types
- NumPy Creating and Manipulating Arrays
- NumPy - Array Creation Routines
- NumPy - Array Manipulation
- NumPy - Array from Existing Data
- NumPy - Array From Numerical Ranges
- NumPy - Iterating Over Array
- NumPy - Reshaping Arrays
- NumPy - Concatenating Arrays
- NumPy - Stacking Arrays
- NumPy - Splitting Arrays
- NumPy - Flattening Arrays
- NumPy - Transposing Arrays
- NumPy Indexing & Slicing
- NumPy - Indexing & Slicing
- NumPy - Indexing
- NumPy - Slicing
- NumPy - Advanced Indexing
- NumPy - Fancy Indexing
- NumPy - Field Access
- NumPy - Slicing with Boolean Arrays
- NumPy Array Attributes & Operations
- NumPy - Array Attributes
- NumPy - Array Shape
- NumPy - Array Size
- NumPy - Array Strides
- NumPy - Array Itemsize
- NumPy - Broadcasting
- NumPy - Arithmetic Operations
- NumPy - Array Addition
- NumPy - Array Subtraction
- NumPy - Array Multiplication
- NumPy - Array Division
- NumPy Advanced Array Operations
- NumPy - Swapping Axes of Arrays
- NumPy - Byte Swapping
- NumPy - Copies & Views
- NumPy - Element-wise Array Comparisons
- NumPy - Filtering Arrays
- NumPy - Joining Arrays
- NumPy - Sort, Search & Counting Functions
- NumPy - Searching Arrays
- NumPy - Union of Arrays
- NumPy - Finding Unique Rows
- NumPy - Creating Datetime Arrays
- NumPy - Binary Operators
- NumPy - String Functions
- NumPy - Matrix Library
- NumPy - Linear Algebra
- NumPy - Matplotlib
- NumPy - Histogram Using Matplotlib
- NumPy Sorting and Advanced Manipulation
- NumPy - Sorting Arrays
- NumPy - Sorting along an axis
- NumPy - Sorting with Fancy Indexing
- NumPy - Structured Arrays
- NumPy - Creating Structured Arrays
- NumPy - Manipulating Structured Arrays
- NumPy - Record Arrays
- Numpy - Loading Arrays
- Numpy - Saving Arrays
- NumPy - Append Values to an Array
- NumPy - Swap Columns of Array
- NumPy - Insert Axes to an Array
- NumPy Handling Missing Data
- NumPy - Handling Missing Data
- NumPy - Identifying Missing Values
- NumPy - Removing Missing Data
- NumPy - Imputing Missing Data
- NumPy Performance Optimization
- NumPy - Performance Optimization with Arrays
- NumPy - Vectorization with Arrays
- NumPy - Memory Layout of Arrays
- Numpy Linear Algebra
- NumPy - Linear Algebra
- NumPy - Matrix Library
- NumPy - Matrix Addition
- NumPy - Matrix Subtraction
- NumPy - Matrix Multiplication
- NumPy - Element-wise Matrix Operations
- NumPy - Dot Product
- NumPy - Matrix Inversion
- NumPy - Determinant Calculation
- NumPy - Eigenvalues
- NumPy - Eigenvectors
- NumPy - Singular Value Decomposition
- NumPy - Solving Linear Equations
- NumPy - Matrix Norms
- NumPy Element-wise Matrix Operations
- NumPy - Sum
- NumPy - Mean
- NumPy - Median
- NumPy - Min
- NumPy - Max
- NumPy Set Operations
- NumPy - Unique Elements
- NumPy - Intersection
- NumPy - Union
- NumPy - Difference
- NumPy Random Number Generation
- NumPy - Random Generator
- NumPy - Permutations & Shuffling
- NumPy - Uniform distribution
- NumPy - Normal distribution
- NumPy - Binomial distribution
- NumPy - Poisson distribution
- NumPy - Exponential distribution
- NumPy - Rayleigh Distribution
- NumPy - Logistic Distribution
- NumPy - Pareto Distribution
- NumPy - Visualize Distributions With Sea born
- NumPy - Matplotlib
- NumPy - Multinomial Distribution
- NumPy - Chi Square Distribution
- NumPy - Zipf Distribution
- NumPy File Input & Output
- NumPy - I/O with NumPy
- NumPy - Reading Data from Files
- NumPy - Writing Data to Files
- NumPy - File Formats Supported
- NumPy Mathematical Functions
- NumPy - Mathematical Functions
- NumPy - Trigonometric functions
- NumPy - Exponential Functions
- NumPy - Logarithmic Functions
- NumPy - Hyperbolic functions
- NumPy - Rounding functions
- NumPy Fourier Transforms
- NumPy - Discrete Fourier Transform (DFT)
- NumPy - Fast Fourier Transform (FFT)
- NumPy - Inverse Fourier Transform
- NumPy - Fourier Series and Transforms
- NumPy - Signal Processing Applications
- NumPy - Convolution
- NumPy Polynomials
- NumPy - Polynomial Representation
- NumPy - Polynomial Operations
- NumPy - Finding Roots of Polynomials
- NumPy - Evaluating Polynomials
- NumPy Statistics
- NumPy - Statistical Functions
- NumPy - Descriptive Statistics
- NumPy Datetime
- NumPy - Basics of Date and Time
- NumPy - Representing Date & Time
- NumPy - Date & Time Arithmetic
- NumPy - Indexing with Datetime
- NumPy - Time Zone Handling
- NumPy - Time Series Analysis
- NumPy - Working with Time Deltas
- NumPy - Handling Leap Seconds
- NumPy - Vectorized Operations with Datetimes
- NumPy ufunc
- NumPy - ufunc Introduction
- NumPy - Creating Universal Functions (ufunc)
- NumPy - Arithmetic Universal Function (ufunc)
- NumPy - Rounding Decimal ufunc
- NumPy - Logarithmic Universal Function (ufunc)
- NumPy - Summation Universal Function (ufunc)
- NumPy - Product Universal Function (ufunc)
- NumPy - Difference Universal Function (ufunc)
- NumPy - Finding LCM with ufunc
- NumPy - ufunc Finding GCD
- NumPy - ufunc Trigonometric
- NumPy - Hyperbolic ufunc
- NumPy - Set Operations ufunc
- NumPy Useful Resources
- NumPy - Quick Guide
- NumPy - Cheatsheet
- NumPy - Useful Resources
- NumPy - Discussion
- NumPy Compiler
NumPy - Union
Union in NumPy
In NumPy, the term "union" refers to the operation that combines the elements of two or more arrays, removing any duplicate values.
It is commonly used when you want to merge multiple datasets or arrays, ensuring that each element appears only once in the final result.
NumPy provides the numpy.union1d() function to easily find the union of two 1-dimensional arrays.
What is Union of Arrays?
The union of two or more arrays refers to the combined set of unique elements from all the input arrays.
This means that no duplicate elements are present in the result. The union operation is closely related to the concept of sets in mathematics.
For example, if you have two arrays containing some common and some unique elements, the union will contain all the unique elements from both arrays.
The NumPy union1d() Function
In NumPy, the numpy.union1d() function is used to compute the union of two 1-dimensional arrays. This function ensures that no elements are repeated in the result, even if the same element appears in both input arrays.
Following is the basic syntax of the NumPy union1d() function −
numpy.union1d(ar1, ar2)
Where, ar1 and ar2 are the two input arrays whose union is to be found. The arrays can contain any data type, and they may or may not have overlapping elements.
Example
In the following example, we are calculating the union of two arrays using the union1d() function in NumPy −
import numpy as np # Define two arrays array1 = np.array([1, 2, 3, 4, 5]) array2 = np.array([4, 5, 6, 7, 8]) # Find union of the two arrays union = np.union1d(array1, array2) print("Union of array1 and array2:", union)
As seen in the output, the union of array1 and array2 contains all unique elements from both arrays, without any repetition. The numbers 4 and 5, which appeared in both arrays, appear only once in the final result −
Union of array1 and array2: [1 2 3 4 5 6 7 8]
Union of Arrays with Different Data Types
NumPy's union1d() function can also handle arrays of different data types, such as integers, floats, and even strings. The function will convert all elements to a common type before computing the union.
Example
As shown in the example below, NumPy has automatically converted all elements to floats because the first array contains a floating-point number, and the union contains no duplicates −
import numpy as np # Define arrays with different data types array1 = np.array([1, 2, 3, 4.5]) array2 = np.array([4.5, 5, 6, 7]) # Find union of the arrays union = np.union1d(array1, array2) print("Union of array1 and array2 with different types:", union)
The result produced is as follows −
Union of array1 and array2 with different types: [1. 2. 3. 4.5 5. 6. 7.]
Handling Multiple Arrays
The numpy.union1d() function works with two arrays at a time. However, if you need to find the union of more than two arrays, you can use loops or the reduce() function from the functools module.
Example
Below is an example that demonstrates how to compute the union of three arrays −
import numpy as np from functools import reduce # Define multiple arrays array1 = np.array([1, 2, 3, 4, 5]) array2 = np.array([4, 5, 6, 7, 8]) array3 = np.array([7, 8, 9, 10]) # Find the union of all arrays union = reduce(np.union1d, [array1, array2, array3]) print("Union of multiple arrays:", union)
As shown in the output, the union operation combines all the unique elements from the three arrays. There are no duplicates, and the union contains all the unique values across the arrays −
Union of multiple arrays: [1 2 3 4 5 6 7 8 9 10]
Union with Arrays Containing Duplicates
When the input arrays contain duplicate elements, numpy.union1d() automatically removes them in the final result. This ensures that the returned union consists of only unique elements.
Example
Following is an example where we find the union of arrays containing duplicates −
import numpy as np # Define arrays with duplicate elements array1 = np.array([1, 2, 2, 3, 4]) array2 = np.array([3, 4, 4, 5, 6]) # Find union of the arrays union = np.union1d(array1, array2) print("Union with duplicates removed:", union)
The output obtained is as shown below −
Union with duplicates removed: [1 2 3 4 5 6]
Union of Arrays with Strings
In NumPy, you can also perform union operations on arrays containing strings. The function will combine all unique strings from both arrays.
Example
Let us take a look at an example with string arrays −
import numpy as np # Define arrays with strings array1 = np.array(['apple', 'banana', 'cherry']) array2 = np.array(['banana', 'cherry', 'date']) # Find the union of the string arrays union = np.union1d(array1, array2) print("Union of string arrays:", union)
We get the following output −
Union of string arrays: ['apple' 'banana' 'cherry' 'date']
Performance Considerations
The numpy.union1d() function is efficient, but the performance can depend on the size of the input arrays. When you are working with very large arrays, it is a good idea to ensure that the arrays are as efficient as possible.
For example, if the arrays contain only unique elements, you can set the assume_unique parameter to True to speed up the union operation:
Example
By assuming that the arrays contain only unique elements, NumPy can perform the union operation more quickly as shown in the example below −
import numpy as np # Define arrays with unique elements array1 = np.array([1, 2, 3, 4, 5]) array2 = np.array([6, 7, 8, 9, 10]) # Find union assuming unique elements union = np.union1d(array1, array2) print("Union of unique arrays:", union)
The result produced is as follows −
Union of unique arrays: [1 2 3 4 5 6 7 8 9 10]