Home > OS >  Python - subtraction inside rolling window
Python - subtraction inside rolling window

Time:03-31

I need to make subtractions inside red frames as [20-10,60-40,100-70] that results in [10,20,30]

enter image description here

Current code makes subtractions but I don't know how to define red frames

seq = [10, 20, 40, 60, 70, 100]
window_size = 2
for i in range(len(seq) - window_size 1):
    x=seq[i: i   window_size]
    y=x[1]-x[0]
    print(y)

CodePudding user response:

You can build a quick solution using the fact that seq[0::2] will give you every other element of seq starting at zero. So you can compute seq[1::2] - seq[0::2] to get this result.

Without using any packages you could do:

seq = [10, 20, 40, 60, 70, 100]
sub_seq = [0]*(len(seq)//2)
for i in range(len(sub_seq)):
    sub_seq[i] = seq[1::2][i] - seq[0::2][i]

print(sub_seq)

Instead you could use Numpy. Using the numpy array object you can subtract the arrays rather than explicitly looping:

import numpy as np
seq = np.array([10, 20, 40, 60, 70, 100])
sub_seq = seq[1::2] - seq[0::2]

print(sub_seq)

CodePudding user response:

Here's a solution using numpy which might be useful if you have to process large amounts of data in a short time. We select values based on whether their index is even (index % 2 == 0) or odd (index % 2 != 0).

import numpy as np

seq = [10, 20, 40, 60, 70, 100]
seq = np.array(seq)

index = np.arange(len(seq))
seq[index % 2 != 0] - seq[index % 2 == 0]
  • Related