【问题标题】:python/pandas time series: fast attack/slow decay; peak detection with decaypython/pandas时间序列:快速攻击/慢衰减;衰减峰检测
【发布时间】:2021-04-21 03:25:36
【问题描述】:

我想在时间序列 ts(pandas 数据帧中的一列)上实现“快速攻击/慢衰减”(使用指数衰减的峰值检测)过滤器,描述如下:

fasd[t] = max(ts[t], 0.9 * fasd[t-1])

“基本”代码(如下)可以工作,但是是否有 Pythonic 和有效的方法来做到这一点,使用 rolling() 或矢量化方法?谢谢。

import pandas as pd
ts = [1,0,0,0,0,1,0,0,0,1,0.95,1,1,1,1,1,0,0,1,1,1,1,1,1,]
df = pd.DataFrame({'ts':ts})
df['fasd'] = 0
df.loc[0,'fasd'] = df.iloc[0]['ts']
for i in range(1, len(df)):
    df.loc[i, 'fasd'] = max(df.loc[i,'ts'], 0.9*df.loc[i-1, 'fasd'])

【问题讨论】:

  • 如果您可以将您的检测器定义为 IIR 或 FIR 滤波器,那么有许多快速实现 - 例如在 scipy 中

标签: pandas time-series rolling-computation peak-detection


【解决方案1】:

使用numpy更高效:

from time import time
import pandas as pd

ts = [1,0,0,0,0,1,0,0,0,1,0.95,1,1,1,1,1,0,0,1,1,1,1,1,1] * 1000  # artificially increasing the input size
df = pd.DataFrame({'ts':ts})
df['fasd'] = 0
df.loc[0,'fasd'] = df.iloc[0]['ts']
df2 = df.copy()

t0 = time()
for i in range(1, len(df)):
    df.loc[i, 'fasd'] = max(df.loc[i,'ts'], 0.9*df.loc[i-1, 'fasd'])
t1 = time()
print(f'Pandas version executed in {t1-t0} sec.')

def fasd(array):
    for i in range(1, len(array)):
        array[i,1] = max(array[i,0], 0.9*array[i-1,1])
    return array

t0 = time()
df2 = pd.DataFrame(fasd(df2.to_numpy()))
t1 = time()
print(f'Numpy version executed in {t1-t0} sec.')

输出:

Pandas version executed in 3.0636708736419678 sec.
Numpy version executed in 0.011569976806640625 sec.

【讨论】:

    猜你喜欢
    • 2011-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    相关资源
    最近更新 更多