NumPy is a popular library for working with arrays. NumPy’s intersect1d() function returns the intersection between two arrays. In other words, it returns the common elements for two given arrays.
numpy.intersect1d(ar1, ar2, assume_unique=False, return_indices=False)
This function accepts the following parameter values:
ar1 and ar2: These two required parameters represent the input arrays for which intersect1d() will return the intersection.Note:
intersect1d()accepts any array-like objects; this includes NumPy arrays andscalars.
Note: If any input array is not one-dimensional, the function will flatten them and convert them to a single dimensional array.
assume_unique: An optional parameter, passed as True if both input arrays are assumed to be unique and False otherwise. If both input arrays are unique, passing assume_unique as True can speed up calculation.Note: If the input arrays are not unique and the user passesassume_uniqueasTrue, the function could return an incorrect result or an out-of-bound exception.
return_indices: An optional parameter, which determines if intersect1d() will return two extra arrays containing indices of the elements of the intersection array in the two input arrays.Note: The optional arrays are only returned when thereturn_indicesinput argument has been set toTrue.
import numpy as np# creating the input arraysa = np.array([1,3,5,7,9])b = np.array([2,4,6,8])# finding the intersect of the two arraysprint(np.intersect1d(a, b))# creating the input arraysc = np.array([[1,2,3], [4,5,6]])d = np.array([[1,2,3], [4,5,6]])# finding the intersect of the two arraysprint(np.intersect1d(c, d))# creating the input arrayse = np.array([[1,2,3], [7,8,9]])f = np.array([[1,2,3], [4,5,6]])# finding the intersect of the two arraysprint(np.intersect1d(e, f, return_indices = True))
numpy as np.a and b.intersect1d() to find the intersection of a and b, and print the results.c and d. These are two 2D arrays.intersect1d() to find the intersection of c and d and print the results. The intersect1d() function returns a 1D array even though we input two 2D arrays.e and f.intersect1d() to find the intersection of e and f, and print the results. The return_indices argument in intersect1d() has been set to True. As a result, intersect1d() returns two extra arrays, which contain indices of the intersection elements in the two input arrays. e and f both contain the intersection elements 1, 2, and 3 at indices 0, 1, and 2.