get number of unique values in array python code example
Example 1: python count number of unique elements in a list
# Basic syntax:
len(set(my_list))
# By definition, sets only contain unique elements, so when the list
# is converted to a set all duplicates are removed.
# Example usage:
my_list = ['so', 'so', 'so', 'many', 'duplicated', 'words']
len(set(my_list))
--> 4
# Note, list(set(my_list)) is a useful way to return a list containing
# only the unique elements in my_list
Example 2: return position of a unique value in python array
def partition(array):
return {i: (array == i).nonzero()[0] for i in np.unique(array)}