【发布时间】:2018-01-01 10:03:33
【问题描述】:
我有一个排序的整数数组,可能有重复。我想计算连续相等的值,当一个值与前一个不同时从零开始。这是用一个简单的 python 循环实现的预期结果:
import numpy as np
def count_multiplicities(a):
r = np.zeros(a.shape, dtype=a.dtype)
for i in range(1, len(a)):
if a[i] == a[i-1]:
r[i] = r[i-1]+1
else:
r[i] = 0
return r
a = (np.random.rand(20)*5).astype(dtype=int)
a.sort()
print "given sorted array: ", a
print "multiplicity count: ", count_multiplicities(a)
输出:
given sorted array: [0 0 0 0 0 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4]
multiplicity count: [0 1 2 3 4 0 1 2 0 1 2 3 0 1 2 3 0 1 2 3]
如何使用 numpy 以有效的方式获得相同的结果?数组很长,但重复次数很少(比如说不超过十次)。
在我的特殊情况下,我还知道值从零开始,并且连续值之间的差异是 0 或 1(值中没有间隙)。
【问题讨论】:
-
进一步思考:也许一个可能的解决方案可以通过使用具有给定对角线和上对角线的精心选择的矩阵的乘法来实现。
标签: python performance numpy