NumPy Set Operations

🔢 NumPy Set Operations

NumPy provides a set of functions to perform set-like operations on arrays. These operations are element-wise, unique, and sorted by default, similar to Python sets but optimized for arrays.


 1. Unique Elements (np.unique)


 

  • Returns sorted unique elements

  • Can also return indices, counts:



 2. Intersection (np.intersect1d)


 

  • Elements present in both arrays


3. Union (np.union1d)


  • Combines all elements from both arrays without duplicates


4. Set Difference (np.setdiff1d)


  • Returns elements present in first array but not in second


5. Symmetric Difference / XOR (np.setxor1d)


  • Returns elements in arr1 or arr2 but not in both


6. Membership Testing (np.in1d)


  • Checks element-wise if array1 elements are in array2

  • Returns boolean array


 7. Notes & Tips

  • All results are sorted

  • Ideal for finding unique items, overlaps, and differences

  • Useful in data cleaning, analysis, and comparisons


🎯 Practice Exercises

  1. Find unique elements of [1,2,2,3,3,4,5,5].

  2. Find intersection and union of [1,2,3,4] and [3,4,5,6].

  3. Find difference and symmetric difference of the same arrays.

  4. Test membership of [1,2,3] in [2,3,4].

You may also like...