使用数据系列作为输入函数的Python

2024-10-01 22:44:01 发布

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

我在matlab中创建了一个很难用函数来描述的timeseries数据,我想知道如何将它移植到Python中。问题是python中的计时器很少(如果有的话)接受数据集的精确值。我很确定这样的方法会奏效:

#this is matlab code just to represent the data
t=linspace(t0,tf,samples);
dataseries;
input=timeseries(dataseries,t);

#python code
def f(timer):
  for i in range(0,len(t)):
    if timer>t[i] and timer<=t[i+1]:
      f=dataseries[i]
    else:
      pass

output=f(timer)

但我觉得这会非常慢,因为每次代码块运行时都要检查所有的t。有没有更简单的方法来获得这个功能?以下内容可能会快一点,但看起来仍然很脏:

def f(timer):
  for i in range(0,len(t)):
    diff[i]=np.abs(timer-t[i])
  location=np.argmin(diff)
  f=dataseries[location]

output=f(timer)

我知道我可以用傅里叶级数来近似函数,但在这种情况下,精度很重要,所以我更希望输出尽可能精确。Python中是否有用于此的内置函数?你知道吗

谢谢你的帮助!你知道吗

编辑 这里所要求的是完整的代码,而不仅仅是伪代码。使用此代码可以工作,但正如所预测的那样,它相当慢。我的时间序列是10274点长。每个函数调用需要0.015秒。你知道吗

import scipy
from matplotlib import pyplot as plt
import datetime
import numpy as np
from time import sleep

A=scipy.io.loadmat('data_for_python.mat')
time_series=A['t'][0]
unshaped_in=A['in'][0]
shaped_in=A['real_in'][0]

time0=datetime.datetime.now()

diff=np.ones(len(time_series))*50
print len(time_series)
def f(time):
    for i in range(0,len(time_series)):
        diff[i]=np.abs(timer-time_series[i])
    location=np.argmin(diff)
    f=shaped_in[location]
    return f

timer=0    
while(timer<15):
    timer=datetime.datetime.now()-time0
    timer=timer.total_seconds()
    t0=datetime.datetime.now()
    output=f(timer)
    t1=datetime.datetime.now()-t0
    print 'time:', timer
    print 'dt',t1.total_seconds()
    print 'output:', output

Tags: 代码inimportforoutputdatetimelentime
1条回答
网友
1楼 · 发布于 2024-10-01 22:44:01

我建议看一下python的bisect模块……有几种方法可以做到这一点,这取决于您是否/如何处理完全相同的情况。bisect_left()方法返回指定值的数组“右边”的索引,假设时间序列数组是严格排序的。你知道吗

import bisect
import numpy as np

def f(time):
    return bisect.bisect_left(time_series, time)

>>> time_series = np.array([0, 1, 1.5, 2.0, 3.0])
>>> bisect.bisect_left(time_series, 0.9)
1
>>> bisect.bisect_left(time_series, 1.0)  ## note the value when you are exactly equal to a time_series value
1
>>> bisect.bisect_left(time_series, 1.1)
2
>>> bisect.bisect_left(time_series, 1.4)
2
>>> bisect.bisect_left(time_series, 1.5)
2
>>> bisect.bisect_left(time_series, 1.500001)
3

如您所见,这通常会为值x提供右端点,除非相等。还有其他不同的方法来处理端点,bisect()bisect_right(),因此如果您对这种行为感兴趣,我建议您阅读python文档。你知道吗

如果要使用左侧索引,只需从返回值中减去一个,如果需要,可以使用该索引将其索引到另一个数组中。但在使用之前,您需要对结果进行错误检查:

ind = bisect.bisect_left(time_series, time)
if (ind < 0) or not (time_series[ind-1] < time <= time_series[ind]):
     ## raise an error condition

相关问题 更多 >

    热门问题