30 Mar Intersection of Numpy Arrays
If you want to get the intersection of two arrays, use the intersect1d() method in Numpy. Intersection means finding common elements between two arrays. In this lesson, we will see some examples:
- Find the intersection between two arrays
- Finding intersection sorts the resultant array
- Find the intersection between two arrays with different elements
Find the intersection between two arrays
The intersect1d() method finds the intersection between two arrays. Let us see an example. We have created two integer arrays. We will find the intersection between these arrays:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import numpy as np # Create two arrays n1 = np.array([5, 10, 15, 20]) n2 = np.array([5, 15, 30, 40]) print("Iterating array1...") for a in n1: print(a) print("\nIterating array2...") for a in n2: print(a) # Find intersection using the intersect1d() method resarr = np.intersect1d(n1, n2) print("\nIntersection = \n", resarr) |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Iterating array1... 5 10 15 20 Iterating array2... 5 15 30 40 Intersection = [ 5 15] |
Finding intersection sorts the resultant array
The intersect1d() method finds the intersection and also sorts the result. Let us see an example. We have created two unsorted integer arrays. We will find the intersection between these arrays that will display a sorted result:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import numpy as np # Create two arrays n1 = np.array([10, 50, 30, 20, 60, 40]) n2 = np.array([80, 50, 90, 100, 40, 70]) print("Iterating array1...") for a in n1: print(a) print("\nIterating array2...") for a in n2: print(a) # Find the intersection resarr = np.intersect1d(n1, n2) print("\nIntersection (sorted result) = \n", resarr) |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
Iterating array1... 10 50 30 20 60 40 Iterating array2... 80 50 90 100 40 70 Intersection (sorted result) = [40 50] |
Find the intersection between two arrays with different elements
Let us see what will happen when we find the intersection between two arrays with different elements. Therefore, both the arrays do not have even a single element similar.
Let us see the result:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import numpy as np # Create two arrays n1 = np.array([10, 20, 30, 40, 50]) n2 = np.array([60, 70, 80, 90, 100]) print("Iterating array1...") for a in n1: print(a) print("\nIterating array2...") for a in n2: print(a) # Find the intersection resarr = np.intersect1d(n1, n2) print("\nIntersection (different elements) = \n", resarr) |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Iterating array1... 10 20 30 40 50 Iterating array2... 60 70 80 90 100 Intersection (different elements) = [] |
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments