The Wayback Machine - https://web.archive.org/web/20240828110613/https://www.geeksforgeeks.org/find-unique-rows-in-a-numpy-array/
Open In App

Find unique rows in a NumPy array

Last Updated : 03 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will discuss how to find unique rows in a NumPy array. To find unique rows in a NumPy array we are using numpy.unique() function of NumPy library.

Syntax of np.unique() in Python

Syntax: numpy.unique()

Parameter:

  • ar: array
  • return_index: Bool, if True return the indices of the input array
  • return_inverse: Bool, if True return the indices of the input array
  • return_counts: Bool, if True return the number of times each unique item appeared in the input array
  • axis: int or none, defines the axis to operate on

Examples to get unique rows in a NumPy array

Example 1:

Get unique rows from complete 2D-array.

Python3




# import library
import numpy as np
 
# Create a 2D numpy array
arr2D = np.array([[11, 11, 12, 11],
                     [13, 11, 12, 11],
                     [16, 11, 12, 11],
                     [11, 11, 12, 11]])
 
print('Original Array :' ,
      arr2D, sep = '\n')
 
uniqueRows = np.unique(arr2D)
                        
 
# print the output result
print('Unique Rows:',
      uniqueRows, sep = '\n')


Output:

Original Array :
[[11 11 12 11]
 [13 11 12 11]
 [16 11 12 11]
 [11 11 12 11]]
Unique Rows:
[11 12 13 16]

Example 2:

Get unique rows from complete 2D-array by passing axis = 0 in unique function along with 2D-array. You will notice that rows 1 and 4 are the same hence one of the columns is excluded.

Python3




# import library
import numpy as np
 
# Create a 2D numpy array
arr2D = np.array([[11, 11, 12, 11],
                     [13, 11, 12, 11],
                     [16, 11, 12, 11],
                     [11, 11, 12, 11]])
 
uniqueRows = np.unique(arr2D, axis=0)
                        
 
# print the output result
print('Unique Rows:',
      uniqueRows, sep = '\n')


Output:

Unique Rows:
[[11 11 12 11]
 [13 11 12 11]
 [16 11 12 11]]

Example 3:

Get unique rows from complete 2D-array by passing axis=1 in unique function along with 2D-array. You will notice that columns 1 and 4 are the same hence one of the columns is excluded.

Python3




# import library
import numpy as np
 
# Create a 2D numpy array
arr2D = np.array([[11, 11, 12, 11],
                     [13, 11, 12, 11],
                     [16, 11, 12, 11],
                     [11, 11, 12, 11]])
 
uniqueRows = np.unique(arr2D, axis=1)
                        
 
# print the output result
print('Unique Rows:',
      uniqueRows, sep = '\n')


Output:

Unique Rows:
[[11 11 12]
 [11 13 12]
 [11 16 12]
 [11 11 12]]

Example 4:

Returning the index of unique elements.

Python3




# import library
import numpy as np
 
# Create a 2D numpy array
arr2D = np.array([[11, 11, 12, 11],
                     [13, 11, 12, 11],
                     [16, 11, 12, 11],
                     [11, 11, 12, 11]])
 
uniqueRows = np.unique(arr2D, return_index=True)
                        
 
# print the output result
print('Unique Rows:',
      uniqueRows, sep = '\n')


Output:

Unique Rows:
(array([11, 12, 13, 16]), array([0, 2, 4, 8], dtype=int64))

Example 5:

In this output, a ndarray will be shown that contains the indices to reconstruct the original array from the unique array.

Python3




# import library
import numpy as np
 
# Create a 2D numpy array
arr2D = np.array([[11, 11, 12, 11],
                     [13, 11, 12, 11],
                     [16, 11, 12, 11],
                     [11, 11, 12, 11]])
 
uniqueRows = np.unique(arr2D, return_inverse=True)
                        
 
# print the output result
print('Unique Rows:',
      uniqueRows, sep = '\n')


Output:

Unique Rows:
(array([11, 12, 13, 16]), array([0, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 0, 0, 1, 0], dtype=int64))


Previous Article
Next Article

Similar Reads

