Skip to main content
 首页 » 编程设计

python之插值到特定时间

2025年02月15日12wayfarer

假设我有这段代码:

import numpy as np 
import time 
from datetime import datetime 
 
class Measurements(): 
    def __init__(self, time_var, value): 
        self.time_var = time_var 
        self.value = value 
 
a = np.array([ Measurements('30-01-2017 12:02:15.880922', 100), 
               Measurements('30-01-2017 12:02:16.880922', 100), 
               Measurements('30-01-2017 12:02:17.880922', 110), 
               Measurements('30-01-2017 12:02:18.880922', 99), 
               Measurements('30-01-2017 12:02:19.880922', 96)]) 
 
 
b = np.array([ Measurements('30-01-2017 12:02:15.123444', 10), 
               Measurements('30-01-2017 12:02:18.880919', 12), 
              ]) 

所以,我有 5 个来自 a 的测量值和 2 个来自 b 的测量值。

我想通过使用 a作为基地,找到失踪的b特定时间的值 a发生了。

所以,最后的b总会有 a时间值和长度。(当时,我想用 time.mktime(datetime.strptime(s, "%d-%m-%Y %H:%M:%S.%f").timetuple()) 以秒为单位返回时间

因此,b将是:

np.array([ Measurements('30-01-2017 12:02:15.880922', MISSING_VALUE), 
               Measurements('30-01-2017 12:02:16.880922', MISSING_VALUE), 
               Measurements('30-01-2017 12:02:17.880922', MISSING_VALUE), 
               Measurements('30-01-2017 12:02:18.880922', MISSING_VALUE), 
               Measurements('30-01-2017 12:02:19.880922', MISSING_VALUE)]) 

现在,我不知道该如何处理。

一个想法是先执行 interp as here并将 b 长度拉伸(stretch)为与 a 相等。

或使用 interp1d (更灵活):

from scipy import interpolate 
 
a = np.array([100, 123, 123, 118, 123]) 
b = np.array([12, 11, 14, 13]) 
 
b_interp = interpolate.interp1d(np.arange(b.size),b, kind ='cubic', assume_sorted=False) 
b_new = b_interp(np.linspace(0, b.size-1, a.size)) 

那么,如何处理时间呢?

请您参考如下方法:

这是您的问题的解决方案:

  • 首先,如果您使用三次插值,则 a 至少需要 4 个值,b 至少需要 4 个值(scipy.interpolate.interp1d 和 kind="cubic"否则不工作)
  • 其次,你不能用 scipy.interpolate.interp1d 插入不在你定义的范围内的值(b 次的范围)

我稍微更改了您的初始代码以向您展示:

time_a_full = ['30-01-2017 12:02:15.880922','30-01-2017 12:02:16.880922','30-01-2017 12:02:17.880922','30-01-2017 12:02:18.880922','30-01-2017 12:02:19.880922','30-01-2017 12:02:22.880922'] 
time_b_full = ['30-01-2017 12:02:15.123444','30-01-2017 12:02:16.880919','30-01-2017 12:02:18.880920', '30-01-2017 12:02:19.880922','30-01-2017 12:02:20.880922'] 
 
# Here I transform the time in seconds as suggested 
time_a = np.array([time.mktime(datetime.strptime(s, "%d-%m-%Y %H:%M:%S.%f").timetuple()) for s in time_a_full]) 
time_b = np.array([time.mktime(datetime.strptime(s, "%d-%m-%Y %H:%M:%S.%f").timetuple()) for s in time_b_full]) 
 
values_a = np.array([100,100,110,99,96,95]) 
values_b = np.array([10,12,13,16,20]) 
 
# result of the linear interp with the numpy function 
np.interp(time_a, time_b, values_b) 
 
# result of the cubic interpolation 
f = interpolate.interp1d(time_b,values_b, kind="cubic") 
time_a[time_a<time_b.min()]=time_b.min() # use this to stay on range define by the times of b 
time_a[time_a>time_b.max()]=time_b.max() # use this to stay on range define by the times of b 
f(time_a)