numpy.unique 保留顺序 [英] numpy.unique with order preserved
本文介绍了numpy.unique 保留顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
['b','b','b','a','a','c','c']
numpy.unique 给出
numpy.unique gives
['a','b','c']
如何才能保留原始订单
['b','a','c']
<小时>
很好的答案.奖金问题.为什么这些方法都不适用于此数据集?http://www.uploadmb.com/dw.php?id=1364341573这是问题numpy排序奇怪的行为
推荐答案
unique()
很慢,O(Nlog(N)),但是你可以通过下面的代码做到这一点:
unique()
is slow, O(Nlog(N)), but you can do this by following code:
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']
Pandas.unique()
对于大数组 O(N) 来说要快得多:
Pandas.unique()
is much faster for big array O(N):
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
这篇关于numpy.unique 保留顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文