0 votes
in Python by
explain numpy.unique() in Python

1 Answer

0 votes
by

numpy.unique() in Python

The numpy.unique() function finds the unique elements of an array and returns the sorted unique elements for the specified array. 

Syntax

numpy.unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)

Parameter

ar : This parameter returns an Input array.If the aaray is not 1-D, this will be flattened.

return_index : This is an optional parameter which takes Boolean values. If Boolean value ‘True’ is passed, it returns the indices of the parameter ‘ar’ (along the specified axis, if provided, or in the flattened array) that result in the unique array.

return_inverse : If Boolean value ‘True’ is passed, it returns the indices of the unique array that can be used to reconstruct the parameter ‘ar’.

return_counts : If Boolean value ‘True’ is passed, it returns the number of times each unique item appears in ar.

axis : The axis parameter is used to operate on.

Return

This function returns the sorted unique elements of an array. There are three optional outputs in addition to the unique elements:

  • It returns the indices of the input array that give the unique values
  • the indices of the unique array that reconstructs the input array
  • the number of times each unique value derives up in the input array

Example 1

# Python program explaining
# numpy.unique() function
import numpy as np
inp_arr = np.array([5,8,6,2,7,5,2,8,12,5])
print ('Input array:')
print (inp_arr)
print ('\nUnique values for the Input array:' )
unq = np.unique(inp_arr)
print (unq)
print ('\nUnique array and Indices array:')
u,indices = np.unique(inp_arr, return_index = True)
print (indices)
print ('\nIndices of unique array:')
u,indices = np.unique(inp_arr,return_inverse = True)
print (u)
print ('Indices are:')
print (indices)
print ('\nReconstruct the original array using indices:')
print (u[indices])

Output

Input array:
[ 5  8  6  2  7  5  2  8 12  5]
Unique values for the Input array:
[ 2  5  6  7  8 12]
Unique array and Indices array:
[3 0 2 4 1 8]
Indices of unique array:
[ 2  5  6  7  8 12]
Indices are:
[1 4 2 0 3 1 0 4 5 1]
Reconstruct the original array using indices:
[ 5  8  6  2  7  5  2  8 12  5]

Related questions

0 votes
asked May 19, 2022 in Python by john ganales
0 votes
asked May 19, 2022 in Python by john ganales
...