-1

I need to stop a loop when a condition is true, I am looping thrue a pandas dataframe and I saw that the problem comes probably from the range(1,len(newdatafr)): because all the elements of this list must be 'filled'

for ind in range(1,len(newdatafr)):
    if newdatafr['h'][ind] > tp_2 and newdatafr['l'][ind] > sl_1:
        sl_1 = tp_2  
        print("scale up")
    elif newdatafr['h'][ind] < tp_2 and newdatafr['h'][ind] > tp_1 and newdatafr['l'][ind] > sl_1:
        sl_1 = tp_1 ## BE

    elif newdatafr['l'][ind] < sl_1: 
        print("Sortie du trade. Ouverture :"+str(open_1)+" Sortie :"+str(sl_1) )
        break

How can I write this in an other way ? Thank you

user9007028
  • 125
  • 1
  • 1
  • 14
  • 3
    simply use `break` – Bemwa Malak Jan 13 '22 at 20:08
  • 1
    The `break` statement in the last `elif` should stop the loop when that condition is met. – Barmar Jan 13 '22 at 20:09
  • 3
    However, looping over pandas dataframes is usually the wrong way to do something. You should use its built-in filtering to get the rows up to the first one that matches the condition. – Barmar Jan 13 '22 at 20:10
  • 1
    See https://stackoverflow.com/questions/47601118/find-only-the-first-row-satisfying-a-given-condition-in-pandas-dataframe/47602605 for how to find that row. – Barmar Jan 13 '22 at 20:10
  • Not that simple @BemwaMalak. I tried, as it is written up. – user9007028 Jan 13 '22 at 20:11
  • 1
    What are `sl_1`,`tp_1`, and `tp_2`? Including (minimal) Example data (even fake data) in your question would facilitate answers. Please read [mre]. [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) – wwii Jan 13 '22 at 20:18
  • With `pandas dataframe` you don't "need to stop a loop". You need "not to loop". It's better that you write a new question with what you are trying to do with the loop, and someone would show you how to do it without a loop. – Aryerez Jan 13 '22 at 21:55

1 Answers1

0

If I understand correctly, you need a break for each if statement:

for ind in range(1,len(newdatafr)):
    if newdatafr['h'][ind] > tp_2 and newdatafr['l'][ind] > sl_1:
        sl_1 = tp_2  
        print("scale up")
        break
    elif newdatafr['h'][ind] < tp_2 and newdatafr['h'][ind] > tp_1 and newdatafr['l'][ind] > sl_1:
        sl_1 = tp_1 ## BE
        break
    elif newdatafr['l'][ind] < sl_1: 
        print("Sortie du trade. Ouverture :"+str(open_1)+" Sortie :"+str(sl_1) )
        break
eshirvana
  • 23,227
  • 3
  • 22
  • 38