对于 Python 中的通用对象,是否有等同于 np.unique 的函数
Is there any function equivalent to np.unique for generic object in Python
np.unique()
可以 return 首次出现的索引、要重建的索引和出现次数。是否有任何 function/library 可以对任何 Python 对象执行相同的操作?
您可以使用 Counter
:
> from collections import Counter
> bob = ['bob','bob','dob']
> Counter(bob)
Counter({'bob': 2, 'dob': 1})
> Counter(bob).keys()
dict_keys(['bob', 'dob'])
并非如此。您可以根据需要使用不同的 类 获得类似的功能。
没有额外标志的 unique
与 set
:
的结果相似
unique_value = set(x)
collections.Counter
模拟 return_counts
:
counts = collections.Counter(x)
unique_values = list(counts.keys())
unique_counts = list(counts.values())
要模仿 return_index
,请在 set
或 Counter
上使用 list.index
。这假设容器是一个列表
first_indices = [x.index(k) for k in counts]
为了模拟return_inverse
,我们看看unique
是如何实际实现的。 unique
对输入进行排序以获得元素的运行。可以通过 sorted
(or in-place list.sort
) and itertools.groupby
:
实现类似的技术
s = sorted(zip(x, itertools.count()))
inverse = [0] * len(x)
for i, (k, g) in enumerate(itertools.groupby(s, operator.itemgetter(0))):
for v in g:
inverse[v[1]] = i
事实上,groupby
方法对所有选项进行了编码:
s = sorted(zip(x, itertools.count()))
unique_values = []
first_indices = []
unique_counts = []
inverse = [0] * len(x)
for i, (k, g) in enumerate(itertools.groupby(s, operator.itemgetter(0))):
unique_values.append(k)
count = 1
v = next(g)
inverse[v[1]] = i
first_indices.append(v[0])
for v in g:
inverse[v[1]] = i
count += 1
unique_counts.append(count)
np.unique()
可以 return 首次出现的索引、要重建的索引和出现次数。是否有任何 function/library 可以对任何 Python 对象执行相同的操作?
您可以使用 Counter
:
> from collections import Counter
> bob = ['bob','bob','dob']
> Counter(bob)
Counter({'bob': 2, 'dob': 1})
> Counter(bob).keys()
dict_keys(['bob', 'dob'])
并非如此。您可以根据需要使用不同的 类 获得类似的功能。
没有额外标志的unique
与 set
:
unique_value = set(x)
collections.Counter
模拟 return_counts
:
counts = collections.Counter(x)
unique_values = list(counts.keys())
unique_counts = list(counts.values())
要模仿 return_index
,请在 set
或 Counter
上使用 list.index
。这假设容器是一个列表
first_indices = [x.index(k) for k in counts]
为了模拟return_inverse
,我们看看unique
是如何实际实现的。 unique
对输入进行排序以获得元素的运行。可以通过 sorted
(or in-place list.sort
) and itertools.groupby
:
s = sorted(zip(x, itertools.count()))
inverse = [0] * len(x)
for i, (k, g) in enumerate(itertools.groupby(s, operator.itemgetter(0))):
for v in g:
inverse[v[1]] = i
事实上,groupby
方法对所有选项进行了编码:
s = sorted(zip(x, itertools.count()))
unique_values = []
first_indices = []
unique_counts = []
inverse = [0] * len(x)
for i, (k, g) in enumerate(itertools.groupby(s, operator.itemgetter(0))):
unique_values.append(k)
count = 1
v = next(g)
inverse[v[1]] = i
first_indices.append(v[0])
for v in g:
inverse[v[1]] = i
count += 1
unique_counts.append(count)