0
0
NumPydata~5 mins

np.intersect1d() for intersection in NumPy

Choose your learning style9 modes available
Introduction

We use np.intersect1d() to find common items between two lists or arrays. It helps us see what values appear in both sets.

Finding common customers between two sales lists.
Checking shared tags between two groups of articles.
Comparing two exam answer sheets to find matching answers.
Identifying overlapping products in two store inventories.
Syntax
NumPy
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.

Examples
This finds numbers present in both arrays: 3 and 4.
NumPy
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)
Works with strings too, showing common fruits.
NumPy
import numpy as np

arr1 = np.array(['apple', 'banana', 'cherry'])
arr2 = np.array(['banana', 'dragonfruit', 'apple'])
common = np.intersect1d(arr1, arr2)
print(common)
Sample Program

This program finds which students are in both classes by comparing their ID numbers.

NumPy
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)
OutputSuccess
Important Notes

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.

Summary

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.