当条件保持为True时,如何循环保持值不变

时间:2016-03-03 14:14:01

标签: python pandas dataframe algorithmic-trading

规则是:

如果Regime = 0 => Position = 0
如果Regime = 1 => Position = Size
如果Regime = -1 => Position = -Size

Position取值后,我希望保持该值不变,Re保持为1-1

任何想法如何在Position更改之前保持Re值不变?

我的数据框:

    Dates()  Close  Re  Size
0  12/29/10  86.76   0  2073
1  12/30/10  86.54   1  2209
2  12/31/10  86.30   1  2339
3  08/09/11  82.69   0   984
4  08/10/11  78.23   0   880
5  09/02/11  79.34  -1  1015
6  09/06/11  78.08  -1  1002

1 个答案:

答案 0 :(得分:0)

您可以使用loc

$ perl -ne 'print unless /<!DOCTYPE html>/i .. /<body>/i' file.html</pre>

编辑:

您可以fillna使用print df Dates() Close Re Size 0 12/29/10 86.76 0 2073 1 12/30/10 86.54 1 2209 2 12/31/10 86.30 1 2339 3 08/09/11 82.69 0 984 4 08/10/11 78.23 0 880 5 09/02/11 79.34 -1 1015 6 09/06/11 78.08 -1 1002 df.loc[df['Re']==0, 'Position'] = 0 df.loc[df['Re']==1, 'Position'] = df['Size'] df.loc[df['Re']==-1, 'Position'] = -df['Size'] print df Dates() Close Re Size Position 0 12/29/10 86.76 0 2073 0 1 12/30/10 86.54 1 2209 2209 2 12/31/10 86.30 1 2339 2339 3 08/09/11 82.69 0 984 0 4 08/10/11 78.23 0 880 0 5 09/02/11 79.34 -1 1015 -1015 6 09/06/11 78.08 -1 1002 -1002

method='ffill'
print df
     Dates()  Close  Re  Size  Position
0   12/30/10  86.54   1   100       100
1   12/30/10  86.54   1   100       100
2   12/29/10  86.76   0  2073         0
3   12/30/10  86.54   1  2209      2209
4   12/30/10  86.54   1 -2209     -2209
5   12/29/10  86.76   0  2073         0
6   12/30/10  86.54   1  2209      2209
7   12/29/10  86.76   0  2073         0
8   12/31/10  86.30   1  2339      2339
9   08/09/11  82.69   0   984         0
10  08/10/11  78.23   0   880         0
11  09/02/11  79.34  -1  1015     -1015
12  09/06/11  78.08  -1  1002     -1002
13  09/06/11  78.08   1    20        20


df.loc[((df['Position'].shift()).fillna(1)) == 0,'pos'] = df['Position']
df.loc[ df['Position'] == 0, 'pos'] = 0
df.at[0,'pos'] = df.at[0,'Position']
df['pos'] = df['pos'].fillna(method='ffill')