How to Remove Duplicate Elements from NumPy Array?

Learn, how to remove duplicate elements from NumPy array in Python?
Submitted by Pranit Sharma, on January 24, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

Removing Duplicate Elements from NumPy Array

Suppose we are given a 2-dimensional NumPy array that contains some repeated rows and we need to remove these repeated rows.
Rows in NumPy are the different values that are aligned horizontally and also provide uniformity. Each row can have the same or different value. Rows are generally marked with the index number.

To remove a duplicate row, we will use numpy.unique() method. We will fetch each row in tuple form and pass it into this method as an argument. It will only return those rows which are not equal i.e., it will only return unique rows.

Let us understand with the help of an example,

Python code to remove duplicate elements from NumPy array

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([
    [1,8,3,3,4],
    [1,8,2,4,6],
    [1,8,9,9,4],
    [1,8,3,3,4]])

# Display original array
print("Original array:\n",arr,"\n")

# Removing duplicate rows
new = [tuple(row) for row in arr]
res = np.unique(new,axis=0)

# Display result
print("Result:\n",res,"\n")

Output:

Example: How to Remove Duplicate Elements from NumPy Array?

Python NumPy Programs »



ADVERTISEMENT
ADVERTISEMENT


What's New (MCQs)



Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.