# Python NumPy For Your Grandma - 4.7 unique()

Contents

In this section, we’ll see how to use the `unique()` function to get the unique elements of an array.

It’s pretty simple to use. If you have an array called `gar`

``````import numpy as np

gar = np.array(['b', 'b', 'a', 'a', 'c', 'c'])
print(gar)
## ['b' 'b' 'a' 'a' 'c' 'c']
``````

then `np.unique(gar)` gives you the unique elements.

``````np.unique(gar)
## array(['a', 'b', 'c'], dtype='<U1')
``````

Simple enough, although, you may have noticed that the order in which the elements occurred in the original array is different than the output. In the original array, ‘b’ occurred first but in the output, ‘a’ occurs first. That’s because `unique()` returns the unique elements in sorted order.

Let’s try that again, but this time we’ll call `unique()` with `return_index = True`.

``````np.unique(gar, return_index = True)
## (array(['a', 'b', 'c'], dtype='<U1'), array([2, 0, 4]))
``````

With `return_index = True`, NumPy gives us a tuple containing the unique elements array and a corresponding array that tells us the index at which each element first occurred in the original array.

For example, ‘a’ first occurred at index 2 in the original array, ‘b’ first occurred at index 0, and so on. This is useful if you want to reorder the unique elements in the same order they occurred in the original array. To do this, `argsort()` the index array and use that to sort the unique array.

``````uniques, first_positions = np.unique(gar, return_index = True)
uniques[np.argsort(first_positions)]
## array(['b', 'a', 'c'], dtype='<U1')
``````

Another sweet feature of `unique()` is that you can tell NumPy to return the count of each element. To do this, just set `return_counts = True`.

``````np.unique(gar, return_counts = True)
## (array(['a', 'b', 'c'], dtype='<U1'), array([2, 2, 2]))
``````