简体   繁体   English

Pandas 滚动日期偏移

[英]Pandas rolling with date offset

From the main documentation, here is an example of pandas with rolling dates.在主文档中,这里有一个带有滚动日期的 pandas 示例。

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)?是否可以进行为期 2 天的滚动 window 并有一天的偏移量,例如,在 29 日,window 将从 27 日开始,到 28 日结束(在这种情况下,最后一行,例如,为零)?

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:使用closed='neither'除了默认排除 window 的开头(默认为'right''neither'同时相当于'right''left' )之外,还可以排除 window 的结尾,增加长度从'2D''3D'以适应排除:

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

IIUC, you want to exclude the current row of rolling . IIUC,您要排除当前行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:rolling之前,您的数据如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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