Numpy difference between neighboring elements
I have algorithm of calculation of the difference between neighboring elements in pure python:
a = range(1000000) #it's numpy array in my case
prev = a[0]
b = [0, ]
for i in a[1:]:
b.append(i - prev)
prev = i
Is there any way to rewrite this functions with Numpy?
Solution 1:
There is the diff
method:
a = range(5) # python list of numpy array
np.diff(a)
returns
array([1, 1, 1, 1])
Solution 2:
Because he said
#it's numpy array in my case,
you may want to use a[1:]-a[:-1]
as it's faster.
> %%timeit a=np.random.rand(10000)
> a[1:]-a[:-1]
6.94 µs ± 188 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
> %%timeit a=np.random.rand(10000)
> np.diff(a)
15.7 µs ± 247 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)