Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The Python Equivalent of the MATLAB function unique

I am aware that this question has been asked but i am not able to find the answer yet. Any help is very much appreciated

In Matlab it is written as: [C,ia,ic] = unique(A)

I am interested in all output elements i.e., C, ia and ic

here is an example of what the matlab function does

A = [9 2 9 5];
Find the unique values of A and the index vectors ia and ic, 
such that C = A(ia) and A = C(ic).

[C, ia, ic] = unique(A)
C = 1×3

     2     5     9

ia = 3×1

     2
     4
     1

ic = 4×1

     3
     1
     3
     2

How can I reproduce this in python please? As mentioned, i am interested in all output elements i.e., C, ia and ic

like image 866
SBad Avatar asked Jun 21 '26 17:06

SBad


1 Answers

A solution using numpy.unique (thanks to @SBad himself for improving the quality of the solution):

import numpy as np

A = np.array([9,2,9,5])

C, ia, ic = np.unique(A, return_index=True, return_inverse=True)

print(C)
print(ia)
print(ic)

output

[2 5 9]
[1 3 0]
[2 0 2 1]

with list comprehension you can also get ic as:

ic = [i for j in A for i,x in enumerate(C) if x == j]

Note:

Remember that MATLAB uses 1 (one) based indexing, while Python uses 0 (zero) based indexing.

like image 106
sentence Avatar answered Jun 24 '26 07:06

sentence