Find closest row of DataFrame to given time in Pandas

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

    This simple method will return the (integer index of the) TimeSeriesIndex entry closest to a given datetime object. There's no need to copy the index to a regular column - simply use the .to_pydatetime method instead.

    import numpy as np
    
    i = np.argmin(np.abs(df.index.to_pydatetime() - image_time))
    

    Then you simply use the DataFrame's .iloc indexer:

    df.iloc[i]
    

    Here's a function to do this:

    def fcl(df, dtObj):
        return df.iloc[np.argmin(np.abs(df.index.to_pydatetime() - dtObj))]
    

    You can then further filter seamlessly, e.g.

    fcl(df, dtObj)['column']
    

提交回复
热议问题