Search code examples
pythonrolling-computation

Python - subtraction inside rolling window


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)

Solution

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