How do you interpolate from an array containing datetime objects?

后端 未结 4 1895
既然无缘
既然无缘 2020-12-31 09:44

I\'m looking for a function analogous to np.interp that can work with datetime objects.

For example:

import datetime, numpy         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-31 10:19

    numpy.interp() function expects that arr1 and arr2 are 1D sequences of floats i.e., you should convert the sequence of datetime objects to 1D sequence of floats if you want to use np.interp().

    If input data uses the same UTC offset for all datetime objects then you could get a float by subtracting a reference date from all values. It is true if your input is UTC (the offset is always zero):

    from datetime import datetime
    import numpy as np
    
    arr1 = np.array([datetime(2008, 1, d) for d in range(1, 10)])
    arr2 = np.arange(1, 10)
    
    def to_float(d, epoch=arr1[0]):
        return (d - epoch).total_seconds()
    
    f = np.interp(to_float(datetime(2008,1,5,12)), map(to_float, arr1), arr2)
    print f # -> 5.5
    

提交回复
热议问题