Find closest row of DataFrame to given time in Pandas

前端 未结 3 671
佛祖请我去吃肉
佛祖请我去吃肉 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 11:42

    I was confronting the same problem today. I wanted a function able to give me the closest value prior a given timestamp. Here is the function I got:

    def get_nearest_past(data, timestamp):
        index = data.index.get_loc(timestamp,"ffill")
        return data.iloc[index]
    

    In the case that you need the global closest (and not the closest before as in my case), you can use:

    def get_nearest(data, timestamp):
        index = data.index.get_loc(timestamp,"nearest")
        return data.iloc[index]
    

    You can find more information in the get_loc documentation.

提交回复
热议问题