Set Operations (NumPy)

NumPy's set routines — intersect1d, union1d, setdiff1d, and in1d/isin — treat arrays as mathematical sets so you can compute intersections, unions, differences, and membership tests element-wise.

NumPy

np.intersect1d(a, b) returns the sorted values present in both arrays, np.union1d(a, b) returns every value from either, and np.setdiff1d(a, b) returns the values in a that are not in b. All return unique, sorted 1-D results, treating the inputs as sets.

For membership testing, np.isin(a, b) returns a boolean mask the same shape as a marking which of its elements appear in b — perfect for filtering rows whose key is in an allowed list. This is the vectorized equivalent of Python's 'in' operator across a whole array.

These functions deduplicate internally, so they pair naturally with np.unique. They are the array-level counterpart to Python's built-in set type, but they keep working in NumPy's fast, vectorized world.

Syntax

np.intersect1d(a, b)  |  np.union1d(a, b)  |  np.isin(a, b)

Examples

Python

import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([3, 4, 5])
print(np.intersect1d(a, b))

Output:

[3 4]

Learn it in a lesson

See also

Back to the Dictionary