1

I am trying to insert a for loop inside a function that loops through values from a list.

Consider I have the following dataframe:

import pandas as pd

df = pd.DataFrame()

df['A'] = (53.104898,   52.032832,  48.705107,  43.150132,  42.09353,   42.32076,   41.620527,  44.479339,  44.673272,  43.811447,  44.273042,  47.384234,  49.210512,  50.330492   ,48.808856, 49.543268,  43.460175,  41.54373,   49.618678,  44.988629,  52.964725,
56.358917,  53.366254)
df['B'] = (2.157,2.0826,0.8452,-0.3046,-0.3436,-0.3906,-1.1528,-0.9462,-1.1314,-0.9994,-1.0538,0.785,1.5334,0.1424, 0.764,-0.6844,-2.5798,-2.3644,-1.97,-3.7466,-1.862,-0.248, -0.456)

def func():
    q = [40,60]

    def valuation_formula(x, y):

        for i in q:
            if x > 3.9:
                return 'SIT'
            elif x < -3.8:
                return 'SIT'
            elif x > 0.00 and y > i:
                return 'BUY'
            elif x < 0.00 and y < 41.14:
                return 'SELL'
            else:
                return 'SIT'

    df['C'] = df.apply(lambda row: valuation_formula(row['A'], row['B']), axis=1)

    print(df)
    i=i+1

func()

Actual results should be 2 seperate dataframes. 1 dataframe using 40 as i from list q and second using 60

3
  • what is i in your func() and why i=i+1? Commented Aug 2, 2019 at 12:50
  • 3
    Your loop never looks past the first value in q, because you return from the function in every possible path. Commented Aug 2, 2019 at 12:50
  • You seem to be incrementing i, which doesn't need to be done as it's inside a for loop. Also, where you increment it, it is not defined. Commented Aug 2, 2019 at 12:54

1 Answer 1

2

As mentioned in the comments, a return inside a loop will terminate everything, so you will only look at the first value of q. Also, you are mixing for i in q and i+=1...

Anyway, a quick fix is:

q = [40,60]

def valuation_formula(i, x, y):
    # pass the i as a parameter
    if x > 3.9:
        return 'SIT'
    elif x < -3.8:
        return 'SIT'
    elif x > 0.00 and y > i:
        return 'BUY'
    elif x < 0.00 and y < 41.14:
        return 'SELL'
    else:
        return 'SIT'

# loop here
for i in q:
    df['C'] = df.apply(lambda row: valuation_formula(i, row['A'], row['B']), axis=1)
    print(df)
Sign up to request clarification or add additional context in comments.

1 Comment

thank you this is the correct answer I was looking for

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.