Home > Blockchain >  How to do the pandas.rolling with "stride" in python?
How to do the pandas.rolling with "stride" in python?

Time:11-19

I want to use the rolling window function with "stride".
That means, the step is still 1.
But we can resample the index with a certain interval not only 1.
Do you have any idea of this? Thanks a lot.

For example:

df:  
  row0: 0  
  row1: 1  
  row2: 2  
  row3: 3  
  row4: 4  
  row5: 5  
  row6: 6   
  row7: 7  
  row8: 8  
  row9: 9   
  ...  

df1 = df.rolling(window=3, stride=3).sum() (where stride is not exist in pd.rolling)  
df1:   
  row0: nan  
  row1: nan  
  row2: nan  
  row3: nan  
  row4: nan   
  row5: nan  
  row6: 9 (row6 row3 row0)  
  row7: 12 (row7 row4 row1)    
  row8: 15 (row8 row5 row2)    
  row9: 18 (row9 row6 row3)     
  ...   

CodePudding user response:

I guess you wouldn't really use rolling in this case, but rather a shift:

out = df.shift(2).add(df)

output:

      col
row0  NaN
row1  NaN
row2  2.0
row3  4.0

CodePudding user response:

I figured it out by myself.
The solution is:

def mean_with_stide(arr, stride):  
    return arr.iloc[::stride].mean()  

df.rolling(window=(win_len-1)*stide 1).apply(lambda x: mean_with_stride(x, stride))
  • Related