2017-05-03 12 views
2

index_pd:パンダ現在の行*前の行+前の行

tradedate | percent | day_index 
------ | ------| ------ 
2015-06-02 | 0  |  1000 
2015-06-03 | 0.5 |  0 
2015-06-04 | 0.6 |  0 
..... 

なりたい:

tradedate | percent | day_index 
------ | ------| ------ 
2015-06-02 | 0  |  1000 
2015-06-03 | 0.5 |  1500 = 1000 + 1000 * 0.5 
2015-06-04 | 0.6 |  2400 = 1500 + 1500 * 0.6 
..... 

私は

index_pd['day_index'] =index_pd['day_index'].shift(1) * index_pd['percent'].shift(0) + index_pd['day_index'].shift(1) 

を試みるが、それは第二列に影響を与えます。 ループiterrowsであるため交換する方法にバッチindex_pdで千行、感謝

+0

あなたは第二の元の値を保持したい場合は、別の列に書き込む必要があります行。 – TLOwater

+0

計算はどのように行うことができますか? –

+0

バッチはどういう意味ですか?私の元の答えは正しくない、あなたは日のインデックスに結果を書いて、次のステップを計算するために結果を使用する必要があります。 – TLOwater

答えて

1

ない非常に良い解決策は、あります:あなたの計算のすべての行で

for i, row in index_pd.iterrows(): 
    if i == 0: 
     index_pd.loc[i, 'value'] = index_pd['day_index'].iat[0] 
    else: 
     index_pd.loc[i, 'value'] = index_pd.loc[i,'percent'] * index_pd.loc[i-1, 'value']+ \ 
            index_pd.loc[i-1, 'value'] 
print (index_pd) 
    tradedate percent day_index value 
0 2015-06-02  0.0  1000 1000.0 
1 2015-06-03  0.5   0 1500.0 
2 2015-06-04  0.6   0 2400.0 
0

前回day_index値が(1+index_pd.percent)を掛けます。だから、(1+index_pd.percent)の累積製品を使用して結果を得るためにday_indexの最初の値を掛けすることができます

index_pd['day_index'] = (index_pd.percent+1).cumprod()*index_pd.day_index.iat[0] 
関連する問題