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:
Python3
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]
Syntax
Syntax: np.unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)
Parameters
- ar: Input array.
- return_index: If True, also return the indices of ar that result in the unique array.
- return_inverse: If True, also return the indices of the unique array that can be used to reconstruct ar.
- return_counts: If True, also return the number of times each unique item appears in ar.
- axis: The axis to operate on. If None, ar will be flattened.
Returns: Return the unique of an array.
Let us look at some examples of how to get the unique elements of an array using NumPy library:
More Examples
Here we will see examples of how to find unique elements in 1D and 2D NumPy arrays.
Example 1: Finding Unique Elements in a 1D Numpy Array
Python3
# import library import numpy as np # create 1d-array arr = np.array([ 3 , 3 , 4 , 5 , 6 , 5 , 6 , 4 ]) # find unique element # from a array rslt = np.unique(arr) print (rslt) |
Output:
[3 4 5 6]
Example 2: Finding Unique Elements in a 2D Numpy Array
Python3
# import library import numpy as np # create a numpy 2d-array arr = np.array([[ 9 , 9 , 7 , 7 ], [ 3 , 4 , 3 , 4 ]]) # find unique element # from a array rslt = np.unique(arr) print (rslt) |
Output:
[3 4 7 9]