【发布时间】:2014-09-03 17:31:50
【问题描述】:
我想删除多余的元组,但保留出现的顺序。我看了类似的问题。这个问题Find unique rows in numpy.array 看起来很有希望,但不知何故对我不起作用。
我可以在这个答案 (https://stackoverflow.com/a/14089586/566035) 中使用 pandas,但我不喜欢使用 pandas,这样 py2exe 生成的可执行文件会很小。
import numpy as np
data = [('a','z'), ('a','z'), ('a','z'), ('1','z'), ('e','z'), ('c','z')]
#What I want is:
array([['a', 'z'],
['1', 'z'],
['e', 'z'],
['c', 'z']],
dtype='|S1')
#What I have tried:
# (1) numpy.unique, order not preserved
np.unique(data)
array([['a', 'z'],
['c', 'z'],
['1', 'z'],
['e', 'z']],
dtype='|S1')
# (2) python set, order not preserved
set(data)
set([('1', 'z'), ('a', 'z'), ('c', 'z'), ('e', 'z')])
# (3) answer here : https://stackoverflow.com/a/16973510/566035, order not preserved
a = np.array(data)
b = np.ascontiguousarray(a).view(np.dtype((np.void, a.dtype.itemsize * a.shape[1])))
_, idx = np.unique(b, return_index=True)
a[idx]
array([['1', 'z'],
['a', 'z'],
['c', 'z'],
['e', 'z']],
dtype='|S1')
【问题讨论】:
标签: python sorting numpy unique