gpt4 book ai didi

python - 使用 Pandas 版本 18.0rc1 将非等距时间序列插值(上采样)为等距时间序列

转载 作者:太空宇宙 更新时间:2023-11-03 16:50:56 24 4
gpt4 key购买 nike

我想对(高档)非等距时间序列进行插值以获得等距时间序列。

目前我正在按以下方式进行:

  1. 采用原始时间序列。
  2. 每隔 30 秒创建一次包含 NaN 值的新时间序列(使用 resample('30S').asfreq() )
  3. 连接原始时间序列和新时间序列
  4. 对时间序列进行排序以恢复时间顺序(我不喜欢这一点 - 排序的复杂性为 O = n log(n) )
  5. 插值
  6. 从时间序列中删除原始点

Pandas 18.0rc1 版本有更简单的方法吗?就像在 matlab 中一样,您有原始时间序列,并将新时间作为参数传递给 interpolate() 函数,以在所需时间接收值。

我注意到原始时间序列的时间可能不是所需时间序列的时间的子集。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

values = [271238, 329285, 50, 260260, 263711]
timestamps = pd.to_datetime(['2015-01-04 08:29:4',
'2015-01-04 08:37:05',
'2015-01-04 08:41:07',
'2015-01-04 08:43:05',
'2015-01-04 08:49:05'])

ts = pd.Series(values, index=timestamps)
ts
ts[ts==-1] = np.nan
newFreq=ts.resample('60S').asfreq()

new=pd.concat([ts,newFreq]).sort_index()
new=new.interpolate(method='time')

ts.plot(marker='o')
new.plot(marker='+',markersize=15)

new[newFreq.index].plot(marker='.')

lines, labels = plt.gca().get_legend_handles_labels()
labels = ['original values (nonequispaced)', 'original + interpolated at new frequency (nonequispaced)', 'interpolated values without original values (equispaced!)']
plt.legend(lines, labels, loc='best')
plt.show()

image

最佳答案

已经有几个请求以更简单的方式插值所需的值(我稍后将在链接中进行编辑,但在问题跟踪器中搜索插值问题)。所以将来会有更简单的方法。

现在您可以更简洁地编写选项,如下

In [9]: (ts.reindex(ts.index | newFreq.index)
.interpolate(method='time')
.loc[newFreq.index])
Out[9]:
2015-01-04 08:29:00 NaN
2015-01-04 08:30:00 277996.070686
2015-01-04 08:31:00 285236.860707
2015-01-04 08:32:00 292477.650728
2015-01-04 08:33:00 299718.440748
...
2015-01-04 08:45:00 261362.402778
2015-01-04 08:46:00 261937.569444
2015-01-04 08:47:00 262512.736111
2015-01-04 08:48:00 263087.902778
2015-01-04 08:49:00 263663.069444
Freq: 60S, dtype: float64

这仍然涉及上面列出的所有步骤,但索引的合并比连接和删除更干净。

关于python - 使用 Pandas 版本 18.0rc1 将非等距时间序列插值(上采样)为等距时间序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35843578/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com