import numpy as np
from operator import itemgetter
arr = np.array([2, 2, 0, 0, 0, 1, 3, 3, 3, 3])
# get unique elements and counts
counts = zip(*np.unique(arr, return_counts=True))
# create a lookup dictionary value -> i where values are sorted according to frequency
mapping = {value: i for i, (value, _) in enumerate(sorted(counts, key=itemgetter(1)))}
# apply the dictionary in a vectorized way
result = np.vectorize(mapping.get)(arr)
print(result)
# get unique elements and counts
counts = Counter(arr)
# create a lookup dictionary value -> i where values are sorted according to frequency
mapping = {value: i for i, value in enumerate(sorted(counts, key=counts.get))}
您可以使用np.unique获取唯一元素和计数,然后构建一个字典,其中键是旧值,而值是新值。最后,使用np.vectorize将其应用于整个数组:
输出
另一种可能更干净的方法是使用collections.Counter计算并创建映射字典:
相关问题 更多 >
编程相关推荐