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

标签 python pandas

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

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

  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/

相关文章:

python - 数据类型 float32 for attr 'T' 不在允许值列表中 : int32, int64

python - 如何修复 "no module named cv2"?

python - Python 中的高效协整检验

python - 值错误 : multiclass-multioutput format is not supported using sklearn roc_auc_score function

python - 添加一个新的 pandas dataframe 列,用条件计算填充它(平均如果,标准差如果)

python - pip install -r requirements.txt 不在 vscode 虚拟环境中安装库

python - 当不需要时,请求会对 POST 参数进行编码

python - 如何根据本地 csv 中的 where 子句从 pandas 访问 Google Bigquery 数据

Pandas 行间计算

python - 查找两个列表的索引最大值