Igor Rivin
Igor Rivin

Reputation: 4864

selecting rows in a pandas dataframe starting with a certain index value

Suppose I have a dataframe, where the rows are indexed by trading days, so something like:

Date          ClosingPrice
2017-3-16      10.00
2017-3-17      10.13
2017-3-20      10.19
    ...

I want to find $N$ rows starting with (say) 2017-2-28, so I don't know the date range, I just know that I want to do something ten rows down. What is the most elegant way of doing this? (there are plenty of ugly ways...)

Upvotes: 1

Views: 1845

Answers (2)

piRSquared
piRSquared

Reputation: 294258

my quick answer

s = df.Date.searchsorted(pd.to_datetime('2017-2-28'))[0]
df.iloc[s:s + 10]

demo

df = pd.DataFrame(dict(
        Date=pd.date_range('2017-01-31', periods=90, freq='B'),
        ClosingPrice=np.random.rand(90)
    )).iloc[:, ::-1]

date = pd.to_datetime('2017-3-11')
s = df.Date.searchsorted(date)[0]
df.iloc[s:s + 10]

         Date  ClosingPrice
29 2017-03-13      0.737527
30 2017-03-14      0.411525
31 2017-03-15      0.794309
32 2017-03-16      0.578911
33 2017-03-17      0.747763
34 2017-03-20      0.081113
35 2017-03-21      0.000058
36 2017-03-22      0.274022
37 2017-03-23      0.367831
38 2017-03-24      0.100930

naive time test

enter image description here

Upvotes: 3

Joran Beasley
Joran Beasley

Reputation: 113948

df[df['Date'] >= Date(2017,02,28)][:10] 

I guess?

Upvotes: 2

Related Questions