Find common values between two NumPy arrays
Last Updated :
29 Aug, 2020
In this article, we are going to discuss how to find out the common values between 2 arrays. To find the common values, we can use the numpy.intersect1d(), which will do the intersection operation and return the common values between the 2 arrays in sorted order.
Syntax: numpy.intersect1d(arr1, arr2, assume_unique = False, return_indices = False)
Parameters :
arr1, arr2 : [array_like] Input arrays.
assume_unique : [bool] If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.
return_indices : [bool] If True, the indices which correspond to the intersection of the two arrays are returned. The first instance of a value is used if there are multiple. Default is False.
Return : [ndarray] Sorted 1D array of common and unique elements.
Example #1: Finding common values between 1d arrays
Python3
import numpy as np
a = np.array([ 2 , 4 , 7 , 1 , 4 ])
b = np.array([ 7 , 2 , 9 , 0 , 5 ])
print ( "Original arrays" , a, ' ' , b)
c = np.intersect1d(a, b)
print ( "Common values" , c)
|
Output:
Original arrays [2 4 7 1 4] [7 2 9 0 5]
Common values [2 7]
Example #2: Finding common values between n-dimensional arrays
Python3
import numpy as np
a = np.array([ 2 , 4 , 7 , 1 , 4 , 9 ]).reshape( 3 , 2 )
b = np.array([ 7 , 2 , 9 , 0 , 5 , 3 ]).reshape( 2 , 3 )
print ( "Original arrays" )
print (a)
print (b)
c = np.intersect1d(a,b)
print ( "Common values" ,c)
|
Output:
Original arrays
[[2 4]
[7 1]
[4 9]]
[[7 2 9]
[0 5 3]]
Common values [2 7 9]
Note: No matter what dimension arrays are passed, the common values will be returned in a 1d flattened manner
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...