NumPy - Find the unique elements of an array that are not present in another

By IncludeHelp Last updated : January 2, 2024

Problem statement

Given two NumPy arrays, write a Python program to find the unique elements of an array that are not present in another array.

Finding the unique elements of an array that are not present in another

For this purpose, you can use the numpy.setdiff1d() method which returns the unique values in an array that are not in another array.

Below is the syntax of numpy.setdiff1d() method:

numpy.setdiff1d(array1, array2, assume_unique=False)

Let us understand with an example.

Python code to find the unique elements of an array that are not present in another

# Import NumPy module
import numpy as np

# Creating two NumPy arrays
arr1 = np.array([50, 100, 200, 500, 50])
arr2 = np.array([50, 100, 400])

# Printing the arrays
print("Array 1 (arr1):\n", arr1)
print("Array 2 (arr1):\n", arr2)

# Unique elements of an array
# that are not present in another
# using the setdiff1d() method
result = np.setdiff1d(arr1, arr2)

# Printing the result
print("The unique elements are:\n", result)

Output

The output of the above example is:

Array 1 (arr1):
 [ 50 100 200 500  50]
Array 2 (arr1):
 [ 50 100 400]
The unique elements are:
 [200 500]

To understand the above program, you should have the basic knowledge of the following Python topics:

Python NumPy Programs »

All Python NumPy Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.