Skip to content Skip to sidebar Skip to footer

How To Run A Function On Each Row In Pandas Dataframe And Have It Stop When A Condition Is Met

I have a DataFrame, I'm running a function on each row, the function compares values in the row, once a condition is met one of the row elements is added to a dictionary. At this p

Solution 1:

I setup the following code:

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

This outputs something similar to what you gave:

    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

Your lambda function will in fact apply the same function individually to each row. I would just do this instead:

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

Note that the above code outputs an empty dictionary. I am not sure what the code is supposed to be doing.

Post a Comment for "How To Run A Function On Each Row In Pandas Dataframe And Have It Stop When A Condition Is Met"