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 thenpalias.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_valsvariable.print(unique_vals)- prints theunique_valsarray.
Helpful links
More of Python Scipy
- How can I use Python and SciPy to find the zeros of a function?
- 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 do I create a numpy array of zeros using Python?
- How can I use Python and Numpy to parse XML data?
- How do I use Scipy zeros in Python?
- How can I use Python and SciPy to read and write WAV files?
- How do I create a 2D array of zeros using Python and NumPy?
- How do I use Python Scipy to perform a Z test?
- How do I create a zero matrix using Python and Numpy?
See more codes...