在日期 +/- 2 个工作日内对 pandas 时间序列进行切片
问题描述
具有以下时间序列:
In [65]: p
Out[65]:
Date
2008-06-02 125.20
2008-06-03 124.47
2008-06-04 124.40
2008-06-05 126.89
2008-06-06 122.84
2008-06-09 123.14
2008-06-10 122.53
2008-06-11 120.73
2008-06-12 121.19
Name: SPY
如何在特定日期 +/- 2 个相邻(工作日)进行切片,即如果 d = '2008-06-06':
how can I slice on a specfic date +/- 2 neighbouring (business) days, so ie if d = '2008-06-06':
-2 2008-06-04 124.40
-1 2008-06-05 126.89
0 2008-06-06 122.84
1 2008-06-09 123.14
2 2008-06-10 122.53
解决方案
你可以使用索引方法get_loc
,然后切片:
You could use the index method get_loc
, and then slice:
d = pd.to_datetime('2008-06-06')
loc = s.index.get_loc(d)
In [12]: loc
Out[12]: 4
In [13]: s[loc-2:loc+3]
Out[13]:
2008-06-04 124.40
2008-06-05 126.89
2008-06-06 122.84
2008-06-09 123.14
2008-06-10 122.53
Name: SPY
.
如果你只是在两天内对这些感兴趣:
In [14]: dt = datetime.timedelta(1)
In [15]: s[d - 2*dt:d + 2*dt]
Out[15]:
2008-06-04 124.40
2008-06-05 126.89
2008-06-06 122.84
Name: SPY
相关文章