MATLAB函数唯一的Python等效项

萨德

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

在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

句子

使用的解决方案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(零)的索引。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章