Python 在NumPy数组中获取唯一行时保留顺序
我有三个二维阵列Python 在NumPy数组中获取唯一行时保留顺序,python,numpy,multidimensional-array,unique,size-reduction,Python,Numpy,Multidimensional Array,Unique,Size Reduction,我有三个二维阵列a1,a2,和a3 In [165]: a1 Out[165]: array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]]) In [166]: a2 Out[166]: array([[ 9, 10, 11], [15, 16, 17], [18, 19, 20]]) In [167]: a3 Out[167]: array([[
a1
,a2
,和a3
In [165]: a1
Out[165]:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
In [166]: a2
Out[166]:
array([[ 9, 10, 11],
[15, 16, 17],
[18, 19, 20]])
In [167]: a3
Out[167]:
array([[6, 7, 8],
[4, 5, 5]])
我将这些数组堆叠成一个数组:
In [168]: stacked = np.vstack((a1, a2, a3))
In [170]: stacked
Out[170]:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[ 9, 10, 11],
[15, 16, 17],
[18, 19, 20],
[ 6, 7, 8],
[ 4, 5, 5]])
现在,我想去掉重复的行。因此,numpy.unique
完成了这项工作
In [169]: np.unique(stacked, axis=0)
Out[169]:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 4, 5, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[15, 16, 17],
[18, 19, 20]])
然而,这里有一个问题。获取唯一行时,原始顺序将丢失。我怎样才能保留原始顺序,同时仍然保留唯一的行
因此,预期输出应为:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[15, 16, 17],
[18, 19, 20],
[ 4, 5, 5]])
使用
return\u索引
_,idx=np.unique(stacked, axis=0,return_index=True)
stacked[np.sort(idx)]
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[15, 16, 17],
[18, 19, 20],
[ 4, 5, 5]])
在得到堆叠阵列之后 步骤1:获取排序后的唯一数组的行索引
row_indexes = np.unique(stacked, return_index=True, axis=0)[1]
注意:行索引包含排序数组的索引
步骤2:现在使用排序索引遍历堆叠数组
sorted_index=sorted(row_indexes)
new_arr=[]
for i in range(len(sorted_index)):
new_arr.append(stacked[sorted_index[i]]
就这样 在手机上工作,直到我贴出来我才看到你的答案+1.