In Python, the numpy
library provides numerous powerful functions for working with arrays. One such function is unique()
, which allows you to find the unique elements in an array.
The numpy.unique()
function returns a sorted array containing unique values from the input array. It can also return the indices or counts of unique values, depending on the optional parameters you specify.
Here’s an example to demonstrate how to use the numpy.unique()
function:
import numpy as np
# Create an array with duplicate values
arr = np.array([1, 2, 3, 4, 3, 2, 1, 5, 4, 6])
# Get unique values from the array
unique_values = np.unique(arr)
print(unique_values)
Output:
[1 2 3 4 5 6]
In the above code, we import the numpy
library using the alias np
for convenience. We then create an array arr
with some duplicate values. By calling np.unique(arr)
, we get an array with the unique values [1, 2, 3, 4, 5, 6]
, which is then printed.
To obtain the indices of the unique values, you can pass the parameter return_index=True
to the np.unique()
function:
unique_values, indices = np.unique(arr, return_index=True)
print(unique_values)
print(indices)
Output:
[1 2 3 4 5 6]
[0 1 2 3 7 9]
Here, indices
contains the indices of the unique values in the original array arr
.
You can also find the count of occurrences of each unique value by using the return_counts=True
parameter:
unique_values, counts = np.unique(arr, return_counts=True)
print(unique_values)
print(counts)
Output:
[1 2 3 4 5 6]
[2 2 2 2 1 1]
In the above example, counts
provides the number of times each unique value appears in the original array.
The numpy.unique()
function offers flexibility and convenience when working with arrays by allowing you to easily extract unique values, their indices, or their occurrence counts. It is a helpful tool for data analysis and manipulation.