Efficiently detect sign-changes in python

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

    I see people using diff a lot in their solutions, but xor seems to be much faster and the result is the same for bools (a good pointer to that might also be the fact that using diff gives a deprecated warning.... :) ) Here is an example:

    positive = a2 > 0
    np.where(np.bitwise_xor(positive[1:], positive[:-1]))[0]
    

    Time it measures it to be around one and a half faster to diff for me:)

    If you do not care about edge cases it might be better to use

    positive = np.signbit(a2)
    

    but positive = a2 >0 seems faster (and cleaner) than signbit AND checking for 0s (e.g. positive = np.bitwise_or(np.signbit(a2),np.logical_not(a2)) is slower...)

提交回复
热议问题