Skip to content Skip to sidebar Skip to footer

How To Get The Closest Single Row After A Specific Datetime Index Using Python Pandas

DataFrame I have: A B C 2012-01-01 1 2 3 2012-01-05 4 5 6 2012-01-10 7 8 9 2012-01-15 10 11 12 What I am using now: date_after = dt.datetime

Solution 1:

You might want to go directly do the index:

i = frame.index.searchsorted(date)
frame.ix[frame.index[i]]

A touch verbose but you could put it in a function. About as good as you'll get (O(log n))

Solution 2:

Couldn't resist answering this, even though the question was asked, and answered, in 2012, by Wes himself, and again in 2015, by ajsp. Yes, besides 'truncate', you can also use get_loc with the option 'backfill' to get the nearest date after the specific date. By the way, if you want to nearest date before the specific date, use 'ffill'. If you just want nearby, use 'nearest'.

df.iloc[df.index.get_loc(datetime.datetime(2016,2,2),method='backfill')]

Solution 3:

Couldn't resist answering this, even though the question was asked, and answered, in 2012, by Wes himself. Yes, just use truncate.

df.truncate(before='2012-01-07')

Post a Comment for "How To Get The Closest Single Row After A Specific Datetime Index Using Python Pandas"