['b','b','b','a','a','c','c']
numpy.uniqueは
['a','b','c']
元の注文を保存するにはどうすればよいですか
['b','a','c']
素晴らしい答え。ボーナス質問。これらのメソッドのいずれもこのデータセットで機能しないのはなぜですか?http://www.uploadmb.com/dw.php?id=1364341573これが質問numpysortwierdbehaviorです
['b','b','b','a','a','c','c']
numpy.uniqueは
['a','b','c']
元の注文を保存するにはどうすればよいですか
['b','a','c']
素晴らしい答え。ボーナス質問。これらのメソッドのいずれもこのデータセットで機能しないのはなぜですか?http://www.uploadmb.com/dw.php?id=1364341573これが質問numpysortwierdbehaviorです
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']
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
return_index
の機能を使用しますnp.unique
。これは、要素が入力で最初に発生したインデックスを返します。次に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')
a = ['b','b','b','a','a','c','c']
[a[i] for i in sorted(np.unique(a, return_index=True)[1])]
すでにソートされている反復可能オブジェクトの重複を削除しようとしている場合は、次の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']
#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']
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]
OrderedDictを使用する(リスト内包よりも速い)
from collections import OrderedDict
a = ['b','a','b','a','a','c','c']
list(OrderedDict.fromkeys(a))