NumPy Tutorial · NumPy ufunc

ufunc Set Operations

Learn all about ufunc Set Operations in this comprehensive tutorial.

5 min read advanced
  • A set in mathematics is a collection of unique elements.
  • We can use NumPy's unique() method to find unique elements from any array.
  • To find the unique values of two arrays, use the union1d() method.
  • To find only the values that are present in both arrays, use the intersect1d() method.
  • To find only the values in the first set that is NOT present in the seconds set, use the setdiff1d() method.
  • To find only the values that are NOT present in BOTH sets, use the setxor1d() method.

What is a Set

A set in mathematics is a collection of unique elements.

Sets are used for operations involving frequent intersection, union and difference operations.

Create Sets in NumPy

We can use NumPy's unique() method to find unique elements from any array. E.g. create a set array, but remember that the set arrays should only be 1-D arrays.

python

Finding Union

To find the unique values of two arrays, use the union1d() method.

python

Finding Intersection

To find only the values that are present in both arrays, use the intersect1d() method.

python
Note: Note: the intersect1d() method takes an optional argument assume_unique, which if set to True can speed up computation. It should always be set to True when dealing with sets.

Finding Difference

To find only the values in the first set that is NOT present in the seconds set, use the setdiff1d() method.

python
Note: Note: the setdiff1d() method takes an optional argument assume_unique, which if set to True can speed up computation. It should always be set to True when dealing with sets.

Finding Symmetric Difference

To find only the values that are NOT present in BOTH sets, use the setxor1d() method.

python
Note: Note: the setxor1d() method takes an optional argument assume_unique, which if set to True can speed up computation. It should always be set to True when dealing with sets.

Module quiz

2 questions
1

Which of the following is true about ufunc Set Operations?

2

What is the most common pitfall when working with ufunc Set Operations?

Answer all questions to submit.