Pandas - 选择每两周重采样的起始日期
假设我有一个时间序列,它从2014年6月1日开始,那天是星期天。
在 [7]:
# 2014-06-01 is Sunday
df = pd.Series( index=pd.date_range( '2014-06-01', periods=30 ), data=nr.randn( 30 ) ) #
df
我可以按周重新采样,从星期天开始,到星期六结束:
In [9]:
df.resample( 'W-SAT' )
Out[9]:
2014-06-07 0.119460
2014-06-14 0.464789
2014-06-21 -1.211579
2014-06-28 0.650210
2014-07-05 0.666044
Freq: W-SAT, dtype: float64
现在我想每两周做一次同样的事情,所以我试了这个:
In [11]:
df.resample( '2W-SAT' )
Out[11]:
2014-06-07 0.119460
2014-06-21 -0.373395
2014-07-05 0.653729
Freq: 2W-SAT, dtype: float64
哦,输出结果是1周,然后是2周,再来2周。这不是我预期的结果。我本来希望第一个索引的值是'2014-06-14'。为什么会这样呢?我该怎么做才能把前两周一起重新采样呢?
2 个回答
0
2014年6月的第一个星期六是7号,所以这个月的星期六从7号开始。如果你用星期天来算,它就会从6月的1号开始,正如你预期的那样。
df.resample( '2W-SUN' )
Out[11]:
2014-06-01 0.739895
2014-06-15 0.497950
2014-06-29 0.445480
2014-07-13 0.767430
Freq: 2W-SUN, dtype: float64
8
在尝试了各种resample
的选项后,我可能找到了一个解释。resample
选择新重采样索引的第一个条目的方式似乎取决于closed
选项:
- 当
closed=left
时,resample
会寻找最新的开始时间 - 当
closed=right
时,resample
会寻找最早的开始时间
我来举个例子:
# 2014-06-01 is Sunday
df = pd.Series( index=pd.date_range( '2014-06-01', periods=30 ), data=range(1 , 31 ) ) #
df
下面的例子展示了closed=left
的行为。在一个左闭合的两周区间内,最新的“左侧”星期六是2014年5月31日,如下所示:
df.resample( '2W-SAT',how='sum', closed='left', label='left' )
Out[119]:
2014-05-31 91
2014-06-14 287
2014-06-28 87
Freq: 2W-SAT, dtype: int64
下一个例子展示了closed=right
的行为,这个我在最初的帖子中没有理解(resample
默认是closed=right
)。在一个右闭合的两周区间内,最早的“右侧”星期六是2014年6月7日,如下所示:
df.resample( '2W-SAT',how='sum', closed='right', label='right' )
Out[122]:
2014-06-07 28
2014-06-21 203
2014-07-05 234
Freq: 2W-SAT, dtype: int64