简体   繁体   English

Pandas 使用其他不规则时间列表重新采样和插入不规则时间序列

[英]Pandas resample and interpolate an irregular time series using a list of other irregular times

I have data collected from 2 different sensors which operate asynchronously at non-uniform intervals.我从 2 个不同的传感器收集了数据,这些传感器以非均匀间隔异步运行。 I want to get data from sensor 1 interpolated to the timestamps from sensor 2. I have found a round about way of doing this with Pandas involving first creating a combined time series, interpolating it and then combining the interpolated one with the 2nd sensor's time series to only bring out the intersecting times.我想将来自传感器 1 的数据插入到来自传感器 2 的时间戳中。我找到了一种使用 Pandas 进行此操作的方法,包括首先创建一个组合时间序列,对其进行插值,然后将插入的时间序列与第二个传感器的时间序列相结合只带出相交的时间。 Is there a more Pythonic (or Pandaic) way to do this more efficiently.有没有更 Pythonic(或 Pandaic)的方式来更有效地做到这一点。 Here is a sample code which uses the method I describe above:这是使用我上面描述的方法的示例代码:

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'])

Using Pandas we can do the following:使用 Pandas,我们可以执行以下操作:

You can use union from pandas.Index along with reindex from pandas.DataFrame, this will eliminate all the merging:您可以使用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')

Output:输出:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM