简体   繁体   English

MATLAB 函数的 Python 等效项 unique

[英]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)在 Matlab 中它被写成: [C,ia,ic] = unique(A)

I am interested in all output elements ie, C , ia and ic我对所有输出元素感兴趣,即Ciaic

here is an example of what the matlab function does这是 matlab 函数功能的示例

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?请问如何在python中重现这个? As mentioned, i am interested in all output elements ie, C , ia and ic如前所述,我对所有输出元素感兴趣,即Ciaic

A solution using numpy.unique (thanks to @SBad himself for improving the quality of the solution):使用numpy.unique的解决方案(感谢@SBad 本人提高了解决方案的质量):

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为:

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.请记住, MATLAB使用基于 1(一)的索引,而Python使用基于 0(零)的索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM