我有一个程序可以理想地每秒测量一次温度。然而,实际上这不会发生。有时,它会跳过一秒钟或中断 400 秒,然后决定重新开始录制。这在我的 2×n 数据框中留下了空白,理想情况下 n = 86400(一天中的秒数)。我想对其应用某种移动/滚动平均值以获得更好的绘图,但如果我对“原始”数据文件执行此操作,数据点的数量就会减少。这显示为 here , 观察 x 轴。我知道“不错的数据”看起来还不太好;我只是在玩弄一些值(value)观。
所以,我想实现一个数据清理方法,将数据添加到数据帧中。我想过,但不知道如何实现。我是这样想的:
如果index不等于时间,那么我们需要加一个数,在time = index。如果这个差距只有 1 个值,那么前一个数字和下一个数字的平均值对我来说就可以了。但是如果它更大,比如少了 100 秒,那么就需要做一个线性函数,它会稳定地增加或减少该值。
所以我想训练集可能是这样的:
index time temp
0 0 20.10
1 1 20.20
2 2 20.20
3 4 20.10
4 100 22.30
在这里,我想获取索引 3、时间 3 以及时间 = 4 和时间 = 100 之间缺失的值。我对我的格式化技巧感到抱歉,我希望它是清楚的。
我将如何对此进行编程?
请您参考如下方法:
使用合并完整时间列然后插值:
# Create your table
time = np.array([e for e in np.arange(20) if np.random.uniform() > 0.6])
temp = np.random.uniform(20, 25, size=len(time))
temps = pd.DataFrame([time, temp]).T
temps.columns = ['time', 'temperature']
>>> temps
time temperature
0 4.0 21.662352
1 10.0 20.904659
2 15.0 20.345858
3 18.0 24.787389
4 19.0 20.719487
以上是缺失时间数据生成的随机表。
# modify it
filled = pd.Series(np.arange(temps.iloc[0,0], temps.iloc[-1, 0]+1))
filled = filled.to_frame()
filled.columns = ['time'] # Create a fully filled time column
merged = pd.merge(filled, temps, on='time', how='left') # merge it with original, time without temperature will be null
merged.temperature = merged.temperature.interpolate() # fill nulls linearly.
# Alternatively, use reindex, this does the same thing.
final = temps.set_index('time').reindex(np.arange(temps.time.min(),temps.time.max()+1)).reset_index()
final.temperature = final.temperature.interpolate()
>>> merged # or final
time temperature
0 4.0 21.662352
1 5.0 21.536070
2 6.0 21.409788
3 7.0 21.283505
4 8.0 21.157223
5 9.0 21.030941
6 10.0 20.904659
7 11.0 20.792898
8 12.0 20.681138
9 13.0 20.569378
10 14.0 20.457618
11 15.0 20.345858
12 16.0 21.826368
13 17.0 23.306879
14 18.0 24.787389
15 19.0 20.719487
