2017-02-05 1 views
2

DataFrameがあり、各行で関数を実行しています。 row要素の1つを満たしたものが辞書に追加されます。この時点で私は機能を終了したい、それは従来のループではないので、私はbreakを使用することはできません。pandasデータフレームの各行で関数を実行し、条件が満たされたときに関数を停止する方法

各行に機能を適用する別の方法を使用するか、applyメソッドを「適用」するのを停止する方法がありますか?

コード

test = # exert from the df I'm using 
    30MA close 
29 0.001311 0.000900 
30 0.001313 0.001060 
31 0.001294 0.001150 
32 0.001290 0.001000 
33 0.001293 0.000950 
34 0.001305 0.000906 
35 0.001310 0.000767 
36 0.001318 0.000800 
37 0.001325 0.000598 
38 0.001331 0.000601 

# Create and run buy and hold backtest 

# buy and hold is measured by the appriciation from first price that crosses the 30MA to close of the most recent period 

buy_and_hold_results = {} 
coin = 'BBR' 
def buy_and_hold(close, MA, coin): 

    if MA < close: 
     entry = close 
     exit = coins[coin].loc[len(coins[coin].index)-1].close 

     profit = exit/entry 

     buy_and_hold_results[coin] = profit 

test.apply(lambda x : buy_and_hold(x['close'], x['30MA'], coin), axis=1) 

buy_and_hold_results 

答えて

0

あなたは必ずしもapplyを使用しない場合、あなたはforループによってDATAFRAMEを反復し、DataFrame.ilocで各行を得ることができます。その後、breakを使用できます。

def buy_and_hold(close, MA, coin): 

    if MA < close: 
     entry = close 
     exit = coins[coin].loc[len(coins[coin].index)-1].close 

     profit = exit/entry 

     buy_and_hold_results[coin] = profit 

     return True 

for i in range(len(test)): 
    x = test.iloc[i] 
    if buy_and_hold(x['close'], x['30MA'], coin): 
     break 
関連する問題