简体   繁体   中英

Pandas rolling with date offset

From the main documentation, here is an example of pandas with rolling dates.

import pandas as pd
times = ['2020-01-01', '2020-01-03', '2020-01-04', '2020-01-05', '2020-01-29']
s = pd.Series(range(5), index=pd.DatetimeIndex(times))
s.rolling(window='2D').sum()

2020-01-01    0.0  
2020-01-03    1.0  
2020-01-04    3.0  
2020-01-05    5.0  
2020-01-29    4.0  
dtype: float64

Would it be possible to do a 2 day rolling window with a one day offset, so that, for example, on the 29th the window would be starting on the 27th, and ending on the 28th, instead (in which case, the last row, for example, would be zero)?

Use closed='neither' to exclude the end of the window in addition to the default exclusion of the start of the window (default is 'right' , 'neither' amounts to 'right' and 'left' simultaneously), increase the length from '2D' to '3D' to accomodate for exclusion:

s.rolling(window='3D', closed = 'neither').sum()

IIUC, you want to exclude the current row of rolling . To do that, you have to recreate the full index without missing days then apply your rolling. Finally, you have to shift your values to exclude the current from the result:

>>> s.resample('D').first().fillna(0).rolling('2D').sum().shift().reindex(s.index)
2020-01-01    NaN
2020-01-03    0.0
2020-01-04    1.0
2020-01-05    3.0
2020-01-29    0.0
dtype: float64

Before rolling , your data look like:

>>> s.resample('D').first().fillna(0)
2020-01-01    0.0
2020-01-02    0.0
2020-01-03    1.0
2020-01-04    2.0
2020-01-05    3.0
2020-01-06    0.0
2020-01-07    0.0
2020-01-08    0.0
2020-01-09    0.0
2020-01-10    0.0
2020-01-11    0.0
2020-01-12    0.0
2020-01-13    0.0
2020-01-14    0.0
2020-01-15    0.0
2020-01-16    0.0
2020-01-17    0.0
2020-01-18    0.0
2020-01-19    0.0
2020-01-20    0.0
2020-01-21    0.0
2020-01-22    0.0
2020-01-23    0.0
2020-01-24    0.0
2020-01-25    0.0
2020-01-26    0.0
2020-01-27    0.0
2020-01-28    0.0
2020-01-29    4.0
Freq: D, dtype: float64

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM