插入到特定时间

2024-04-28 16:18:54 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有这个代码:

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作为基,找到在a发生的特定时间丢失的b值。在

因此,最后的b将始终具有a时间值和长度(对于时间,我考虑使用time.mktime(datetime.strptime(s, "%d-%m-%Y %H:%M:%S.%f").timetuple())以秒为单位返回时间)

因此,b将是:

^{pr2}$

现在,我不知道该怎么处理。在

一种想法是首先执行interpas here,并将b的长度扩展为与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))

但是,如何处理时间呢?在


Tags: fromimportselfsizedatetimetimevaluevar
1条回答
网友
1楼 · 发布于 2024-04-28 16:18:54

以下是您问题的解决方案:

  • 首先,如果使用三次插值,则a至少需要4个值,b至少需要4个值(scipy.interpolate.interp1d与{}一起使用将不起作用)
  • 其次,不能用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)

相关问题 更多 >