×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Find Unique Rows in a NumPy Array

In this tutorial, we will learn how to find the unique rows from a given multi-dimensional (2D) NumPy array? By Pranit Sharma Last updated : May 26, 2023

Problem Statement

Given a multi-dimensional (2D) NumPy array, we have to find its unique rows.

Finding unique rows in a NumPy array

The numpy.unique() method can be used to find the unique rows in a NumPy array. You can use this method with axis = 0 parameter to exclude the common rows. Consider the below statement for finding the unique rows:

np.unique(arr, axis=0)

Where, arr is a 2D NumPy array.

Let us understand with the help of an example,

Example 1: Find unique rows in a NumPy array

# Import NumPy
import numpy as np

# Creating 2D NumPy array
arr = np.array(
    [
        [1, 1, 1, 0, 0, 0],
        [0, 1, 1, 1, 0, 0],
        [0, 1, 1, 1, 0, 0],
        [1, 1, 1, 0, 0, 0],
        [1, 1, 1, 1, 1, 0],
    ]
)

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

# Finding unique rows
res = np.unique(arr, axis=0)

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

Output

Original array (arr):
 [[1 1 1 0 0 0]
 [0 1 1 1 0 0]
 [0 1 1 1 0 0]
 [1 1 1 0 0 0]
 [1 1 1 1 1 0]] 

Unique rows (res):
 [[0 1 1 1 0 0]
 [1 1 1 0 0 0]
 [1 1 1 1 1 0]]

Example 2: Find unique rows in a NumPy array

# Import NumPy
import numpy as np

# Creating 2D NumPy array
arr = np.array(
    [
        [10, 20, 30, 40, 50],
        [20, 30, 40, 50, 60],
        [30, 60, 40, 80, 90],
        [20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50],
    ]
)

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

# Finding unique rows
res = np.unique(arr, axis=0)

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

Output

Original array (arr):
 [[10 20 30 40 50]
 [20 30 40 50 60]
 [30 60 40 80 90]
 [20 30 40 50 60]
 [10 20 30 40 50]] 

Unique rows (res):
 [[10 20 30 40 50]
 [20 30 40 50 60]
 [30 60 40 80 90]]

Python NumPy Programs »

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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