在日期 +/- 2 个工作日内对 pandas 时间序列进行切片

slice pandas timeseries on date +/- 2 business days(在日期 +/- 2 个工作日内对 pandas 时间序列进行切片)
本文介绍了在日期 +/- 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

这篇关于在日期 +/- 2 个工作日内对 pandas 时间序列进行切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)