Merge two arrays without duplicates in Python
In this tutorial, we are going to see how to merge two arrays without duplicate values in Python. To do this we will require the NumPy Python library. This library is used to work with arrays.
Import the library to use in the code :
import numpy as np
Define two arrays using the array()
function from the numpy library. This function defines an array of any data type.
x = np.array([1,2,3,4,8,5]) y = np.array([4,5,6,7,8,9,10])
isin( ) function
isin(first_array, second_array)
is a function from the Python library which returns True if the element from the first array is found in the second and False otherwise.
Note: Here Second_array is a check array that can have the same size as the first but not larger.
Now using this function, update the y array.
y = y[~np.isin(y,x)] print(y)
Now updated y array will have elements that are in y but not in x.
As we are removing elements from the y array which are as same as x, take the negation of the isin( )
function.
~
is a sign of negation. It inverts the statement i.e., if isin( )
returns True after negation, it will become False and vice-versa.
Output:
[ 6 7 9 10]
concatenate( ) function to merge two arrays without duplicates
concatenate(first_array, second_array)
is a function from the numpy library which is used to join two arrays.
Now using this function merges the x and y array.
z = np.concatenate([x,y]) print(z)
Output:
[ 1 2 3 4 8 5 6 7 9 10]
As you can see the final (z) merged array has all the unique elements from the x and y array.
You may also read How to remove duplicate elements from a NumPy array in Python
Leave a Reply