Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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)

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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
  
  
# create 2 arrays
a = np.array([2, 4, 7, 1, 4])
b = np.array([7, 2, 9, 0, 5])
  
# Display the arrays
print("Original arrays", a, ' ', b)
  
# use the np.intersect1d method
c = np.intersect1d(a, b)
  
# Display result
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
  
  
# create 2 arrays
a = np.array([2,4,7,1,4,9]).reshape(3,2)
b = np.array([7,2,9,0,5,3]).reshape(2,3)
  
# Display the arrays
print("Original arrays")
print(a)
print(b)
  
# use the np.intersect1d method
c = np.intersect1d(a,b)
  
# Display result
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




My Personal Notes arrow_drop_up
Recommended Articles
Page :