slice pandas timeseries on date +/- 2 business days

后端 未结 2 1084
野趣味
野趣味 2021-02-10 09:15

having following timeseries:

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
2         


        
2条回答
  •  滥情空心
    2021-02-10 10:14

    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
    

    .

    If you were just interested in those within two days:

    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
    

提交回复
热议问题