MATLAB函数唯一的Python等效项

时间:2019-05-17 11:30:51

标签: python-3.x matlab group-by pandas-groupby

我知道有人问过这个问题,但我还找不到答案。非常感谢您的任何帮助

在Matlab中,其编写为:[C,ia,ic] = unique(A)

我对所有输出元素,例如Ciaic

感兴趣

这是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

请问如何在python中重现此内容?如前所述,我对Ciaic

的所有输出元素都感兴趣

谢谢

1 个答案:

答案 0 :(得分:2)

使用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)

输出

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

借助列表理解功能,您还可以获取ic的信息:

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

注意

请记住, MATLAB 使用基于1(一)的索引,而 Python 使用基于0(零)的索引。