python-3.x - 更快的滚动在不均匀间隔的时间序列上应用标准和斜率
问题描述
我有一个 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 秒进行一次计算:
- 计算 00:00:00 到 00:05:00 之间所有 (~300) 数据的 sd 和斜率
- 计算 00:00:30 到 00:05:30 之间所有 (~300) 数据的 sd 和斜率
- 计算 00:01:00 到 00:06:00 之间所有 (~300) 数据的 sd 和斜率
- 等等
代替:
- 计算 00:00:00 到 00:05:00 之间所有 (~300) 数据的 sd 和斜率
- 计算 00:00:01 和 00:05:01 之间所有 (~300) 数据的 sd 和斜率
- 计算 00:00:02 和 00:05:02 之间所有 (~300) 数据的 sd 和斜率
- 等等
我不知道如何(以正确的熊猫方式)使用不均匀间隔的数据来做到这一点。
它将使过程加快 30 倍,以换取精度的损失。
解决方案
推荐阅读
- reactjs - 使用 Jest 和 Enzyme 测试 react-router 重定向
- swift - 我应该为 iOS 应用创建 Firestore 索引吗
- mysql - 获取每个可用天的持续时间
- python - PyYAML文件高效管理
- azure-cosmosdb - FeedOption 中的 MaxItemCount 和 QueryMetric 中的 RetrievedDocumentCount 如何在 Cosmos DB 中工作,为什么两者都不匹配?
- java - 如何在java中修改和序列化字符串?
- android - 是否有更新的 Android 制造商 USB 供应商 ID 的完整列表?
- python - 我无法在pygame中移动精灵
- php - 如何解决 wamp 上的 mysql 端口 3306 错误?
- android - 重复警报 BroadcastReceiver Intent 字符串附加信息未更新