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 and Numpy to parse XML data?
- 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 Numpy to select elements from an array based on multiple conditions?
- How do I use Python Scipy to perform a Z test?
- How can I use Scipy with Python?
- How do I use the scipy ttest_ind function in Python?
- How do I create a 2D array of zeros using Python and NumPy?
- How do I check the version of Python SciPy I'm using?
See more codes...