w3resource

NumPy: Get the unique elements of an array

NumPy: Array Object Exercise-19 with Solution

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:

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/python-numpy-exercise-19.php