对于Python中的通用对象,有没有等效于np.unique的函数

问题描述 投票:0回答:2

np.unique()可以返回第一次出现的索引,要重建的索引和出现次数。是否有可以对任何Python对象执行相同操作的函数/库?

python algorithm numpy unique
2个回答
1
投票

并非如此。您可以根据需要使用不同的类来获得类似的功能。

没有额外标志的[np.unique()具有与unique相似的结果:

set

[set模拟unique_value = set(x)

collections.Counter

要模拟collections.Counter,请在return_countscounts = collections.Counter(x) unique_values = list(counts.keys()) unique_counts = list(counts.values()) 上使用return_index。假设容器是一个列表

list.index

为了模拟list.index,我们看一下set的实际实现方式。 Counter对输入进行排序以获得元素的运行。可以通过first_indices = [x.index(k) for k in counts] (或就地return_inverse)和unique实现类似的技术:

unique

实际上,sorted方法对所有选项进行编码:

sorted

0
投票

您可以使用list.sort

list.sort
© www.soinside.com 2019 - 2024. All rights reserved.