Efficiently detect sign-changes in python

前端 未结 7 1490
深忆病人
深忆病人 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:21

    As remarked by Jay Borseth the accepted answer does not handle arrays containing 0 correctly.

    I propose using:

    import numpy as np
    a = np.array([-2, -1, 0, 1, 2])
    zero_crossings = np.where(np.diff(np.signbit(a)))[0]
    print(zero_crossings)
    # output: [1]
    

    Since a) using numpy.signbit() is a little bit quicker than numpy.sign(), since it's implementation is simpler, I guess and b) it deals correctly with zeros in the input array.

    However there is one drawback, maybe: If your input array starts and stops with zeros, it will find a zero crossing at the beginning, but not at the end...

    import numpy as np
    a = np.array([0, -2, -1, 0, 1, 2, 0])
    zero_crossings = np.where(np.diff(np.signbit(a)))[0]
    print(zero_crossings)
    # output: [0 2]
    
    0 讨论(0)
提交回复
热议问题