python - pandas df 中 “look ahead” 值的有效方法

标签 python pandas numpy time-series

我有一个包含时间序列的 pandas df,从 t(0) 开始,我需要向前查看 t(n) 并查看前面的最大值和最小值是多少,其大小由下式定义“从”和“到”列。

这是我的 df: enter image description here

这是我的解决方案,它有效,但速度非常慢:

df[‘max_ahead’] = df.apply(lambda x: df[‘value’][int(df[‘from’]):int(df[‘to’])].max(), axis=1)
df[‘min_ahead’] = df.apply(lambda x: df[‘value’][int(df[‘from’]):int(df[‘to’])].min(), axis=1)

有没有办法在 pandas 或 numpy 数组中加快速度?我的 df 包含数百万行,上面的代码花费的时间太长。

最佳答案

由于切片窗口似乎是恒定的(在您的情况下为 100),请尝试以下操作:

df['max_ahead'] = df[value].rolling(window=100).max()
df['max_ahead'] = df['max_ahead'].shift(-100)

最后的转变重新创建了您想要的解决方案,无需使用 apply lambda,这可能会很慢。

关于python - pandas df 中 “look ahead” 值的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48573715/

相关文章:

python - Pandas reshape 柱形

python-2.7 - python / Pandas : How do I convert from datetime64[ns] to datetime

python - Pandas :添加新列,其中包含来自其他两列中任何一列的值

python - numpy中的Unicode元素字符串比较

python - Matplotlib Legend 的问题

javascript - 使用 Python/Flask 迭代 HTML 模板中的 URL 列表

python - 使用 Python Scipy Minimize 优化运输成本流

python - numpy,相同的计算不同的结果

python - kafka-python 生产者 - SSL 连接失败 - 仅限 Trustore

python - tensorflow 卷积神经网络的人脸识别准确率仅为0.05