Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫从最近的年终日期开始重新取样?_Python_Pandas - Fatal编程技术网

Python 熊猫从最近的年终日期开始重新取样?

Python 熊猫从最近的年终日期开始重新取样?,python,pandas,Python,Pandas,有人能解释一下我的重采样是怎么回事吗 比如说, In [53]: daily_3mo_treasury.resample('5Y').mean() Out[53]: 1993-12-31 2.997120 1998-12-31 4.917730 2003-12-31 3.297176 2008-12-31 2.997204 2013-12-31 0.097330 2018-12-31 0.53447

有人能解释一下我的重采样是怎么回事吗

比如说,

   In [53]: daily_3mo_treasury.resample('5Y').mean()
    Out[53]:
    1993-12-31    2.997120
    1998-12-31    4.917730
    2003-12-31    3.297176
    2008-12-31    2.997204
    2013-12-31    0.097330
    2018-12-31    0.534476
其中,我的时间序列中的最后一个日期是2018-08-23 2.04

我真的希望从最近一个年末重新采样,例如从
2017-12-31
2012-12-31
等等

我试过了

end = daily_3mo_treasury.index.searchsorted(date(2017,12,31))
daily_3mo_treasury.iloc[:end].resample('5Y').mean()

In [66]: daily_3mo_treasury.iloc[:end].resample('5Y').mean()
Out[66]:
1993-12-31    2.997120
1998-12-31    4.917730
2003-12-31    3.297176
2008-12-31    2.997204
2013-12-31    0.097330
2018-12-31    0.333467
dtype: float64
其中,
daily\u 3mo\u treasury.iloc[:end]
中的最后一个值为
2017-12-29 1.37

为什么我的第二次5年重采样没有结束
2017-12-31


编辑:我的索引已排序。

来自@ALollz-重新采样时,箱子基于索引中的第一个日期

sistart = daily_3mo_treasury.index.searchsorted(date(1992,12,31))
siend = daily_3mo_treasury.index.searchsorted(date(2017,12,31))

In [95]: daily_3mo_treasury.iloc[sistart:siend].resample('5Y').mean()
Out[95]:
1992-12-31    3.080000
1997-12-31    4.562246
2002-12-31    4.050696
2007-12-31    2.925971
2012-12-31    0.360775
2017-12-31    0.278233
dtype: float64

好的,那么如果2018年已经结束,那么你想基本上忽略这些日期,只使用2017-12-31?可能重复的
convention='end'
?查看文档:当您
重新采样时
,箱子基于索引中的第一个日期。在这两种情况下,这似乎都是
1993-12-31
,因此删除结束日期不会影响这一点,这就是为什么不管切片如何,都会看到相同的日期范围。我建议使用
pd.date\u range
来指定
pd.cut
到组的箱子,或者只采用coldspeed的答案,使用整数除法到组。每5年一次。在这种情况下,您需要类似于
groupby((df.index.year+2)//5*5+2)