['b','b','b','a','a','c','c']
numpy.unique给出
['a','b','c']
我怎样才能保留原来的顺序?
['b','a','c']
很好的答案。奖金问题。为什么这些方法都不适用于此数据集?http://www.uploadmb.com/dw.php?id=1364341573这里是问题numpy sort wierd behavior
发布于 2013-03-26 20:50:34
unique()
很慢,O(Nlog(N)),但您可以通过以下代码来实现:
import numpy as np
a = np.array(['b','a','b','b','d','a','a','c','c'])
_, idx = np.unique(a, return_index=True)
print(a[np.sort(idx)])
输出:
['b' 'a' 'd' 'c']
对于大数组O(N),Pandas.unique()
的速度要快得多:
import pandas as pd
a = np.random.randint(0, 1000, 10000)
%timeit np.unique(a)
%timeit pd.unique(a)
1000 loops, best of 3: 644 us per loop
10000 loops, best of 3: 144 us per loop
发布于 2013-03-26 20:49:36
使用np.unique
的return_index
功能。它返回元素在输入中首次出现的索引。然后argsort
这些索引。
>>> u, ind = np.unique(['b','b','b','a','a','c','c'], return_index=True)
>>> u[np.argsort(ind)]
array(['b', 'a', 'c'],
dtype='|S1')
发布于 2013-03-26 20:44:43
a = ['b','b','b','a','a','c','c']
[a[i] for i in sorted(np.unique(a, return_index=True)[1])]
https://stackoverflow.com/questions/15637336
复制相似问题