2017-06-19 67 views
4

考虑我有具有两列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 

在Excel我可以计算rollingmean这样不包括第一行: enter image description hereenter image description here

我该如何在熊猫中做到这一点?

这里是我试过:

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() 

这给了我匹配的Excel期望的结果。但是有更好的熊猫方法吗?我试过使用expandingrolling没有产生预期的结果。

+0

我对你在这里瞄准的目标有些困惑。例如,窗口长度为2的系列A的“标准”移动平均值在单元格B2中具有公式= AVERAGE(A2:A1),而不是= AVERAGE(A1,B1)鉴于您已经接受一个答案,我假设你已经得到了你以前的样子,但是如果你有时间提供一些细节,那将是很酷的。 – vestland

+1

我正在尝试制作Heiken-Ashi蜡烛。当前栏开盘价格是前一栏的开盘价和平仓价的平均值。有关更多详细信息,请参阅此链接https://www.quantiacs.com/Blog/Intro-to-Algorithmic-Trading-with-Heikin-Ashi.aspx – Abbas

回答

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 

开始甚至在短短十行,做这种方式通过有关的10 %timeit(959微秒从10.3ms)因素加速了代码。在100行上,这成为100的因子(1.1ms vs 110ms)。

+3

您可以使用'adjust = False',我想,像' df [“A”]。shift()。fillna(df [“B”])。ewm(com = 1,adjust = False).mean()'。 – DSM

+0

@DSM绝对正确。我的眼睛不停地跳过那条线。更新。 – EFT