Set Operations
Compare two arrays like mathematical sets: intersect1d (common), union1d (all), setdiff1d (only in first), setxor1d, and isin for membership masks.
The franchise changed its squad between 2023 and 2024. The coach asks: who was retained? Who is new? Who was released? Who played in either season? These are set questions, and NumPy answers each with one function.
Definition
Set operations treat 1D arrays as mathematical sets of values: intersection (in both), union (in either), difference (in the first but not the second) and symmetric difference (in exactly one). NumPy's
intersect1d,union1d,setdiff1dandsetxor1dreturn sorted, unique 1D arrays.np.isin(a, b)instead returns a boolean mask the same shape asa, True where an element ofais found inb.
- "1d" — these functions flatten their inputs and return 1D results.
- Sorted, unique — duplicates are dropped and the output is sorted (like
np.unique). - isin keeps shape and order — it doesn't return values, it returns a True/False for every element, so you can filter or count.
Syntax
python
np.intersect1d(ar1, ar2, assume_unique=False, return_indices=False)
np.union1d(ar1, ar2)
np.setdiff1d(ar1, ar2, assume_unique=False)
np.setxor1d(ar1, ar2, assume_unique=False)
np.isin(element, test_elements, assume_unique=False, invert=False)| Parameter | Meaning | Default |
|---|---|---|
ar1, ar2 | the two arrays to compare | required |
assume_unique | True if you know inputs have no duplicates (faster) | False |
return_indices | intersect1d only: also return where the common values sit in ar1 and ar2 | False |
element | array whose elements are checked (isin) | required |
test_elements | values to look for | required |
invert | True = return True where NOT found (same as ~np.isin(...)) | False |
Venn picture
text
2023 2024
( Dhoni ( Virat ) Gill )
( Warner ( Rohit ) Buttler )
( ( Bumrah ) )
setdiff intersect setdiff
(2023-2024) (2024-2023)
union = everything; setxor = both outer partsExample — squad changes
python
import numpy as np
squad_2023 = np.array(["Virat", "Rohit", "Dhoni", "Warner", "Bumrah"])
squad_2024 = np.array(["Virat", "Rohit", "Gill", "Bumrah", "Buttler"])
print(np.intersect1d(squad_2023, squad_2024)) # retained
print(np.union1d(squad_2023, squad_2024)) # played in either season
print(np.setdiff1d(squad_2023, squad_2024)) # released
print(np.setdiff1d(squad_2024, squad_2023)) # new signings
print(np.setxor1d(squad_2023, squad_2024)) # changed (in exactly one)text
['Bumrah' 'Rohit' 'Virat']
['Bumrah' 'Buttler' 'Dhoni' 'Gill' 'Rohit' 'Virat' 'Warner']
['Dhoni' 'Warner']
['Buttler' 'Gill']
['Buttler' 'Dhoni' 'Gill' 'Warner']How it works: every result is sorted alphabetically with no duplicates. setdiff1d is not symmetric — the order of arguments matters: setdiff1d(A, B) = "in A, not in B".
Example — isin: a mask that keeps order
python
print(np.isin(squad_2024, squad_2023))
print(squad_2024[~np.isin(squad_2024, squad_2023)])text
[ True True False True False]
['Gill' 'Buttler']How it works: isin answers "was this 2024 player also in 2023?" for each player, in the original order. Inverting with ~ and using it as a mask gives the new signings in squad order — unlike setdiff1d, which sorts.
Example — numbers, duplicates and return_indices
python
a = np.array([5, 3, 3, 1, 9])
b = np.array([3, 9, 9, 7])
print(np.intersect1d(a, b))
common, ia, ib = np.intersect1d(a, b, return_indices=True)
print(common, ia, ib)
print(np.union1d(a, b))
print(np.setdiff1d(a, b))
print(np.isin(a, b))
print(np.isin(a, b, invert=True))text
[3 9]
[3 9] [1 4] [0 1]
[1 3 5 7 9]
[1 5]
[False True True False True]
[ True False False True False]How it works: duplicates (3, 3 and 9, 9) collapse in the set results, but isin gives an answer for every element of a — both 3s are True. return_indices says 3 is first found at a[1]/b[0] and 9 at a[4]/b[1].
Example — isin as a filter
python
runs = np.array([72, 45, 88, 31, 64, 0, 103])
print(np.isin(runs, [0, 100, 103]))text
[False False False False False True True]isin replaces long chains like (runs == 0) | (runs == 100) | (runs == 103).
Comparison
| Function | Set meaning | Result | Python set equivalent |
|---|---|---|---|
np.intersect1d(A, B) | A ∩ B | sorted unique values | A & B |
np.union1d(A, B) | A ∪ B | sorted unique values | A | B |
np.setdiff1d(A, B) | A − B | sorted unique values | A - B |
np.setxor1d(A, B) | A △ B | sorted unique values | A ^ B |
np.isin(A, B) | is each a in B? | boolean mask, shape of A | [x in B for x in A] |
Common mistakes
- ❌ Swapping the arguments of
setdiff1d. ✅setdiff1d(A, B)keeps what is in A only. - ❌ Expecting the original order from
intersect1d/setdiff1d. ✅ They sort; useA[np.isin(A, B)]to keep A's order (and duplicates). - ❌ Using Python
inon an array to test many values (x in arrchecks one value). ✅np.isin(values, arr)checks all at once. - ❌ Looking for
np.in1d. ✅ It was deprecated and removed in NumPy 2 — usenp.isin.
Interview tip
Q: How do you keep only the rows of a table whose team code is in an allowed list?
A: table[np.isin(team_codes, allowed)] — isin builds a boolean mask aligned with the rows, and the mask selects them. This is exactly what Pandas df[df["team"].isin(allowed)] does under the hood.
Key points to remember
- intersect1d = in both, union1d = in either, setdiff1d = in the first only, setxor1d = in exactly one.
- These set functions flatten inputs and return SORTED, UNIQUE 1D arrays.
- setdiff1d is not symmetric — setdiff1d(A, B) keeps values of A that are not in B.
- np.isin(a, b) returns a boolean mask the shape of a, preserving order and duplicates.
- Use a[np.isin(a, b)] or a[~np.isin(a, b)] to filter while keeping the original order.
- intersect1d(..., return_indices=True) also tells you where the common values sit in each input.
Try it yourself
Retained, released and new players
isin to filter in original order
Practice: compare two playing XIs
Revision Flashcards
Tap a card to flip it and see the answer.
