In this chapter, we will discuss about NumPy unique. This function returns an array of unique elements in the input array. The function can be able to return a tuple of an array of unique values and an array of associated indices. The nature of the indices depends upon the type of return parameter in the function call.
numpy.unique(arr, return_index, return_inverse, return_counts)
Where,
Sr.No. | Parameter & Description |
---|---|
1 | arr, input array. It Will be flattened if the not 1-D array |
2 | return_indexIf True returns the indices of elements in the input array |
3 | return_inverseIf True returns the indices of a unique array, which can be used to reconstruct the input array |
4 | return_countsIf True returns the number of times the element in a unique array appears in the original array |
Example Of NumPy unique
import numpy as np a = np.array([5,2,6,2,7,5,6,8,2,9]) print 'First array:' print a print '\n' print 'Unique values of first array:' u = np.unique(a) print u print '\n' print 'Unique array and Indices array:' u,indices = np.unique(a, return_index = True) print indices print '\n' print 'We can see each number corresponds to index in original array:' print a print '\n' print 'Indices of unique array:' u,indices = np.unique(a,return_inverse = True) print u print '\n' print 'Indices are:' print indices print '\n' print 'Reconstruct the original array using indices:' print u[indices] print '\n' print 'Return the count of repetitions of unique elements:' u,indices = np.unique(a,return_counts = True) print u print indices
Its output is as follows −
First array: [5 2 6 2 7 5 6 8 2 9] Unique values of first array: [2 5 6 7 8 9] Unique array and Indices array: [1 0 2 4 7 9] We can see each number corresponds to index in original array: [5 2 6 2 7 5 6 8 2 9] Indices of unique array: [2 5 6 7 8 9] Indices are: [1 0 2 0 3 1 2 4 0 5] Reconstruct the original array using indices: [5 2 6 2 7 5 6 8 2 9] Return the count of repetitions of unique elements: [2 5 6 7 8 9] [3 2 2 1 1 1]
Next Topic – Click Here
Pingback: NumPy - Array Manipulation - Adglob Infosystem Pvt Ltd
Pingback: NumPy- delete - Adglob Infosystem Pvt Ltd