2D numpy数组根据发生情况替换值n

2024-05-06 22:32:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有许多二维数组1161 x 1161,由0,1,2,3个数字组成。例如,其中一个由以下方式组成:

521859个零,288972个一,481471个二,55619个三

我想找到获得相同数组的最快方法,但现在出现的次数最少的是0,第二次出现的次数是1,依此类推,给出相同的数组,但现在由以下组成:

55619个零,288972个一,481471个二,521859个三

如果有一种非常适合Python的方式,那当然会很棒

提前感谢您的帮助


Tags: 方法方式数字数组次数
1条回答
网友
1楼 · 发布于 2024-05-06 22:32:22

您可以使用np.unique获取唯一元素和计数,然后构建一个字典,其中键是旧值,而值是新值。最后,使用np.vectorize将其应用于整个数组:

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)

输出

[1 1 2 2 2 0 3 3 3 3]

另一种可能更干净的方法是使用collections.Counter计算并创建映射字典:

# 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))}

相关问题 更多 >