仅计算最后一个指数加权移动平均 pandas

use*_*780 9 python pandas

我知道,对于熊猫来说,通过这样做

test_df.ewm(halflife=half_life_for_mean).mean()
Run Code Online (Sandbox Code Playgroud)

我可以随时得到指数移动平均线......

然而我实际上只对最后一个感兴趣,我怀疑通过计算所有它可能有点低效。换句话说,我所需要的只是

test_df.ewm(halflife=half_life_for_mean).mean().iloc[-1]
Run Code Online (Sandbox Code Playgroud)

然而...我想知道这是否效率太低,它本质上需要从开始到构造进行计算ewm().mean()

是否有其他方法可以让我仅获取最后一个元素,而无需花费时间来计算整个时间依赖ewm.mean()

Lau*_* B. 1

另一种技术

这次我们使用的online方法是:

import pandas as pd

df = pd.DataFrame({'col1':[1, 1, 2, 3, 3, 5, 8, 9],
                   })

online_ewm = df['col1'].ewm(alpha=0.5, adjust=False).online()
df['ewm'] = online_ewm.mean()


new_values = pd.DataFrame({'col1':[10, 11, 13]
                           })

def add_newRow(df, new_values, ncol, online_ewm):
    r = pd.concat([df, new_values], axis=0, ignore_index=True)
    r.loc[len(df):len(r), 'ewm'] = online_ewm.mean(update=r.loc[len(df):len(r), ncol])
    return r

new_df = add_newRow(df, new_values, 'col1', online_ewm)

print(new_df)
Run Code Online (Sandbox Code Playgroud)
    col1        ewm
0      1   1.000000
1      1   1.000000
2      2   1.500000
3      3   2.250000
4      3   2.625000
5      5   3.812500
6      8   5.906250
7      9   7.453125
8     10   8.726562
9     11   9.863281
10    13  11.431641
Run Code Online (Sandbox Code Playgroud)