首页 > 解决方案 > 更快的滚动在不均匀间隔的时间序列上应用标准和斜率

问题描述

我有一个 Pandas (1.0.*) 数据框,其中包含几个物理变量的记录(例如温度、压力和湿度)。两条记录之间的时间间隔大约为 1s,但在 0.8s 和 4s 之间变化。

我想计算 5 分钟滚动窗口中的标准偏差和斜率(线性回归)。

这是我的做法:

import numpy as np
import pandas as pd
import datetime
np.random.seed(1)

# Build the dummy dataset for testing
rows, cols = 1000, 3    
datetimes_sec = pd.date_range('2020-01-01', periods=rows, freq='1s').astype(np.int64) / 1e9
shifts = np.random.rand(rows) - 0.5  # Create random shift between -0.5s and +0.5s
datetimes = [sum(x) * 1e9 for x in zip(datetimes_sec, shifts)]    
df = pd.DataFrame(np.random.rand(rows,cols),
                  columns=['temperature', 'pressure', 'humidity'],
                  index=pd.to_datetime(datetimes))

# Custom function to calculate the slope
def get_slope(series):
    hours_since_epoch = series.index.astype(np.int64) / 3.6e12  # nanosecond to hour, I want the slope to be in [variable's unit] per hour
    slope = np.polyfit(hours_since_epoch, series, 1)[0]
    return slope

# Get the result
df = df.rolling("5min").agg(["std", get_slope]) 

这行得通,但是太慢了:1000 行的最后一行需要超过 2 秒。

我可以看到我的自定义get_slope函数是负责任的,如果我用标准函数(例如min())替换它,它需要 0.007 秒。但我可以找到如何让它更快。

如果不可能更快地获得相同的结果,解决方法可能是跳过一些数据行:不要在每一行上滚动窗口(即 0.8 到 4 秒),而是每 30 秒进行一次计算:

代替:

我不知道如何(以正确的熊猫方式)使用不均匀间隔的数据来做到这一点。

它将使过程加快 30 倍,以换取精度的损失。

标签: python-3.xpandastime-series

解决方案


推荐阅读