我有一个可能有重复的整数的整数数组。我想计算连续的相等值,当值与前一值不同时,从零开始重新计数。这是预期的结果实现了简单的Python循环:numpy:累计重复次数
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的一种有效的方法是什么?阵列非常长,但重复只是少数(不超过10次)。
在我的特殊情况下,我也知道值从零开始,并且连续值之间的差值为0或1(值中没有差距)。
进一步的想法:也许一个可能的解决方案可以通过使用与给定对角线和上对角线的良好选择矩阵的乘法来实现。 –