How to remove duplicate elements from a NumPy array in Python

In this post, we are going to learn about how to remove duplicate elements from a NumPy array in Python.

NumPy in Python: NumPy which stands for Numerical Python is a library for the Python programming, adding support for large, multi-dimensional arrays and matrices. It is one of the popular modules in Python.

Here we have various useful mathematical functions to operate different operations with the arrays.

For removing elements we use an in-build function numpy.unique(parameters) or if we have imported numpy pakage we can directly write uniques.

To import NumPy in our program we can simply use this line: import numpy as np

Here are some examples below:

Example1: remove duplicate elements from a NumPy array in Python

import numpy as np
print(np.unique([1, 1, 2, 2, 3, 3])

Output:

[1 2 3]

Example2: Print unique values from a NumPy array in Python

import numpy as np

array = np.array([[2,4,3,3], [9,5,6,7], [13,3,4],[2,4,3,3]])
print(np.unique(array))

Output:

array([[2,4,3,3], [9,5,6,7], [13,3,4]])

Here we have imported the package so simply we write:

->unique

np.unique(array)

Explanation:

For example1 we have removed duplicate in a single array. The function unique check each element and discard the duplicate element.

Example2 illustrates that if we have nested array and two arrays have the same content then it removes one array so duplicates are removed.

You may also read:

Leave a Reply

Your email address will not be published. Required fields are marked *