Python 如何在dataframe中的每一行上运行函数,并在满足条件时使其停止

Python 如何在dataframe中的每一行上运行函数,并在满足条件时使其停止,python,pandas,numpy,dataframe,Python,Pandas,Numpy,Dataframe,我有一个数据帧,我在每一行上运行一个函数,该函数比较行中的值,一旦满足条件,一个行元素就会添加到字典中。在这一点上,我希望函数结束,它不是一个常规的循环,因此我不能使用中断 我应该使用不同的方法将函数应用于每一行,还是有方法停止“应用”的apply方法 代码 test = # exert from the df I'm using 30MA close 29 0.001311 0.000900 30 0.001313 0.001060 31 0.001294

我有一个数据帧,我在每一行上运行一个函数,该函数比较行中的值,一旦满足条件,一个行元素就会添加到字典中。在这一点上,我希望函数结束,它不是一个常规的循环,因此我不能使用
中断

我应该使用不同的方法将函数应用于每一行,还是有方法停止“应用”的
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
test=#从我正在使用的df中使用
30毫安关闭
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
#创建并运行购买和保留测试
#买入并持有是通过从30毫安区间的第一个价格到最近一段时间的收盘价的估值来衡量的
买入和持有结果={}
硬币='BBR'
def买入和持有(收盘、MA、硬币):
如果MA<关闭:
进入=关闭
退出=硬币[coin].loc[len(硬币[coin].index)-1]。关闭
利润=出入境
买入和持有结果[硬币]=利润
测试。应用(lambda x:买入和持有(x['close',x['30MA',coin),axis=1)
买入和持有结果

我设置了以下代码:

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
买入和持有结果={}
硬币='BBR'
对于ind,df.iterrows()中的行:
如果行['30MA']<行['Close']:
进入=关闭
退出=硬币[coin].loc[len(硬币[coin].index)-1]。关闭
利润=出入境
买入和持有结果[硬币]=利润
打破
买入和持有结果
注意,上面的代码输出一个空字典。我不确定代码应该做什么