Introduction
We use np.intersect1d() to find common items between two lists or arrays. It helps us see what values appear in both sets.
Jump into concepts and practice - no test required
We use np.intersect1d() to find common items between two lists or arrays. It helps us see what values appear in both sets.
np.intersect1d(array1, array2, assume_unique=False, return_indices=False)
array1 and array2 are the two arrays to compare.
assume_unique=True speeds up the function if you know arrays have unique elements.
import numpy as np arr1 = np.array([1, 2, 3, 4]) arr2 = np.array([3, 4, 5, 6]) common = np.intersect1d(arr1, arr2) print(common)
import numpy as np arr1 = np.array(['apple', 'banana', 'cherry']) arr2 = np.array(['banana', 'dragonfruit', 'apple']) common = np.intersect1d(arr1, arr2) print(common)
This program finds which students are in both classes by comparing their ID numbers.
import numpy as np # Two lists of student IDs from two classes class_a = np.array([101, 102, 103, 104, 105]) class_b = np.array([104, 105, 106, 107]) # Find students in both classes common_students = np.intersect1d(class_a, class_b) print("Students in both classes:", common_students)
The result is always sorted in ascending order.
If you want to know the positions of common elements in the original arrays, use return_indices=True.
np.intersect1d() finds common elements between two arrays.
It works with numbers, strings, or any comparable data.
The output is a sorted array of shared values.
np.intersect1d() do in NumPy?np.intersect1d() is designed to find elements that appear in both input arrays.np.intersect1d().a and b using NumPy?np.intersect1d() and it takes two arrays as separate arguments.import numpy as np x = np.array([3, 1, 4, 1, 5]) y = np.array([5, 9, 2, 6, 5]) print(np.intersect1d(x, y))
import numpy as np arr1 = [1, 2, 3] arr2 = [2, 3, 4] result = np.intersect1d(arr1 arr2) print(result)
np.intersect1d(arr1 arr2) is missing a comma between the two arguments.store1 = np.array([101, 102, 103, 104, 105]) store2 = np.array([104, 105, 106, 107])
np.intersect1d()?np.intersect1d(store1, store2) returns sorted common elements. Other options return union, difference, or concatenation, which are not correct here.