NumPy: Get the unique elements of an array
Unique Elements of Array
Write a NumPy program to get the unique elements of an array.
Pictorial Presentation:

Sample Solution:
Python Code:
# Importing the NumPy library with an alias 'np'
import numpy as np
# Creating a NumPy array 'x' with repeated elements
x = np.array([10, 10, 20, 20, 30, 30])
# Printing the original array
print("Original array:")
print(x)
# Finding and printing the unique elements in the array 'x'
print("Unique elements of the above array:")
print(np.unique(x))
# Creating a 2D NumPy array 'x' with multiple elements
x = np.array([[1, 1], [2, 3]])
# Printing the original 2D array
print("Original array:")
print(x)
# Finding and printing the unique elements in the 2D array 'x'
print("Unique elements of the above array:")
print(np.unique(x))
Sample Output:
Original array: [10 10 20 20 30 30] Unique elements of the above array: [10 20 30] Original array: [[1 1] [2 3]] Unique elements of the above array: [1 2 3]
Explanation:
In the above code -
x = np.array([10, 10, 20, 20, 30, 30]): Creates a NumPy array with elements 10, 10, 20, 20, 30, and 30.
print(np.unique(x)): The np.unique function returns the sorted unique elements of the input array x. In this case, the unique elements are 10, 20, and 30, so the output will be [10 20 30].
x = np.array([[1, 1], [2, 3]]): Creates a 2x2 NumPy array with elements 1, 1, 2, and 3.
print(np.unique(x)): The np.unique function works with multi-dimensional arrays as well. It flattens the input array and then returns the sorted unique elements. In this case, the unique elements are 1, 2, and 3, so the output will be [1 2 3].
For more Practice: Solve these Related Problems:
- Extract unique elements from a 1D array using np.unique and verify against manual filtering.
- Create a function that returns unique elements along with their occurrence counts.
- Apply np.unique on a 2D array and ensure that the result is a flattened array of distinct values.
- Handle arrays with mixed types to observe how uniqueness is determined by NumPy.
Python-Numpy Code Editor:
Previous: Write a NumPy program to find common values between two arrays.Next: Write a NumPy program to find the set difference of two arrays. The set difference will return the sorted, unique values in array1 that are not in array2.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics