w3resource

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:

Python NumPy: Get the unique elements of an array

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].

Python-Numpy Code Editor: