python-scipyHow can I use Python and NumPy to find unique values in an array?
Using Python and NumPy, you can find unique values in an array by using the np.unique()
function. This function takes an array as an argument and returns a sorted array of unique values in the array. For example:
import numpy as np
arr = np.array([1, 2, 3, 3, 4, 4, 5])
unique_vals = np.unique(arr)
print(unique_vals)
This will output:
[1 2 3 4 5]
The np.unique()
function works by looping through the given array and adding each value to a set. Since sets only contain unique values, each value will only be added once. After all values have been added to the set, the set is then converted into an array and sorted.
The parts of the code above are:
import numpy as np
- imports the NumPy library and assigns it to thenp
alias.arr = np.array([1, 2, 3, 3, 4, 4, 5])
- creates a NumPy array with the given values.unique_vals = np.unique(arr)
- calls thenp.unique()
function and assigns the returned array to theunique_vals
variable.print(unique_vals)
- prints theunique_vals
array.
Helpful links
More of Python Scipy
- How do I create a 2D array of zeros using Python and NumPy?
- How can I use Python Scipy to zoom in on an image?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How to use Python, XML-RPC, and NumPy together?
- How can I use Python and Numpy to parse XML data?
- How can I use Python and SciPy to perform a hypothesis test?
- How do I create a numpy array of zeros using Python?
- How do I create a zero matrix using Python and Numpy?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- How can I use the x.shape function in Python Numpy?
See more codes...