I have a list e.g. my_list = [1, 3, 5, 7, 14, 16, 18, 22, 28, 30, 32, 41, 43]
I want a function that will return all values from the list where the difference between that value and previous value is not equal to 2, e.g. the function will return [1, 14, 22, 28, 41] for the above list. Note that the first value of my_list will always appear as the first value of the output. The input lists are of non-zero length and up to the order of 100's.
So far I have this:
def get_output(array):
start = [array[0]]
for i in range(1, len(array)-1):
if (array[i] - array[i-1]) != 2:
start.append(array[i])
return start
Is there a vectorised solution that would be faster, bearing in mind I will be applying this function to thousands of input arrays?
To avoid using the inefficient np.concat, use np.ediff1 instead of np.diff, which takes a to_begin argument to pre-pend to the result:
>>> my_list = [1, 3, 5, 7, 14, 16, 18, 22, 28, 30, 32, 41, 43]
>>> arr = np.array(my_list)
>>> np.ediff1d(arr, to_begin=0)
array([0, 2, 2, 2, 7, 2, 2, 4, 6, 2, 2, 9, 2])
So now, using boolean-indexing:
>>> arr[np.ediff1d(arr, to_begin=0) != 2]
array([ 1, 14, 22, 28, 41])
Apart from the first element which you can add manually (although it doesn't really make sense as per Azat Ibrakov comment) you can use np.where
a = np.array([1, 3, 5, 7, 14, 16, 18, 22, 28, 30, 32, 41, 43])
a[np.where(a[1:] - a[:-1] != 2)[0] + 1]
array([14, 22, 28, 41])
Adding first element:
[a[0]] + list(a[np.where(a[1:] - a[:-1] != 2)[0] + 1])
[1, 14, 22, 28, 41]
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