numpy。

问题描述 投票:0回答:6
['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 candy

unique()
python numpy
6个回答
118
投票

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

27
投票
np.unique

这些索引。

argsort

>>> a, idx = np.unique(['b','b','b','a','a','c','c'], return_index=True)
>>> a[np.argsort(idx)]
array(['b', 'a', 'c'], 
      dtype='|S1')

如果您试图删除已经分类的重复,则可以使用

9
投票
函数:
itertools.groupby

5
投票

>>> from itertools import groupby >>> a = ['b','b','b','a','a','c','c'] >>> [x[0] for x in groupby(a)] ['b', 'a', 'c']

    

>>> b = ['b','b','b','a','a','c','c','a','a']
>>> [x[0] for x in groupby(b)]
['b', 'a', 'c', 'a']



3
投票
#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']
,这是一个解决方案:
uniq

2
投票

使用订单(比列表理解更快)

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]

	
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.