Pandas rolling values

I think you need first add NaNs and then this solution:

N = 3
x = np.concatenate([[np.nan] * (N-1), df['temperature'].values])

def rolling_window(a, window):
    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
    strides = a.strides + (a.strides[-1],)
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
print (rolling_window(x, N))
[[  nan   nan  0.  ]
 [  nan  0.    1.  ]
 [ 0.    1.    2.  ]
 [ 1.    2.     nan]
 [ 2.     nan  4.  ]
 [  nan  4.    2.  ]
 [ 4.    2.    0.8 ]
 [ 2.    0.8   4.  ]
 [ 0.8   4.    8.8 ]
 [ 4.    8.8   7.12]]

Leave a Comment