Skip to content Skip to sidebar Skip to footer

Python: Finding The Input Of Pandas Datetimeindex.asof()

I am trying to use pandas.DatetimeIndex.asof() to find the closest value to a certain date. However, what is the input for this function exactly? The documentation states that the

Solution 1:

Agreed, the use of the word label in the documentation is unclear. The format should be the same as your datetime format. For example:

# If datetime column is already in datetime format:
df.set_index(df.datetime).asof('2018-07-28 13:00:00')

# If datetime is not already in proper datetime format
df.set_index(pd.to_datetime(df.datetime)).asof('2018-07-28 13:00:00')

returns a series of the closest datetime found:

datetime2018-07-28 12:59:45price8.6Name:2018-07-28 13:00:00,dtype:object

Alternative solution (better IMO)

I think a better way to do this though is just to subtract your target datetime from the datetime column, find the minumum, and extract that using loc. In this way you can get the true closest value, including from rows that come after it (asof is limited to the most recent label up to and including the passed label, as noted in the docs you linked)

>>> df.loc[abs(df.datetime - pd.to_datetime('2018-07-28 13:00:00')).idxmin()]
datetime    2018-07-2812:59:45
price                       8.6
Name: 1, dtype: object

Post a Comment for "Python: Finding The Input Of Pandas Datetimeindex.asof()"