Niels Henkens
Niels Henkens

Reputation: 2696

How to find previous and next rows in dataframe for a datetime value?

I have a dataframe containing events with a datetime column. Now I want to find for a specific datetime value the previous and the next event rows. Is there an efficient way to do this?

My dataframe df looks like this:

       Datetime           Event    ...
0    2019-04-01 00:00:00  x        ...
1    2019-04-01 07:16:54  y
2    2019-04-01 07:17:22  z
3    2019-04-01 07:18:31  a
4    2019-04-01 07:22:23  b
5    2019-04-01 07:23:24  c..

What I've tried is this:

time = pd.to_datetime('2019-04-01 07:20:02')
prev_row = df[df['Datetime'] < time].tail(1)
next_row = df[df['Datetime'] > time].head(1)

This will get me the previous and next rows, but I was wandering if there is a more efficient way to do this (something like .between(), but the for around...)

Upvotes: 1

Views: 166

Answers (1)

BENY
BENY

Reputation: 323226

Check with searchsorted

s=np.searchsorted(df.Datetime,time)

Then

df.iloc[[s-1,s],:]

Upvotes: 3

Related Questions