熊猫 - 选择每两周重新采样的开始日期

时间:2014-06-13 14:45:41

标签: python pandas

说我有以下时间序列,从2014-06-01开始,这是一个星期天。

在[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 :(得分:5)

在尝试resample的各种选项后,我可能会有一个解释。 resample选择新重新采样索引的第一个条目的方式似乎取决于closed选项:

  • closed=leftresample寻找最新可能的开始时
  • closed=rightresample寻找最早可能的开始时

我将举例说明:

# 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-05-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的行为,这是我在初始帖子中未理解的行为(closed=right默认情况下resample)。在右侧关闭的2周间隔最早的“右侧”星期六发生在2014/06/07,如下所示:

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

答案 1 :(得分:-1)

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