[英]Number of Consecutive values in with index Numpy Python
下面的代碼計算連續正值Cons_Pos_results
、負值Cons_Neg_results
、零值Cons_Zero_results
的最大次數。 我正在嘗試將代碼實現到已經存在的代碼中,其中顯示了最大連續值數量之間的索引。 因此,對於連續值為正的最大數量介於索引 38-60 之間。 所用代碼的問題: 問題
大批:
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))
預期 Output:
Consecutive Positive results: 22 Indexes: 38 - 60
Consecutive Zero results: 21 Indexes: 0 - 21
Consecutive Negative results: 2 Indexes: 26 - 27
您可以利用 d 數組在每個找到的序列的開頭和結尾都有非零值這一事實。 當兩個這樣的非零值之間的距離等於計數時,您已經找到了所需的索引:
import numpy as np
def count_consecutive(arr, sign):
sign_dic = {'positive':1, 'negative':-1, 'zero':0, 'pos':1, 'neg':-1, 0:0}
n = sign_dic.get(sign, -2)
if n == -2:
return "sign must be 'positive', 'negative', or 'zero'."
signs = np.sign(arr) # we only care about the sign
# pad a with False at both sides for edge cases when array starts or ends with n
d = np.diff(np.concatenate(([False], signs == n, [False])).astype(int))
# subtract indices when value changes from False to True from indices where value changes from True to False
# get max of these
count = np.max(np.flatnonzero(d == -1) - np.flatnonzero(d == 1))
# calculate starting index of longest sequence
indexes = np.nonzero(d)
dif = np.diff(indexes)
i = dif[0].tolist().index(count)
idx = indexes[0][i]
return f'Consecutive {sign} results: {count}, Indexes: {idx} - {idx+count-1}'
a = np.array([1,1,2,3,0,0,0,0,-1,-2,0,0,0,0,0,0,0,1,1,1,1,1,1,-21])
print(count_consecutive(a, 'positive')) #Consecutive positive results: 6, Indexes: 17 - 22
print(count_consecutive(a, 'negative')) #Consecutive negative results: 2, Indexes: 8 - 9
print(count_consecutive(a, 'zero')) #Consecutive zero results: 7, Indexes: 10 - 16
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.