Find closest row of DataFrame to given time in Pandas

前端 未结 3 677
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 11:06

I have a Pandas dataframe which is indexed by a DatetimeIndex:


DatetimeIndex: 53732 entries, 1993-01-07 12:23:5         


        
3条回答
  •  庸人自扰
    2020-12-05 12:00

    I think you can try DatetimeIndex.asof to find the most recent label up to and including the input. Then use the returned datetime to select the appropriate row. If you only need values for a particular column, Series.asof exists and combines the two steps above into one.

    This assumes you want the closest datetime. If you don't care about the date and just want the same time every day, use at_time in DataFrame.

    Follow up:

    Edit: false alarm, I had an older version locally. The latest on master should work with np.abs.

    In [10]: np.abs(df.time - image_time)
    Out[10]: 
    0    27 days, 13:39:02
    1    26 days, 13:39:02
    2    25 days, 13:39:02
    3    24 days, 13:39:02
    4    23 days, 13:39:02
    5    22 days, 13:39:02
    

    Also just to clarify:

    aeronet.index - image_time doesn't work because subtraction on Index is a set difference (back in the day Index used to be constrained to be unique).

提交回复
热议问题