ian_chan
ian_chan

Reputation: 355

How to select indices using a combination of loc and iloc

I have a time-sorted dataset indexed by dates looking like:

             result
2009-09-08  Positive
2009-08-24  Negative
2009-06-01  Positive
2009-04-23  Positive
2008-12-06  Positive
 ...         ...

I would like to find a date, for example, 2009-08-24 plus the two rows below the date, i.e.

2009-08-24  Negative
2009-06-01  Positive
2009-04-23  Positive

My problem is that finding a specific date requires loc (df.loc['2009-08-24']), but finding that date and two rows below requires numerical position (iloc). In matlab, I would first find the numerical row number 'n' of '2009-08-24' (the second row in this case) and then select rows 'n' to 'n + 2'. But I am not sure if there is an easier way in python. Thansk!

Upvotes: 0

Views: 1350

Answers (2)

marvb
marvb

Reputation: 1324

df.index.get_loc('2009-08-24') will return the 'numerical row number' for the date you want.

Upvotes: 2

Mr Tarsa
Mr Tarsa

Reputation: 6652

How about

df.loc['2009-08-24':].head(2)

Upvotes: 0

Related Questions