假设我有以下numpy数组:a = np.array([1,5,5,2,3,6,5,2,5,5,5])我试图想出一个numpy解决方案来计算给定值连续出现的次数。因此,例如对于5我想得到的数字:array([2,1,3])因为它在数组中连续出现 3 次,每次都有指定的重复次数。
2 回答

慕仙森
TA贡献1827条经验 获得超8个赞
这是改编自此答案的一个选项:
def count_consecutive(arr, n):
# pad a with False at both sides for edge cases when array starts or ends with n
d = np.diff(np.concatenate(([False], arr == n, [False])).astype(int))
# subtract indices when value changes from False to True from indices where value changes from True to False
return np.flatnonzero(d == -1) - np.flatnonzero(d == 1)
count_consecutive(a, 5)
# array([2, 1, 3])

慕姐8265434
TA贡献1813条经验 获得超2个赞
如果你没问题,list那么可以使用 groupby
from itertools import groupby
a=[1,5,5,2,3,6,5,2,5,5,5]
[len(list(v)) for k,v in groupby(a) if k==5]
输出
[2, 1, 3]
添加回答
举报
0/150
提交
取消