Efficiently detect sign-changes in python

前端 未结 7 1491
深忆病人
深忆病人 2020-11-29 20:28

I want to do exactly what this guy did:

Python - count sign changes

However I need to optimize it to run super fast. In brief I want to take a time series an

7条回答
  •  醉梦人生
    2020-11-29 21:02

    Jim Brissom's answer fails if a contains the value 0:

    import numpy  
    a2 = [1, 2, 1, 1, 0, -3, -4, 7, 8, 9, 10, -2, 1, -3, 5, 6, 7, -10]  
    zero_crossings2 = numpy.where(numpy.diff(numpy.sign(a2)))[0]  
    print zero_crossings2  
    print len(zero_crossings2)  # should be 7
    

    Output:

    [ 3  4  6 10 11 12 13 16]  
    8  
    

    The number of zero crossing should be 7, but because sign() returns 0 if 0 is passed, 1 for positive, and -1 for negative values, diff() will count the transition containing zero twice.

    An alternative might be:

    a3 = [1, 2, 1, 1, 0, -3, -4, 7, 8, 9, 10, 0, -2, 0, 0, 1, 0, -3, 0, 5, 6, 7, -10]  
    s3= numpy.sign(a3)  
    s3[s3==0] = -1     # replace zeros with -1  
    zero_crossings3 = numpy.where(numpy.diff(s3))[0]  
    print s3  
    print zero_crossings3  
    print len(zero_crossings3)   # should be 7
    

    which give the correct answer of:

    [ 3  6 10 14 15 18 21]
    7
    

提交回复
热议问题