保留NumPy数组中的唯一行时的顺序

时间:2019-01-11 04:51:56

标签: python numpy multidimensional-array unique size-reduction

我有三个二维数组a1a2a3

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]])

2 个答案:

答案 0 :(得分:3)

使用return_index

_,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 :(得分:0)

获得堆叠数组后

步骤1:获取排序后的唯一数组的行的索引

row_indexes = np.unique(stacked, return_index=True, axis=0)[1]

注意:row_indexes保留排序数组的索引

第2步:现在使用排序后的索引遍历堆栈数组

sorted_index=sorted(row_indexes)
new_arr=[]
for i in range(len(sorted_index)):
    new_arr.append(stacked[sorted_index[i]]

就这样!!!!!