首页 > 解决方案 > 如何填充缺少数据但仅当差距小于某个数字时的时间序列?

问题描述

下午好,

我正在对从传感器流式传输的数据进行预处理,这些数据通常每秒 (1hz) 出现一次。然而,情况并非总是如此,有时会出现 2s、3s 甚至更多的数据间隙。

我正在尝试设置一些代码来填补这些空白,但前提是它们小于某个数字,比如 10 秒。

数据如下:

     Timestamp           Sensor1    Sensor2    Sensor3
7/1/2020 00:00:00           5         135        77
7/1/2020 00:00:01           6         118        79
7/1/2020 00:00:02           4         131        75
7/1/2020 00:00:04           3         125        78
7/1/2020 00:00:05           9         145        67
7/1/2020 00:00:06           6         136        71
7/1/2020 00:00:10           7         141        77
7/1/2020 00:00:11           4         145        72

我想做的是在错过的窗口小于 10 秒时填充数据帧,并用两个相邻值的平均值填充它。

     Timestamp           Sensor1    Sensor2    Sensor3
7/1/2020 00:00:00           5         135        77
7/1/2020 00:00:01           6         118        79
7/1/2020 00:00:02           4         131        75
7/1/2020 00:00:03           3.5       128        76.5
7/1/2020 00:00:04           3         125        78
7/1/2020 00:00:05           9         145        67
7/1/2020 00:00:06           6         136        71
7/1/2020 00:00:07           6.5       138.5      74
7/1/2020 00:00:08           6.5       138.5      74
7/1/2020 00:00:09           6.5       138.5      74
7/1/2020 00:00:10           7         141        77
7/1/2020 00:00:11           4         145        72

我认为一旦我可以设置正确的时间“网格”而不会丢失秒数,使用填充方法应该相对简单。但是我如何告诉它只填充小于 10 秒的窗口呢?

提前致谢

标签: pythonpandastime-series

解决方案


没有 10s 缺失的窗口,它是带有resampleand的东西interpolate

df.set_index('Timestamp').resample('s').interpolate().reset_index()

要仅在缺少少于 10 秒时添加填充,则可以使用groupby并获取一个新组,其中diff2 行之间的秒数小于 10。注意:要查看它,我在最后两个时间戳中将您的数据更改为 10 x 20 和 11 x 22。

print (df.set_index('Timestamp')
         .groupby(df['Timestamp'].diff().dt.total_seconds()
                                 .gt(10).cumsum()
                                 .to_numpy())
         .apply(lambda x: x.resample('s').interpolate())
         .reset_index()
         .drop('level_0', axis=1)
      )
            Timestamp  Sensor1  Sensor2  Sensor3
0 2020-07-01 00:00:00      5.0    135.0     77.0
1 2020-07-01 00:00:01      6.0    118.0     79.0
2 2020-07-01 00:00:02      4.0    131.0     75.0
3 2020-07-01 00:00:03      3.5    128.0     76.5
4 2020-07-01 00:00:04      3.0    125.0     78.0
5 2020-07-01 00:00:05      9.0    145.0     67.0
6 2020-07-01 00:00:06      6.0    136.0     71.0
7 2020-07-01 00:00:20      7.0    141.0     77.0 
8 2020-07-01 00:00:21      5.5    143.0     74.5
9 2020-07-01 00:00:22      4.0    145.0     72.0

推荐阅读