如何在pandas数据帧中的每一行上运行一个函数,并在满足条件时停止它

时间:2017-02-05 14:29:57

标签: python pandas numpy dataframe

我有一个DataFrame,我在每一行上运行一个函数,该函数比较行中的值,一旦满足条件,其中一个行元素被添加到字典中。此时我希望函数结束,它不是传统的循环所以我不能使用break

我是否应该使用不同的方法将该功能应用于每一行,或者是否有办法停止{申请'的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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我设置了以下代码:

import pandas as pd
ma = [0.001311, 0.001313, 0.001294, 0.001290, 0.001293, 0.001305, 0.001310, 0.001318, 0.001325, 0.001331]
close = [0.000900, 0.001060, 0.001150, 0.001000, 0.000950, 0.000906, 0.000767, 0.000800, 0.000598, 0.000601]
df = pd.DataFrame(list(zip(ma, close)), 
               columns =['30MA', 'Close']) 
df

这会输出类似于您给出的内容:

    30MA        Close
0   0.001311    0.000900
1   0.001313    0.001060
2   0.001294    0.001150
3   0.001290    0.001000
4   0.001293    0.000950
5   0.001305    0.000906
6   0.001310    0.000767
7   0.001318    0.000800
8   0.001325    0.000598
9   0.001331    0.000601

您的 lambda 函数实际上会将相同的函数单独应用于每一行。我只想这样做:

buy_and_hold_results = {}
coin = 'BBR'
for ind, row in df.iterrows():
    if row['30MA'] < row['Close']:
        entry = close
        exit = coins[coin].loc[len(coins[coin].index)-1].close
        profit = exit / entry
        buy_and_hold_results[coin] = profit
        break
        
buy_and_hold_results

注意上面的代码输出的是一个空字典。我不确定代码应该做什么。