简体   繁体   English

使用Python的panda对多传感器时间序列数据进行子采样

[英]Subsample multi-sensor time series data using Python's panda.Dataframe

I have a file coming from multiple sensor readings. 我有一个来自多个传感器读数的文件。 Each line is of the following format: 每行的格式如下:

timestamp sensor_name sensor_value

eg 例如

191.12 temperature -5.19
191.17 pressure 20.05
191.18 pressure 20.04
191.23 pressure 20.07
191.23 temperature -5.17
191.31 temperature -5.09
...

The frequency of the readings is irregular, approximately 10-20Hz. 读数频率是不规则的,大约为10-20Hz。 I need do downsample these readings to 1Hz and output the result in the following format 我需要将这些读数下采样到1Hz,并以以下格式输出结果

timestamp sensor_1_value sensor_2_value ... sensor_n_value

reflecting the (running?) mean value of the sensor readings in the successive seconds, eg 反映连续几秒中传感器读数的(运行?)平均值,例如

timestamp temperature pressure
191.00 -5.02 21.93
192.00 -5.01 21.92
193.00 -5.01 21.91
...

I loaded each line of the input file into a dictionary as follows: 我将输入文件的每一行加载到字典中,如下所示:

   def add(self, timestamp, sensor_name, sensor_value):
     self.timeseries[sensor_name].append([timestamp, sensor_value]) 

... and created a DataFrame from the dictionary: ...并根据字典创建了一个DataFrame:

df = pd.DataFrame(self.timeseries)

... but I need some guidance how to move forward from here, ie what's an elegant way to perform the sampling. ...但是我需要一些指导,说明如何从这里开始前进,即执行采样的一种优雅方法。

I'm not 100% sure what you're doing but this is what I'd do to solve the problem. 我不是100%知道您在做什么,但这就是我要解决的问题。 It assumes your data file is space-separated with a header row. 假定您的数据文件用标题行用空格分隔。

import pandas as pd
import numpy as np

# Load the data
data = pd.read_csv(file_name, sep="\s", index_col=None)

# Take the mean of the values within a second
data = np.floor(data["timestamp"])
data = data.groupby(["timestamp", "sensor_name"]).mean()
data = data.reset_index()

# Pivot
data = data.pivot(index="timestamp", columns="sensor_name", values="sensor_value")

If you have some other concept for "downsampling" in mind for this context you should do that instead of mean. 如果您在这种情况下还想了解“下采样”的其他概念,则应该这样做,而不是刻薄。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM