Python 在数据帧中插入缺失的数字

Python 在数据帧中插入缺失的数字,python,pandas,time-series,Python,Pandas,Time Series,我有一个程序,理想情况下每秒测量一次温度。然而,在现实中,这并没有发生。有时,它会跳过一秒钟或故障400秒,然后决定再次开始录制。这在我的2×n数据帧中留下了空白,理想情况下,n=86400(一天中的秒数)。我想对它应用某种移动/滚动平均来获得更好的绘图,但是如果我对“原始”数据文件这样做,数据点的数量就会减少。如图所示,观察x轴。我知道“好数据”看起来还不好;我只是在玩弄一些价值观 因此,我想实现一种数据清理方法,它将数据添加到数据帧中。我考虑过,但不知道如何实施。我的想法如下: 如果索引不等

我有一个程序,理想情况下每秒测量一次温度。然而,在现实中,这并没有发生。有时,它会跳过一秒钟或故障400秒,然后决定再次开始录制。这在我的2×n数据帧中留下了空白,理想情况下,n=86400(一天中的秒数)。我想对它应用某种移动/滚动平均来获得更好的绘图,但是如果我对“原始”数据文件这样做,数据点的数量就会减少。如图所示,观察x轴。我知道“好数据”看起来还不好;我只是在玩弄一些价值观

因此,我想实现一种数据清理方法,它将数据添加到数据帧中。我考虑过,但不知道如何实施。我的想法如下:

如果索引不等于时间,那么我们需要添加一个数字,at time=index。如果这个差距只有一个值,那么上一个数字和下一个数字的平均值就可以了。但如果它更大,比如说缺少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,time 3的值,以及time=4和time=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

首先,可以将第二个值设置为实际时间值,如下所示:

df.index = pd.to_datetime(df['time'], unit='s')
之后,您可以使用pandas的内置时间序列操作重新采样并填充缺失的值:

df = df.resample('s').interpolate('time')
(可选)如果仍要进行平滑处理,则可以使用以下操作:

df.rolling(5, center=True, win_type='hann').mean()
这将顺利与5元素宽。注意:任何基于窗口的平滑都会消耗边缘的值点

现在,您的数据帧将以日期时间(包括日期)作为索引。这是重采样方法所必需的。如果您想丢失日期,只需使用:

df.index = df.index.time