关于python:numpy不带排序的唯一

numpy unique without sort

本问题已经有最佳答案,请猛点这里访问。

我如何使用numpy unique而不对结果进行排序,而仅按它们在序列中出现的顺序排序? 像这样吗

a = [4,2,1,3,1,2,3,4]

np.unique(a) = [4,2,1,3]

而不是

np.unique(a) = [1,2,3,4]

使用幼稚的解决方案应该可以编写一个简单的函数。 但是,由于我需要多次执行此操作,因此有什么快速而整洁的方法吗?


您可以使用return_index参数执行此操作:

1
2
3
4
5
6
7
>>> import numpy as np
>>> a = [4,2,1,3,1,2,3,4]
>>> np.unique(a)
array([1, 2, 3, 4])
>>> indexes = np.unique(a, return_index=True)[1]
>>> [a[index] for index in sorted(indexes)]
[4, 2, 1, 3]


您可以通过执行numpy这样的操作来做到这一点,mergsort是稳定的,因此您可以选择每个值的第一个或最后一个出现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def unique(array, orderby='first'):
    array = np.asarray(array)
    order = array.argsort(kind='mergesort')
    array = array[order]
    diff = array[1:] != array[:-1]
    if orderby == 'first':
        diff = np.concatenate([[True], diff])
    elif orderby == 'last':
        diff = np.concatenate([diff, [True]])
    else:
        raise ValueError
    uniq = array[diff]
    index = order[diff]
    return uniq[index.argsort()]

这个答案非常类似于:

1
2
3
def unique(array):
    uniq, index = np.unique(array, return_index=True)
    return uniq[index.argsort()]

但是,numpy.unique在内部使用不稳定的排序方式,因此不能保证您会获取任何特定的索引,即first或last。

我认为命令字典也可能有效:

1
2
3
4
5
def unique(array):
    uniq = OrderedDict()
    for i in array:
         uniq[i] = 1
    return uniq.keys()