In this article we will discuss how to find unique values / rows / columns in a 1D & 2D Numpy array. Also how to find their index position & frequency count using numpy.unique().

numpy.unique()

Python’s numpy module provides a function to find the unique elements in a numpy array i.e.

Arguments

  • arr : Numpy array in which we want to find the unique values.
  • return_index : optional bool flag. If True returns an array of indices of first occurrence of each unique value.
  • return_counts : optional bool flag. If True returns an array of occurrence count of each unique value.
  • axis : If not provided then will act on flattened array. If 0 or 1 then acts on row or column wise.

It returns either one numpy array of unique values or based on arguments can also return a tuple of arrays.
Let’s understand by some examples,

Find Unique Values from a Numpy Array

To find the unique values in this array pass the complete array to numpy.unique(). It will return an array of unique values i.e.

Output:

Here we passed only one argument in the numpy.unique(). Therefore it returned only an array of unique values.
Let’s explore other arguments,

Find Unique Values & their first index position from a Numpy Array

To get the indices of unique values in numpy array, pass the return_index argument in numpy.unique(), along with array i.e.

Output:

It returns a tuple of 2 arrays i.e.

  • Array of unique values
  • Array of first index position of unique values in first array

Now just zipped the contents of both array to get a combination of unique value and it’s index position i.e.

Output:

Get Unique Values & their frequency count from a Numpy Array

To get the frequency count of unique values in numpy array, pass the return_counts argument in numpy.unique(), along with array i.e.

Output:

It returns a tuple of 2 arrays i.e.

  • Array of unique values
  • Array of frequency count of unique values in first array

Now just zipped the contents of both array to get a combination of unique value and their frequency count i.e.

Output:

Get Unique Values , frequency count & index position from a Numpy Array

We can also pass all the arguments together i.e.

Output:

Find unique values, rows & columns in a 2D numpy array

We can also pass a 2D numpy array to numpy.unique() to get the unique values i.e.

Output:

If axis argument is not passed, 2D array will be flattened and used. To get the unique rows or columns pass axis argument i.e.

Get unique Rows :

Output:

Get unique Columns :

Output:

Get unique Columns & index position :

Output:

Complete example is as follows,

Output:

 

Python Resources

C++11 / C++14 Resources

Design Patterns Resources

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Do Subscribe with us for more Articles / Tutorials like this,