How to find set difference between two Numpy arrays?

PythonNumpyServer Side ProgrammingProgramming

In this program, we will find the set difference of two numpy arrays. We will use the setdiff1d() function in the numpy library. This function takes two parameters: array1 and array2 and returns the unique values in array1 that are not in array2.


Step 1: Import numpy.
Step 2: Define two numpy arrays.
Step 3: Find the set difference between these arrays using the setdiff1d() function.
Step 4: Print the output.

Example Code

import numpy as np

array_1 = np.array([2,4,6,8,10,12])
print("Array 1: \n", array_1)

array_2 = np.array([4,8,12])
print("\nArray 2: \n", array_2)

set_diff = np.setdiff1d(array_1, array_2)
print("\nThe set difference between array_1 and array_2 is:\n",set_diff)


Array 1:
[ 2  4  6  8 10 12]
Array 2:
[ 4  8 12]
The set difference between array_1 and array_2 is:
[ 2  6 10]


Array 1 has elements 2, 6, and 10 which are not in Array 2. Hence [2 6 10] are is the set difference between the two arrays.

Published on 16-Mar-2021 15:03:23