numpy.unique 保留顺序
- 2025-03-06 08:55:00
- admin 原创
- 66
问题描述:
['b','b','b','a','a','c','c']
numpy.unique 给出
['a','b','c']
我怎样才能保留原始订单
['b','a','c']
很好的答案。附加问题。为什么这些方法都不适用于此数据集?http://www.uploadmb.com/dw.php?id =1364341573 这是numpy 排序怪异行为的问题
解决方案 1:
unique()
速度很慢,O(Nlog(N)),但你可以通过以下代码来实现:
import numpy as np
a = np.array(['b','b','b','a','a','c','c'])
_, idx = np.unique(a, return_index=True)
print(a[np.sort(idx)])
输出:
['b' 'a' 'c']
Pandas.unique()
对于大数组 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
解决方案 2:
使用return_index
的功能np.unique
。它将返回元素在输入中首次出现的索引。然后是argsort
这些索引。
>>> a = ['b','b','b','a','a','c','c']
>>> b, idx = np.unique(a, return_index=True)
>>> b[np.argsort(idx)]
array(['b', 'a', 'c'],
dtype='|S1')
解决方案 3:
a = ['b','b','b','a','a','c','c']
[a[i] for i in sorted(np.unique(a, return_index=True)[1])]
解决方案 4:
如果您尝试删除已排序的可迭代对象的重复项,则可以使用itertools.groupby
函数:
>>> from itertools import groupby
>>> a = ['b','b','b','a','a','c','c']
>>> [x[0] for x in groupby(a)]
['b', 'a', 'c']
这更像 unix 的 'uniq' 命令,因为它假定列表已经排序。当您在未排序的列表上尝试它时,您将得到如下结果:
>>> b = ['b','b','b','a','a','c','c','a','a']
>>> [x[0] for x in groupby(b)]
['b', 'a', 'c', 'a']
解决方案 5:
#List we need to remove duplicates from while preserving order x = ['key1', 'key3', 'key3', 'key2'] thisdict = dict.fromkeys(x) #dictionary keys are unique and order is preserved print(list(thisdict)) #convert back to list output: ['key1', 'key3', 'key2']
解决方案 6:
如果您想删除重复的条目,就像Unix工具一样uniq
,这是一个解决方案:
def uniq(seq):
"""
Like Unix tool uniq. Removes repeated entries.
:param seq: numpy.array
:return: seq
"""
diffs = np.ones_like(seq)
diffs[1:] = seq[1:] - seq[:-1]
idx = diffs.nonzero()
return seq[idx]
解决方案 7:
使用 OrderedDict(比列表理解更快)
from collections import OrderedDict
a = ['b','a','b','a','a','c','c']
list(OrderedDict.fromkeys(a))
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD