【发布时间】:2021-08-12 05:10:04
【问题描述】:
下面的代码计算连续正值Cons_Pos_results、负值Cons_Neg_results、零值Cons_Zero_results 的最大次数。我正在尝试将代码实现到已经存在的代码中,其中显示了最大连续值数量之间的索引。因此,对于连续值为正的最大数量介于索引 38-60 之间。使用代码的问题:issue
数组:
import numpy as np
a = np.array([ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. -8. 0. 0.
304.2 -27.8 -15.4 0. 0. -14.8 0. 6.4 14.4 0. -10.6 55.8
23.1 0. 27.9 34.7 62. 23. 41.6 30.7 30.5 34.9 40.9 21.7
31.3 19.9 32.8 26.2 14.8 18.9 15.2 23.8 21.9 112.7 38.4 34.4])
代码:
sign = np.sign(a) # we only care about the sign
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)
Cons_Pos_results= np.max(count_consecutive(sign, 1))
Cons_Neg_results= np.max(count_consecutive(sign, 0))
Cons_Zero_results= np.max(count_consecutive(sign, -1))
预期输出:
Consecutive Positive results: 22 Indexes: 38 - 60
Consecutive Zero results: 21 Indexes: 0 - 21
Consecutive Negative results: 2 Indexes: 26 - 27
【问题讨论】:
标签: python arrays numpy indexing max