首页 > 解决方案 > 重新采样/重新索引传感器数据

问题描述

我想对传感器数据(大约 300 个不同的传感器)进行一些数据处理。这是来自温度传感器的原始数据的示例:

 "2018-06-30T13:17:05.986Z" 30.5
 "2018-06-30T13:12:05.984Z" 30.3
 "2018-06-30T13:07:05.934Z" 29.5
 "2018-06-30T13:02:05.873Z" 30.3
 "2018-06-30T12:57:05.904Z" 30

我想重新采样数据以平滑日期时间:

13:00:00
13:05:00
13:10:00
...

我编写了一些有效的代码,但在用于较大文件时速度非常慢。我的代码只是通过线性插值将所有数据上采样到 1 秒。然后下采样到请求的频率。

有没有更快的方法来实现这一点?

编辑:传感器数据被写入数据库,我的代码从数据库中的任意时间间隔加载数据

EDIT2:我的工作代码

upsampled = dataframe.resample('1S').asfreq()
upsampled = upsampled.interpolate(method=method, limit=limitT) # ffill or bfill for some sensors 
resampled = upsampled.astype(float).resample(str(sampling_time) + 'S').mean() # for temperature 
resampled = upsampled.astype(float).resample(str(sampling_time) + 'S').asfreq() # for everything else

标签: pythonpandas

解决方案


您可以先将数据帧的索引设置为带有时间戳的列,然后使用resample()方法将其带到每 1 秒或每 5 分钟间隔的数据。

例如:

temp_df = pd.read_csv('temp.csv',header=None)
temp_df.columns = ['Timestamps','TEMP']
temp_df = temp_df.set_index('Timestamps') #set the timestamp column as index
temp_re_df = temp_df.TEMP.resample('5T').mean()

您可以将周期设置为resample()ie T - min 、 S - sec 、 M - 月、 H - 小时等的参数,还可以应用类似mean()ormax()的函数min()来考虑下采样方法。

PS:这是因为您的时间戳是熊猫的日期时间格式。其他用于pd.to_datetime(temp_df['Timestamps'],unit='s')转换为日期时间索引列


推荐阅读