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 can I use Python Scipy to zoom in on an image?
- How do I use Python Scipy to perform a Z test?
- How can I check if a certain version of Python is compatible with SciPy?
- How do I create a 2D array of zeros using Python and NumPy?
- How to use Python, XML-RPC, and NumPy together?
- How can I use Python and SciPy to find the zeros of a function?
- How can I use Python and Numpy to zip files?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How can I use Python and SciPy to visualize data?
- How do I use Python and SciPy to write a WAV file?
See more codes...