Home > Software engineering >  getting difference between list values with variable window
getting difference between list values with variable window

Time:10-14

>>> 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]

CodePudding user response:

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])

CodePudding user response:

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

CodePudding user response:

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

np.diff(jj[::3])
  • Related