Find unique rows in a NumPy array

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 : numpy.unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)

Now, let’s see an example:

Example 1:

Python3



filter_none

edit
close

play_arrow

link
brightness_4
code

# 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')
  
# Get unique rows from
# complete 2D-array by 
# passing axis = 0 in 
# unique function along
# with 2D-array
uniqueRows = np.unique(arr2D, 
                       axis = 0)
  
# print the output result
print('Unique Rows:',
      uniqueRows, sep = '\n')

chevron_right


Output:

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

Example 2:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# import library
import numpy as np
  
# create 2d numpy array
array = np.array([[1, 2, 3, 4],
                  [3, 2, 4, 1],
                  [6, 8, 1, 2]])
  
print("Original array: \n",
      array)
  
# Get unique rows from
# complete 2D-array by 
# passing axis = 0 in 
# unique function along
# with 2D-array
uniqueRows = np.unique(array, 
                       axis = 0)
  
# print the output result
print('Unique Rows :',
      uniqueRows,
      sep = '\n')

chevron_right


Output:

Original array: 
 [[1 2 3 4]
 [3 2 4 1]
 [6 8 1 2]]
Unique Rows :
[[1 2 3 4]
 [3 2 4 1]
 [6 8 1 2]]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.