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:
[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]`
I want the count to be 8.
One solution is to run a loop and check for greater than or less than 0, and keep a history of the previous polarity.
Can we do this faster?
EDIT: My purpose is really to find something faster, because I have these arrays of length around 68554308, and I have to do these calculations on 100+ such arrays.
Python len() method enables us to find the total number of elements in the array/object. That is, it returns the count of the elements in the array/object.
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
Here's a numpy
solution. Numpy's methods are generally pretty fast and well-optimized, but if you're not already working with numpy
there's probably some overhead from converting the list to a numpy
array:
import numpy as np
my_list = [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]
(np.diff(np.sign(my_list)) != 0).sum()
Out[8]: 8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With