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
# 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' ) |
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
# 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' ) |
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]]