1

I have a data frame similar to this:

df = pd.DataFrame({'B': [0, 1, 2, 3, 4]})

I want to use rolling function in pandas, but I don't need the aggregated function (sum, mean, min, max,...) after rolling. I need data for each window.

I can develop a sliding window myself, but my question is about rolling function. is it possible to have something similar to this by using rolling function in pandas.

when I use the following function

w = df.rolling(2)

I received the following result:

Rolling [window=2,center=False,axis=0]

while I need this:

w = [[0 , 1]
    [1 , 2]
    [2 , 3]
    [3 , 4]]
MSN
  • 173
  • 4
  • 12
  • 2
    What you want is [How to shift a column in Pandas DataFrame](https://stackoverflow.com/questions/10982089/how-to-shift-a-column-in-pandas-dataframe) – RunOrVeith Oct 24 '18 at 09:22

2 Answers2

1

Since pandas 1.1 rolling objects are iterable, so you can just do:

w = list(df.rolling(2))
Philipp
  • 1,191
  • 1
  • 14
  • 16
0

You could use np.stride_tricks:

import numpy as np
as_strided = np.lib.stride_tricks.as_strided  
win = 2
v = as_strided(df.B, (len(df) - (win - 1), win), (df.B.values.strides * 2))
print(v)
Rohit-Pandey
  • 2,039
  • 17
  • 24