getting difference between list values with variable window

Question:

>>> jj = [1,3,9,4,5,6,1,2,4,1,7,9,0,4,1,9]
>>> np.diff(jj) 
[ 2  6 -5  1  1 -5  1  2 -3  6  2 -9  4 -3  8]

np.diff gives difference between the consecutive numbers. I am looking for difference between every element with a gap of 3 values

input: [1,3,9,4,5,6,1,2,4,1,7,9,0,4,1,9]

difference between the bold values
output : [3,-3,0,-1,-9]

Asked By: arya

||

Answers:

Well, the most straightforward way is to slice for every third number:

>>> import numpy as np
>>> arr = np.array([1,3,9,4,5,6,1,2,4,1,7,9,0,4,1,9])
>>> np.diff(arr[::3])
array([ 3, -3,  0, -1,  9])

Note, if you use a numpy.ndarray then this is fairly space-efficient since arr[::3] creates a view

Answered By: juanpa.arrivillaga

First, you can use slicing with step : 3. then use numpy.diff. You can read understanding-slicing

import numpy as np
a = np.array([1,3,9,4,5,6,1,2,4,1,7,9,0,4,1,9])
b = np.diff(a[::3])
print(b)

Output: array([ 3, -3, 0, -1, 9])

Answered By: I'mahdi

You still can use np.diff just pass not the whole array but a specific array like this:

np.diff(jj[::3])
Answered By: Masha
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.