Set operations help us find common or different items between groups of data easily. They make comparing lists or arrays simple and fast.
0
0
Why set operations matter in NumPy
Introduction
Finding common customers between two sales lists
Identifying unique products sold in different stores
Removing duplicate entries from a dataset
Checking which students attended both classes
Comparing survey answers from two groups
Syntax
NumPy
numpy.intersect1d(array1, array2) numpy.union1d(array1, array2) numpy.setdiff1d(array1, array2) numpy.setxor1d(array1, array2)
These functions work on 1D arrays and return sorted unique values.
Use intersect1d for common items, union1d for all unique items combined, setdiff1d for items in first array not in second, and setxor1d for items in either array but not both.
Examples
This finds numbers present in both arrays.
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)
This combines all unique numbers from both arrays.
NumPy
union = np.union1d(arr1, arr2)
print(union)This finds numbers in the first array but not in the second.
NumPy
diff = np.setdiff1d(arr1, arr2)
print(diff)This finds numbers in either array but not in both.
NumPy
xor = np.setxor1d(arr1, arr2)
print(xor)Sample Program
This program compares product IDs sold in two stores using set operations to find common, all, unique to one store, and exclusive products.
NumPy
import numpy as np # Two lists of product IDs sold in two stores store1 = np.array([101, 102, 103, 104, 105]) store2 = np.array([104, 105, 106, 107]) # Products sold in both stores common_products = np.intersect1d(store1, store2) print("Common products:", common_products) # All unique products sold all_products = np.union1d(store1, store2) print("All products:", all_products) # Products only in store1 only_store1 = np.setdiff1d(store1, store2) print("Only in store1:", only_store1) # Products sold in one store but not both exclusive_products = np.setxor1d(store1, store2) print("Exclusive products:", exclusive_products)
OutputSuccess
Important Notes
Set operations automatically remove duplicates and sort the results.
These operations are very useful for cleaning and comparing data quickly.
Summary
Set operations help compare and combine data easily.
They find common, unique, or different items between arrays.
NumPy provides simple functions to do these tasks fast.