Python code for counting number of zero crossings in an array

前端 未结 6 1458
春和景丽
春和景丽 2021-02-08 01:44

I am looking to count the number of times the values in an array change in polarity (EDIT: Number of times the values in an array cross zero).

Suppose I have an array:<

6条回答
  •  一向
    一向 (楼主)
    2021-02-08 02:34

    This produces the same result:

    import numpy as np
    my_array = np.array([80.6, 120.8, -115.6, -76.1, 131.3, 105.1, 138.4, -81.3, -95.3,  
                         89.2, -154.1, 121.4, -85.1, 96.8, 68.2])
    ((my_array[:-1] * my_array[1:]) < 0).sum()
    

    gives:

    8
    

    and seems to be the fastest solution:

    %timeit ((my_array[:-1] * my_array[1:]) < 0).sum()
    100000 loops, best of 3: 11.6 µs per loop
    

    Compared to the fastest so far:

    %timeit (np.diff(np.sign(my_array)) != 0).sum()
    10000 loops, best of 3: 22.2 µs per loop
    

    Also for larger arrays:

    big = np.random.randint(-10, 10, size=10000000)
    

    this:

    %timeit ((big[:-1] * big[1:]) < 0).sum()
    10 loops, best of 3: 62.1 ms per loop
    

    vs:

    %timeit (np.diff(np.sign(big)) != 0).sum()
    1 loops, best of 3: 97.6 ms per loop
    

提交回复
热议问题