Set operations help you find common or different items between groups of data. For structured data, this means comparing rows with multiple fields.
Set operations on structured data in NumPy
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
NumPy
numpy.intersect1d(array1, array2) numpy.union1d(array1, array2) numpy.setdiff1d(array1, array2) numpy.setxor1d(array1, array2)
These functions work on 1D arrays, so for structured data, you often view rows as single items.
Structured arrays have named fields, so you can compare rows as tuples.
Examples
NumPy
import numpy as np # Define two structured arrays arr1 = np.array([(1, 'A'), (2, 'B'), (3, 'C')], dtype=[('id', 'i4'), ('label', 'U1')]) arr2 = np.array([(2, 'B'), (3, 'C'), (4, 'D')], dtype=arr1.dtype) # Find common rows common = np.intersect1d(arr1, arr2) print(common)
NumPy
unique_to_arr1 = np.setdiff1d(arr1, arr2)
print(unique_to_arr1)NumPy
all_unique = np.union1d(arr1, arr2)
print(all_unique)NumPy
diff = np.setxor1d(arr1, arr2)
print(diff)Sample Program
This program shows how to use set operations on structured arrays to find common, unique, combined, and different rows.
NumPy
import numpy as np # Create two structured arrays with fields 'id' and 'score' arr1 = np.array([(1, 90), (2, 85), (3, 88)], dtype=[('id', 'i4'), ('score', 'i4')]) arr2 = np.array([(2, 85), (3, 88), (4, 92)], dtype=arr1.dtype) # Find common rows common = np.intersect1d(arr1, arr2) print('Common rows:') print(common) # Find rows unique to arr1 unique_arr1 = np.setdiff1d(arr1, arr2) print('\nRows unique to arr1:') print(unique_arr1) # Combine all unique rows all_unique = np.union1d(arr1, arr2) print('\nAll unique rows combined:') print(all_unique) # Find rows in either arr1 or arr2 but not both diff = np.setxor1d(arr1, arr2) print('\nRows in either arr1 or arr2 but not both:') print(diff)
Important Notes
Structured arrays compare rows as whole records, so all fields must match to be considered equal.
Set operations return sorted results by default.
If you want to compare only some fields, extract those fields first.
Summary
Set operations help compare structured data by rows.
Use numpy functions like intersect1d, union1d, setdiff1d, and setxor1d.
These operations are useful to find common, unique, or different records.
Practice
1. What does the
numpy.intersect1d function do when applied to two structured arrays?easy
Solution
Step 1: Understand intersect1d purpose
numpy.intersect1dreturns elements common to both input arrays.Step 2: Apply to structured arrays
For structured arrays, it compares rows and returns those present in both arrays.Final Answer:
Finds the common rows present in both arrays -> Option CQuick Check:
Intersection = common rows [OK]
Hint: Intersect means common elements only [OK]
Common Mistakes:
- Confusing intersect1d with union1d
- Thinking it returns unique rows from one array only
- Assuming it returns rows exclusive to one array
2. Which of the following is the correct syntax to find the union of two structured numpy arrays
a and b?easy
Solution
Step 1: Recall numpy union function
The correct function to find union isnumpy.union1d.Step 2: Check syntax correctness
The syntax isnumpy.union1d(a, b)with two arguments.Final Answer:
numpy.union1d(a, b) -> Option DQuick Check:
Use union1d for union operation [OK]
Hint: Use union1d, not union or setunion [OK]
Common Mistakes:
- Using nonexistent functions like union or setunion
- Passing arguments incorrectly with bitwise operators
- Confusing union1d with intersect1d
3. Given two structured arrays:
What is the output?
a = np.array([(1, 'A'), (2, 'B'), (3, 'C')], dtype=[('id', int), ('val', 'U1')])
b = np.array([(2, 'B'), (4, 'D')], dtype=[('id', int), ('val', 'U1')])
print(np.setdiff1d(a, b))What is the output?
medium
Solution
Step 1: Understand setdiff1d behavior
np.setdiff1d(a, b)returns rows inanot inb.Step 2: Compare rows of a and b
Rows (2, 'B') is common, so excluded. Remaining are (1, 'A') and (3, 'C').Final Answer:
[(1, 'A') (3, 'C')] -> Option AQuick Check:
Difference = rows only in a [OK]
Hint: Setdiff1d returns items only in first array [OK]
Common Mistakes:
- Including common rows in output
- Confusing setdiff1d with union1d or intersect1d
- Expecting output from second array instead
4. Consider this code snippet:
It raises an error. What is the likely cause?
a = np.array([(1, 'X'), (2, 'Y')], dtype=[('id', int), ('val', 'U1')])
b = np.array([(2, 'Y'), (3, 'Z')], dtype=[('id', int), ('val', 'U2')])
result = np.setxor1d(a, b)
print(result)It raises an error. What is the likely cause?
medium
Solution
Step 1: Check dtype compatibility
For set operations on structured arrays, dtypes and field order must match exactly.Step 2: Identify cause of error
If dtypes differ or field order differs, setxor1d raises an error.Final Answer:
Structured arrays have different dtypes or field order -> Option BQuick Check:
Matching dtypes needed for set operations [OK]
Hint: Ensure structured arrays have identical dtypes [OK]
Common Mistakes:
- Assuming setxor1d can't handle structured arrays
- Forgetting to check dtype and field order
- Thinking arrays must be sorted first
5. You have two structured arrays representing employee records:
You want to find employees who are in either list but not both (exclusive employees). Which numpy function and code will give the correct result?
emp1 = np.array([(101, 'Alice'), (102, 'Bob'), (103, 'Carol')], dtype=[('id', int), ('name', 'U10')])
emp2 = np.array([(102, 'Bob'), (104, 'Dave')], dtype=[('id', int), ('name', 'U10')])You want to find employees who are in either list but not both (exclusive employees). Which numpy function and code will give the correct result?
hard
Solution
Step 1: Understand exclusive elements
Exclusive employees are those in one array but not both, which is the symmetric difference.Step 2: Identify correct numpy function
np.setxor1dreturns elements in either array but not in both.Final Answer:
np.setxor1d(emp1, emp2) -> Option AQuick Check:
Symmetric difference = setxor1d [OK]
Hint: Use setxor1d for exclusive elements [OK]
Common Mistakes:
- Using union1d which includes all elements
- Using intersect1d which finds common only
- Using setdiff1d which finds only one-sided difference
