How to find all unique values in a matrix using numpy in python

Published: July 28, 2020

Tags: Python; Numpy;

DMCA.com Protection Status

Examples of how to find all unique values in a matrix using numpy in python:

Create a matrix

Lets consider the following matrix

import numpy as np

A = np.random.randint(3, size=20)

print(A)

returns for example

[1 2 1 0 1 2 2 1 2 0 2 1 1 1 0 1 2 1 2 2]

Find the unique values in the matrix A

To find the unique values in a matrix, a solution is to use the numpy function called unique, example:

np.unique(A)

which returns here

array([0, 1, 2])

Find the unique values in a 2D matrix

Another example with a matrix of dimensions (3,4)

A = np.random.randint(10, size=(3,4))

print(A)

returns for example

[[9 8 6 7]
 [0 8 3 3]
 [0 5 9 1]]

Then the function unique:

np.unique(A)

gives

array([0, 1, 3, 5, 6, 7, 8, 9])

Note: to find all unique combinations of values a solution is to use the argument axis in the function unique. For example with the matrix:

A = np.random.randint(2, size=(10,2))

print(A)

which returns fo example

[[1 0]
 [0 1]
 [1 1]
 [1 0]
 [1 0]
 [1 1]
 [0 0]
 [1 0]
 [0 1]
 [1 0]]
Out[13]:

and using axis=0:

np.unique(A, axis=0)

the we get:

array([[0, 0],
    [0, 1],
    [1, 0],
    [1, 1]])

Find all unique values and reconstruct the initial matrix

Lets consider the following matrix:

import numpy as np

A = np.array([-2,6,-7,8,9,-4,3])

print(A)

gives

[-2  6 -7  8  9 -4  3]

then to get the unique values and the associated indexes to reconstruct the initial matrix, just add the argument "return_inverse=True" :

u_values, u_indices = np.unique(A, return_inverse=True)

print(u_values)

print(u_indices)

gives respectively

[-7 -4 -2  3  6  8  9]

and

[2 4 0 5 6 1 3]

Then to reconstruct the initial matrix, one can do:

print(u_values[u_indices])

[-2  6 -7  8  9 -4  3]

References