Pandas 使用其他不规则时间列表对不规则时间序列进行重新采样和插值
Pandas resample and interpolate an irregular time series using a list of other irregular times
我从 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'])
我从 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'])