Chapter 6: NumPy functions

Unique

face Josiah Wang

Like a Python set, NumPy has a function called np.unique() to obtain a set of unique elements in an array.

>>> x = np.array([12, 15, 13, 15, 16, 17, 13, 13, 18, 13, 19, 18, 11, 16, 15])
>>> print(np.unique(x))
[11 12 13 15 16 17 18 19]

You can also return the index of the first occurrence of each of the unique elements in the array. For example, the number 11 is first encountered at index 12.

>>> x = np.array([12, 15, 13, 15, 16, 17, 13, 13, 18, 13, 19, 18, 11, 16, 15])
>>> (unique_x, unique_indices) = np.unique(x, return_index=True)
>>> print(unique_x)
[11 12 13 15 16 17 18 19]
>>> print(unique_indices)
[12  0  2  1  4  5  8 10]

You can also count the number of times each unique element occurs in the array. Useful when you to compute a histogram of counts!

>>> x = np.array([12, 15, 13, 15, 16, 17, 13, 13, 18, 13, 19, 18, 11, 16, 15])
>>> (unique_x, unique_counts) = np.unique(x, return_counts=True)
>>> print(unique_x)
[11 12 13 15 16 17 18 19]
>>> print(unique_counts)
[1 1 4 3 2 1 2 1]