【发布时间】:2017-10-11 21:13:39
【问题描述】:
我有一个排序的非唯一数字的一维数组。他们重复的次数是随机的。 它与具有相同大小的权重数组相关联。对于给定的一系列相同元素,相关的一系列权重可能也可能有重复元素,也可能没有重复元素,并且在整个权重数组中,可能有也可能没有重复元素。例如:
pos = np.array([3, 3, 7, 7, 9, 9, 9, 10, 10])
weights = np.array([2, 10, 20, 8, 5, 7, 15, 7, 2])
我需要提取pos 的唯一元素数组,但其中唯一元素是权重最大的元素。
我想出的工作解决方案涉及循环:
pos = np.array([3, 3, 7, 7, 9, 9, 9, 10, 10])
weights = np.array([2, 10, 20, 8, 5, 7, 15, 7, 2])
# Get the number of occurences of the elements in pos but throw away the unique array, it's not the one I want.
_, ucounts = np.unique(pos, return_counts=True)
# Initialize the output array.
unique_pos_idx = np.zeros([ucounts.size], dtype=np.uint32)
last = 0
for i in range(ucounts.size):
maxpos = np.argmax( weights[last:last+ucounts[i]] )
unique_pos_idx[i] = last + maxpos
last += ucounts[i]
# Result is:
# unique_pos_idx = [1 2 6 7]
但我没有使用太多 Python 语言或 Numpy(除了使用 numpy 数组),所以我想知道是否有比上述 Cython 版本更 Pythonesque 和/或更有效的解决方案?
谢谢
【问题讨论】:
标签: arrays numpy unique extraction weighted