59
['b','b','b','a','a','c','c']

numpy.uniqueは

['a','b','c']

元の注文を保存するにはどうすればよいですか

['b','a','c']

素晴らしい答え。ボーナス質問。これらのメソッドのいずれもこのデータセットで機能しないのはなぜですか?http://www.uploadmb.com/dw.php?id=1364341573これが質問numpysortwierdbehaviorです

4

7 に答える 7

93

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
于 2013-03-26T12:50:33.547 に答える
25

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')
于 2013-03-26T12:49:35.853 に答える
8
a = ['b','b','b','a','a','c','c']
[a[i] for i in sorted(np.unique(a, return_index=True)[1])]
于 2013-03-26T12:44:43.173 に答える
3

すでにソートされている反復可能オブジェクトの重複を削除しようとしている場合は、次の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']
于 2013-03-26T12:54:47.070 に答える
2
#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']
于 2020-11-16T17:52:12.257 に答える
1

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]
于 2015-07-10T13:40:45.160 に答える
1

OrderedDictを使用する(リスト内包よりも速い)

from collections import OrderedDict  
a = ['b','a','b','a','a','c','c']
list(OrderedDict.fromkeys(a))
于 2019-09-17T16:21:14.510 に答える