繁体   English   中英

索引中的连续值数 Numpy Python

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM