切片 pandas 时间序列,日期为+/- 2个工作日 [英] slice pandas timeseries on date +/- 2 business days
本文介绍了切片 pandas 时间序列,日期为+/- 2个工作日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
具有以下时间序列:
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
推荐答案
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
这篇关于切片 pandas 时间序列,日期为+/- 2个工作日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文