python - Pandas 使用其他不规则时间列表对不规则时间序列进行重新采样和插值

标签 python pandas time-series interpolation resampling

我从 2 个不同的传感器收集数据,这些传感器以不均匀的间隔异步运行。我想从传感器 1 获取数据,并将其插值到传感器 2 的时间戳中。 我发现了一种使用 Pandas 进行此操作的方法,首先创建一个组合时间序列,对其进行插值,然后将插值时间序列与第二个传感器的时间序列组合,以仅显示相交时间。 是否有更 Pythonic(或 Pandaic)的方式来更有效地做到这一点。这是使用我上面描述的方法的示例代码:

import numpy as np
from matplotlib import pyplot as plt
import datetime
import pandas as pd

rand_secs = np.sort(np.random.randint(1, high=60,size=10))
times = [pd.datetime(2019, 5, 23,9, x) for x in rand_secs]
frame1 = pd.DataFrame(index = times,
                      data = np.sin(rand_secs/60*2*np.pi))
ax1 = frame1.plot(marker='+')
plt.xlim(pd.datetime(2019, 5, 23,9, 0), pd.datetime(2019, 5, 23,9, 59))
plt.ylim(-1.1,1.1)

times2 = [pd.datetime(2019, 5, 23,9, x) for x in np.sort(np.random.randint(1, high=60,size=10))]
frame2 = pd.DataFrame(index = times2)

frame12_combined = pd.merge(frame1, frame2, how='outer',left_index=True, right_index=True)
frame12_interp = frame12_combined.interpolate(method='index') #Linear is not Correct

frame1_resampled = pd.merge(frame2, frame12_interp, how='left',left_index=True, right_index=True)
frame1_resampled.plot(ax=ax1,style='o' )
ax1.legend(['Original time series', 'Resampled time series'])

最佳答案

使用 Pandas,我们可以执行以下操作:

您可以使用 union来自 pandas.Index 以及 reindex来自 pandas.DataFrame,这将消除所有合并:

ax1 = frame1.plot(marker='+')
frame1_r = frame1.reindex(frame1.index.union(frame2.index))\
                 .interpolate(method='index')\
                 .reindex(frame2.index)
frame1_r.plot(ax=ax1, style='o')

输出:

enter image description here

关于python - Pandas 使用其他不规则时间列表对不规则时间序列进行重新采样和插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56285924/

相关文章:

python - 用于样本外预测的 ARMA.predict 不适用于 float ?

python - 时间序列数据预处理 - numpy strides trick to save memory

r - R中的滞后功能有什么作用?

python - gremlin-python 不是可用的 GremlinScriptEngine

python - 核心转储 : Extract all the global variables , 核心转储中的数据结构和子结构

python - 在 Python 中,遍历工作表并仅计算第一列中的非 NaN 单元格。每张表的输出名称和找到的总数

Python如何添加多个列表的总和

python - GHMM - 尝试对 NULL 指针进行 m_free

python - pyarrow.lib.ArrowInvalid : ('Could not convert X with type Y: did not recognize Python value type when inferring an Arrow data type' )

python - 如何迭代股票代码的 DataFrame 列并添加包含股票价格的列?