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)
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
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
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
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.