大熊猫 - 指数加权移动平均线 - 类似于excel

Abb*_*bas 4 python mean pandas

考虑我有一个包含两列A和B的10行数据帧,如下所示:

    A  B
0  21  6
1  87  0
2  87  0
3  25  0
4  25  0
5  14  0
6  79  0
7  70  0
8  54  0
9  35  0
Run Code Online (Sandbox Code Playgroud)

在excel中我可以计算出rolling mean这样的排除第一行: 在此输入图像描述 在此输入图像描述

我怎么能在熊猫中做到这一点?

这是我尝试过的:

import pandas as pd

df = pd.read_clipboard() #copying the dataframe given above and calling read_clipboard will get the df populated
for i in range(1, len(df)):
    df.loc[i, 'B'] = df[['A', 'B']].loc[i-1].mean()
Run Code Online (Sandbox Code Playgroud)

这给了我匹配excel的理想结果.但有没有更好的熊猫方式呢?我尝试过使用expandingrolling没有产生预期的结果.

EFT*_*EFT 5

您有一个指数加权移动平均线,而不是一个简单的移动平均线.这就是为什么pd.DataFrame.rolling不起作用.你可能正在寻找pd.DataFrame.ewm.

从...开始

df

Out[399]: 
    A  B
0  21  6
1  87  0
2  87  0
3  25  0
4  25  0
5  14  0
6  79  0
7  70  0
8  54  0
9  35  0

df['B'] = df["A"].shift().fillna(df["B"]).ewm(com=1, adjust=False).mean()
df

Out[401]: 
    A          B
0  21   6.000000
1  87  13.500000
2  87  50.250000
3  25  68.625000
4  25  46.812500
5  14  35.906250
6  79  24.953125
7  70  51.976562
8  54  60.988281
9  35  57.494141
Run Code Online (Sandbox Code Playgroud)

即使只有十行,这样做也可以将代码加速大约10倍%timeit(从10.3ms开始959微秒).在100行上,这成为100的因子(1.1ms对110ms).

  • 你可以使用`adjust = False`,我想,像`df ["A"] .shift().fillna(df ["B"]).ewm(com = 1,adjust = False).mean() `. (3认同)