NumPy Intersection of Two Arrays

NumPy Intersection With the
numpy.in1d()
Method in Python 
NumPy Intersection With the
numpy.intersect1d()
Method in Python
This tutorial will introduce the methods to perform intersection on NumPy arrays in Python.
NumPy Intersection With the numpy.in1d()
Method in Python
Intersection means the common elements in two sets of elements. If we want to find the intersection of two 1D NumPy arrays, we can use the numpy.in1d()
method in Python. The numpy.in1d()
method takes the two arrays, checks whether each element of the first array is present in the second array, and returns a boolean array that contains true for each element present in both arrays and false for each element present in the first array but not in the second array. We can use this resultant array as the first array index to get the common elements in both arrays.
import numpy as np
A = np.array([2,3,5,7,11])
B = np.array([1,3,5,7,9])
C = A[np.in1d(A, B)]
print(C)
Output:
[3 5 7]
We first created the two arrays with the np.array()
method. We then stored the intersection of both arrays inside array C
with C = A[np.in1d(A, B)]
.
NumPy Intersection With the numpy.intersect1d()
Method in Python
We can also use the numpy.intersect1d()
method to find the intersection of two 1D arrays in Python. The numpy.intersect1d()
method takes the arrays and returns the sorted intersection in the form of another 1D array. See the following code example.
import numpy as np
A = np.array([2,3,5,7,11])
B = np.array([1,3,5,7,9])
C = np.intersect1d(A, B)
print(C)
Output:
[3 5 7]
We stored the intersection of arrays A
and B
inside array C
with the numpy.intersect1d()
method in the above code.
Both methods work just fine, but the np.intersect1d()
method is easier to use than the np.in1d()
method.