python - 每秒复制最后一个值直到 Python 2.7 中的下一个数据点的函数,分段常量插值

标签 python python-2.7 time-series interpolation

我在 Python 2.7 中工作,我有时间戳和相应的值。我想将这些值设置为每秒一个值的时基,即最后一个测量值。所以:

[[1,  4,  6],
 [15, 17, 12]]

到:

[[1,  2,  3,  4,  4,  6],
 [15, 15, 15, 17, 17, 12]]

我想出了这个,它可以满足我的要求,但必须有更优雅的方式。有人知道吗?

import numpy as np

#Example data:
origdata= {}
origdata['time'] = [4, 26, 37, 51, 59, 71, 93]
origdata['vals'] = [17, 5, 43, 21, 14, 8, np.NaN]

extratime = [t-1 for t in origdata['time']]
data={}
data['time'] = np.concatenate((origdata['time'][:-1], extratime[1:]), axis=0)
data['vals'] = np.concatenate((origdata['vals'][:-1], origdata['vals'][:-1]), axis=0)

sorter = data['time'].argsort()
data['time'] = data['time'][sorter]
data['vals'] = data['vals'][sorter]

filledOutData = {}
filledOutData['time'] = range(data['time'][0], data['time'][-1])
filledOutData['vals'] = np.interp(filledOutData['time'], data['time'], data['vals'])

用下面的代码绘制原始数据和期望的结果得到下面的图像:

import matplotlib.pyplot as plt
plt.plot(origdata['time'], origdata['vals'], '-o', filledOutData['time'], filledOutData['vals'], '.-')
plt.legend(['original', 'desired result'])
plt.show

An illustration of what I want

最佳答案

试试这个:

data = {}
times = [4, 26, 37, 51, 59, 71, 93]
vals = [17, 5, 43, 21, 14, 8, float('nan')]
# i don't have numpy so i had to change to nan

for i in range(times[0], times[-1]+1):
    if i in times:
        v = vals[times.index(i)]
    data.setdefault('time', []).append(i)
    data.setdefault('vals', []).append(v)

print data['time']

[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27、28、29、30、31、32、33、34、35、36、37、38、39、40、41、42、43、44、45、46、47、48、49、50、51、 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93]

print data['vals']

[17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 21, 21, 21, 21, 21, 21, 21, 21, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 南]

关于python - 每秒复制最后一个值直到 Python 2.7 中的下一个数据点的函数,分段常量插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35871809/

相关文章:

python - 获取文件的 md5 而不将其保存在光盘上

python - Django 1.9 URLField 删除必要的 http ://prefix

python - PyCharm 未列出 python3.6

Python参数语法错误: invalid syntax

python - Colab 中没有名为 'statsmodels.tsa.arima' 的模块,但 Pycharm 中没有

python - __str__ 方法调用实例方法的返回值

python - 对行值进行排序并显示列顺序

python - 如何简单地导入文件

python - 将ARMA模型拟合到python中按时间索引的时间序列

Python:使用 Pandas 从数据框中选择特定日期