numpy.unique()
The numpy.unique()
function returns unique elements from a given array or matrix. It returns the sorted unique elements of an array or matrix.
Syntax
The basic syntax of the numpy.unique()
function is:
numpy.unique(arr, return_index=False, return_inverse=False, return_counts=False, axis=None)
Where arr
is the input array.
Example
import numpy as np
arr = np.array([10, 20, 10, 30, 20, 40])
print(np.unique(arr))
Output:
[10 20 30 40]
In this example, the numpy.unique()
function returns the unique elements in the input array arr
. It should be noted that the function returns elements in a sorted order.
Explanation
The numpy.unique()
function returns the unique elements from a given array or matrix. These elements are sorted in ascending order. The unique elements are determined by comparing the elements in the input array pairwise.
Use
The numpy.unique()
function can be very useful when you want to find unique elements in an array or matrix. It can be used for various operations like filtering unique values, value counts, etc.
Important Points
numpy.unique()
function returns an array of unique elements.- If the input array contains NaN values, then they are also considered while computing the unique elements.
- If we want to return the indices for the unique elements, we can set the
return_index
parameter asTrue
. - If we want to return the inverse of the input array such that each element in the original array is replaced by its index in the returned array, we can set the
return_inverse
parameter asTrue
. - If we want to return the count of each unique element in the input array, we can set the
return_counts
parameter asTrue
.
Summary
The numpy.unique()
function returns unique elements from an array or matrix. These elements are sorted in ascending order. The function can be used for various operations like filtering unique values, value counts, etc. The parameters like return_index
, return_inverse
, and return_counts
can be used to return additional information like the indices for the unique elements, the inverse of the input array, and the count of each unique element in the input array.