NumPy ndarray.__abs__() | Find Absolute Value of Elements in NumPy Array
The ndarray.__abs__() method returns the absolute value of every element in the NumPy array. It is automatically invoked when we use Python's built-in method abs() on a NumPy array. Example C/C++ Code import numpy as np gfg = np.array([1.45, 2.32, 3.98, 4.41, 5.55, 6.12]) print(gfg.__abs__()) Output[ 1 2 3 4 5 6] SyntaxSyntax: ndarray.__abs__() Ret
1 min read
NumPy ndarray.transpose() Method | Find Transpose of the NumPy Array
The ndarray.transpose() function returns a view of the array with axes transposed. For a 1-D array, this has no effect, as a transposed vector is simply the same vector.For a 2-D array, this is a standard matrix transpose.For an n-D array, if axes are given, their order indicates how the axes are permuted. If axes are not provided and arr.shape = (
2 min read
Find the number of rows and columns of a given matrix using NumPy
The shape attribute of a NumPy array returns a tuple representing the dimensions of the array. For a two-dimensional array, the shape tuple contains two values: the number of rows and the number of columns. In this article, let's discuss methods used to find dimensions of the matrix. How to Find the Number of Rows and Columns of a Matrix?We can fin
2 min read
NumPy Array Sorting | How to sort NumPy Array
Sorting an array is a very important step in data analysis as it helps in ordering data, and makes it easier to search and clean. In this tutorial, we will learn how to sort an array in NumPy. You can sort an array in NumPy: Using np.sort() functionin-line sortsorting along different axesUsing np.argsort() functionUsing np.lexsort() functionUsing s
4 min read
How to delete last N rows from Numpy array?
In this article, we will discuss how to delete the last N rows from the NumPy array. Method 1: Using Slice Operator Slicing is an indexing operation that is used to iterate over an array. Syntax: array_name[start:stop] where start is the start is the index and stop is the last index. We can also do negative slicing in Python. It is denoted by the b
4 min read
How to access different rows of a multidimensional NumPy array?
Let us see how to access different rows of a multidimensional array in NumPy. Sometimes we need to access different rows of multidimensional NumPy array-like first row, the last two rows, and even the middle two rows, etc. In NumPy , it is very easy to access any rows of a multidimensional array. All we need to do is Slicing the array according to
3 min read
How to Remove rows in Numpy array that contains non-numeric values?
Many times we have non-numeric values in NumPy array. These values need to be removed, so that array will be free from all these unnecessary values and look more decent. It is possible to remove all rows containing Nan values using the Bitwise NOT operator and np.isnan() function. Example 1: C/C++ Code # Importing Numpy module import numpy as np #
2 min read
How to remove array rows that contain only 0 using NumPy?
Numpy library provides a function called numpy.all() that returns True when all elements of n-d array passed to the first parameter are True else it returns False. Thus, to determine the entire row containing 0's can be removed by specifying axis=1. It will traverse each row and will check for the condition given in first parameter. Example: data=[
2 min read
How to randomly select rows of an array in Python with NumPy ?
In this article, we will see two different methods on how to randomly select rows of an array in Python with NumPy. Let's see different methods by which we can select random rows of an array: Method 1: We will be using the function shuffle(). The shuffle() function shuffles the rows of an array randomly and then we will display a random row of the
2 min read
How to delete multiple rows of NumPy array ?
NumPy is the Python library that is used for working with arrays. In Python there are lists which serve the purpose of arrays but they are slow. Therefore, NumPy is there to provide us with the array object that is much faster than the traditional Python lists. The reason for them being faster is that they store arrays at one continuous place in me
3 min read
How to remove rows from a Numpy array based on multiple conditions ?
In this article, we will learn how to remove rows from a NumPy array based on multiple conditions. For doing our task, we will need some inbuilt methods provided by the NumPy module which are as follows: np.delete(ndarray, index, axis): Delete items of rows or columns from the NumPy array based on given index conditions and axis specified, the para
3 min read
How to Swap Two Rows in a NumPy Array
One common task you might encounter when working with NumPy arrays is the need to swap two rows. Swapping rows can be essential in data preprocessing, reshaping data, or reordering data to perform specific analyses in Python. In this article, we will explore different methods to swap two rows in a NumPy array. In this article, we will see how to sw
4 min read
How to count the frequency of unique values in NumPy array?
Let's see How to count the frequency of unique values in the NumPy array. Python’s Numpy library provides a numpy.unique() function to find the unique elements and their corresponding frequency in a NumPy array. numpy.unique() Syntax Syntax: numpy.unique(arr, return_counts=False) Return: Sorted unique elements of an array with their corresponding f
4 min read
NumPy| How to get the unique elements of an Array
To find unique elements of an array we use the numpy.unique() method of the NumPy library in Python. It returns unique elements in a new sorted array. Example: C/C++ Code import numpy as np arr = np.array([1, 2, 3, 1, 4, 5, 2, 5]) unique_elements = np.unique(arr) print(unique_elements) Output: [1 2 3 4 5]SyntaxSyntax: np.unique(ar, return_index=Fal
2 min read
Python | Print unique rows in a given boolean matrix using Set with tuples
Given a binary matrix, print all unique rows of the given matrix. Order of row printing doesn't matter. Examples: Input: mat = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 1, 1, 0, 0]] Output: (1, 1, 1, 0, 0) (0, 1, 0, 0, 1) (1, 0, 1, 1, 0) We have existing solution for this problem please refer link. We can solve this problem in python
2 min read
NumPy ndarray.tolist() Method | Convert NumPy Array to List
The ndarray.tolist() method converts a NumPy array into a nested Python list. It returns the array as an a.ndim-levels deep nested list of Python scalars. Data items are converted to the nearest compatible built-in Python type. Example C/C++ Code import numpy as np gfg = np.array([1, 2, 3, 4, 5]) print(gfg.tolist()) Output[1, 2, 3, 4, 5] SyntaxSynt
1 min read
NumPy ndarray.size() Method | Get Number of Elements in NumPy Array
The ndarray.size() method returns the number of elements in the NumPy array. It works the same as np.prod(a.shape), i.e., the product of the dimensions of the array. Example C/C++ Code import numpy as np arr = np.zeros((3, 4, 2), dtype = np.complex128) gfg = arr.size print (gfg) Output : 24Syntax Syntax: numpy.ndarray.size(arr) Parameters arr : [ar
1 min read
NumPy ndarray.__ilshift__() | Shift NumPy Array Elements to Left
The ndarray.__ilshift__() method is an in-place left-shift operation. It shifts elements in the array to the left of the number of positions specified. Example C/C++ Code import numpy as np gfg = np.array([1, 2, 3, 4, 5]) # applying ndarray.__ilshift__() method print(gfg.__ilshift__(2)) Output[ 4 8 12 16 20] SyntaxSyntax: ndarray.__ilshift__($self,
1 min read
NumPy ndarray.__irshift__() | Shift NumPy Array Elements to Right
The ndarray.__irshift__() method returns a new array where each element is right-shifted by the value that is passed as a parameter. Example C/C++ Code import numpy as np gfg = np.array([1, 2, 3, 4, 5]) # applying ndarray.__irshift__() method print(gfg.__irshift__(2)) Output[0 0 0 1 1] SyntaxSyntax: ndarray.__irshift__($self, value, /) Parameter se
1 min read
NumPy ndarray.imag() Method | Get Imaginary Part in NumPy Array
The ndarray.imag() method returns the imaginary part of the complex number in the NumPy array. Note: Remember resulting data type for the imaginary value is 'float64'. Example C/C++ Code # import the important module in python import numpy as np # make an array with numpy gfg = np.array([1 + 2j, 2 + 3j]) # applying ndarray.imag() method geeks = np.
1 min read
NumPy - Filtering rows by multiple conditions
In this article, we will discuss how to filter rows of NumPy array by multiple conditions. Before jumping into filtering rows by multiple conditions, let us first see how can we apply filter based on one condition. There are basically two approaches to do so: Method 1: Using mask array The mask function filters out the numbers from array arr which
4 min read
Delete rows and columns of NumPy ndarray
In this article, we will discuss how to delete the specified rows and columns in an n-dimensional array. We are going to delete the rows and columns using numpy.delete() method. Syntax: numpy.delete(array_name, obj, axis=None) Let's discuss with the help of some examples: Example 1: Program to create a 2-dimensional array (3 rows and 4 columns) wit
3 min read
How to Set Axis for Rows and Columns in NumPy ?
In this article, we are going to see how to set the axis for rows and columns in NumPy. Functions Usednp.array(object): to create a NumPy array, the object is the parameter that contains the arraynp.reshape(rows, columns): to reshape the array into the specified number of rows and columns. Here in the below examples, we have given -1 in place of ro
3 min read
Python | Numpy np.unique() method
With the help of np.unique() method, we can get the unique values from an array given as parameter in np.unique() method. Syntax : np.unique(Array) Return : Return the unique of an array. Example #1 : In this example we can see that by using np.unique() method, we are able to get the unique values from an array by using this method. # import numpy
1 min read
Python | Numpy numpy.resize()
With the help of Numpy numpy.resize(), we can resize the size of an array. Array can be of any shape but to resize it we just need the size i.e (2, 2), (2, 3) and many more. During resizing numpy append zeros if values at a particular place is missing. Parameters: new_shape : [tuple of ints, or n ints] Shape of resized array refcheck : [bool, optio
2 min read
Python | Numpy numpy.transpose()
With the help of Numpy numpy.transpose(), We can perform the simple function of transpose within one line by using numpy.transpose() method of Numpy. It can transpose the 2-D arrays on the other hand it has no effect on 1-D arrays. This method transpose the 2-D numpy array. Parameters: axes : [None, tuple of ints, or n ints] If anyone wants to pass
2 min read
Python | Numpy numpy.ndarray.__lt__()
With the help of numpy.ndarray.__lt__() method of Numpy, We can find that which element in an array is less than the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__lt__($self, value, /) Return: self<value Example #1 : In this example we can see that
1 min read
Python | Numpy numpy.ndarray.__gt__()
With the help of numpy.ndarray.__gt__() method of Numpy, We can find that which element in an array is greater then the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__gt__($self, value, /) Return: self>value Example #1 : In this example we can see th
1 min read
Python | Numpy numpy.ndarray.__le__()
With the help of numpy.ndarray.__le__() method of Numpy, We can find that which element in an array is less than or equal to the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__le__($self, value, /) Return: self<=value Example #1 : In this example we
1 min read
Python | Numpy numpy.ndarray.__ge__()
With the help of numpy.ndarray.__ge__() method of Numpy, We can find that which element in an array is greater then or equal to the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__ge__($self, value, /) Return: self>=value Example #1 : In this example
1 min read
Practice Tags :