[英]Pandas rolling with date offset
在主文檔中,這里有一個帶有滾動日期的 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
是否可以進行為期 2 天的滾動 window 並有一天的偏移量,例如,在 29 日,window 將從 27 日開始,到 28 日結束(在這種情況下,最后一行,例如,為零)?
使用closed='neither'
除了默認排除 window 的開頭(默認為'right'
, 'neither'
同時相當於'right'
和'left'
)之外,還可以排除 window 的結尾,增加長度從'2D'
到'3D'
以適應排除:
s.rolling(window='3D', closed = 'neither').sum()
IIUC,您要排除當前行rolling
。 為此,您必須在不丟失日期的情況下重新創建完整索引,然后應用滾動。 最后,您必須更改值以從結果中排除當前值:
>>> 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
在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.