我知道有人问过这个问题,但我还找不到答案。非常感谢您的任何帮助
在Matlab中,其编写为:[C,ia,ic] = unique(A)
我对所有输出元素,例如C
,ia
和ic
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中重现此内容?如前所述,我对C
,ia
和ic
谢谢
答案 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(零)的索引。