piRSquared piRSquared - 1 month ago 12
Python Question

slice pandas series by set number of rows from a specific index

consider the

pd.Series
s


import pandas as pd
import numpy as np

tidx = pd.date_range('2012-12-31', periods=261)
s = pd.Series(np.arange(len(tidx)), tidx)


Suppose I want to get a 14 period window ending at date
'2013-02-22'


I'd expect the result to be

2013-02-09 40
2013-02-10 41
2013-02-11 42
2013-02-12 43
2013-02-13 44
2013-02-14 45
2013-02-15 46
2013-02-16 47
2013-02-17 48
2013-02-18 49
2013-02-19 50
2013-02-20 51
2013-02-21 52
2013-02-22 53
Freq: D, dtype: int32

Answer

To avoid chained indexing, you could use s.index.get_loc to find the positional index associated with 2013-02-22 and the use iloc with the positional index to make the selection:

In [93]: i = s.index.get_loc('2013-02-22')+1; s.iloc[i-14:i]
Out[93]: 
2013-02-09    40
2013-02-10    41
2013-02-11    42
2013-02-12    43
2013-02-13    44
2013-02-14    45
2013-02-15    46
2013-02-16    47
2013-02-17    48
2013-02-18    49
2013-02-19    50
2013-02-20    51
2013-02-21    52
2013-02-22    53
Freq: D, dtype: int64
Comments