TExcelTAD
Home › NumPy › ufunc Set Operations

ufunc Set Operations

A mathematical set is a collection of unique elements: no duplicates, and the order doesn't matter. Python has a built-in set type, but when your data is already in NumPy arrays, NumPy's set functions are faster and return sorted arrays.

Function Result
np.unique(a) the distinct values of a, sorted
np.union1d(a, b) values in a or b
np.intersect1d(a, b) values in both
np.setdiff1d(a, b) values in a but not in b
np.setxor1d(a, b) values in exactly one of them
np.isin(a, b) boolean mask: is each element of a in b?

The 1d in the names is a reminder that these functions treat their inputs as flat 1-D arrays.

Creating a set: np.unique

python · try it yourself
import numpy as np

visits = np.array(["home", "shop", "home", "blog", "shop", "home"])
print(np.unique(visits))

values, counts = np.unique(visits, return_counts=True)
print(dict(zip(values.tolist(), counts.tolist())))

ids = np.array([7, 3, 7, 1, 3, 9])
uniq, first_pos = np.unique(ids, return_index=True)
print(uniq, first_pos)       # where each value first appeared
['blog' 'home' 'shop']
{'blog': 1, 'home': 3, 'shop': 2}
[1 3 7 9] [3 1 0 5]

return_counts is a quick frequency table; return_index gives the position of the first occurrence of each distinct value.

Union and intersection

python · try it yourself
import numpy as np

monday = np.array([101, 102, 105, 108])     # customer ids who visited
tuesday = np.array([102, 103, 108, 110])

print("visited on either day:", np.union1d(monday, tuesday))
print("visited on both days: ", np.intersect1d(monday, tuesday))
visited on either day: [101 102 103 105 108 110]
visited on both days:  [102 108]

When you know both inputs are already unique, pass assume_unique=True to intersect1d (and setdiff1d, setxor1d) to skip the internal de-duplication and save time.

Difference and symmetric difference

setdiff1d(a, b) keeps what is in a only. The order matters: setdiff1d(a, b) is not setdiff1d(b, a). setxor1d keeps elements that belong to one set but not to both:

python · try it yourself
import numpy as np

monday = np.array([101, 102, 105, 108])
tuesday = np.array([102, 103, 108, 110])

print("only Monday: ", np.setdiff1d(monday, tuesday))
print("only Tuesday:", np.setdiff1d(tuesday, monday))
print("exactly one day:", np.setxor1d(monday, tuesday))
only Monday:  [101 105]
only Tuesday: [103 110]
exactly one day: [101 103 105 110]

Membership: np.isin

np.isin(a, b) returns a mask the same shape as a, so you can filter with it. invert=True flips it:

python · try it yourself
import numpy as np

orders = np.array(["pen", "ink", "lamp", "desk", "pen", "chair"])
in_stock = np.array(["pen", "lamp", "chair"])

print(np.isin(orders, in_stock))
print("can ship:   ", orders[np.isin(orders, in_stock)])
print("backordered:", orders[np.isin(orders, in_stock, invert=True)])
[ True False  True False  True  True]
can ship:    ['pen' 'lamp' 'pen' 'chair']
backordered: ['ink' 'desk']

Unlike the other functions, isin keeps duplicates and the original order, because it answers a question about every element instead of building a set.

Example: comparing two class lists

python · try it yourself
import numpy as np

math_club = np.array(["Ada", "Ben", "Cy", "Dee", "Eli"])
chess_club = np.array(["Cy", "Eli", "Fay", "Gus"])

both = np.intersect1d(math_club, chess_club)
everyone = np.union1d(math_club, chess_club)
print(f"{len(everyone)} students in total, {len(both)} in both clubs: {both}")
print("math only:", np.setdiff1d(math_club, chess_club))
overlap = len(both) / len(everyone)
print(f"overlap (Jaccard index): {overlap:.2f}")
7 students in total, 2 in both clubs: ['Cy' 'Eli']
math only: ['Ada' 'Ben' 'Dee']
overlap (Jaccard index): 0.29

The Jaccard index (size of intersection ÷ size of union) is a common similarity measure for sets, used for comparing documents, tags and recommendations.

Test yourself

What does np.unique([3, 1, 3, 2, 1]) return?

  1. [3 1 2]
  2. [1 2 3]
  3. [3 1 3 2 1]
  4. 3

What is np.setdiff1d([1, 2, 3, 4], [2, 4, 6])?

  1. [6]
  2. [1 3]
  3. [1 3 6]
  4. [2 4]

Which function returns a boolean mask telling whether each element of a appears in b?

  1. np.intersect1d
  2. np.isin
  3. np.unique
  4. np.setxor1d