简体   繁体   中英

Multiple conditions in for-loop

I want to loop through a data frame to check if one statement is stratified (before checking elif, I want the code goes through all the K values and if it is not satisfied check the elif): I have the following data frame:

z={'speed':[2.2,12.74,5.1,.91,8.9]}
data=pd.DataFrame(data=z)

I want to select the row which has speed less than 5 and previous speed is also less than 5. if this statement is not satisfied, I want the code finds the first point (backwards) which has speed less than 5 this is the code I've wrote but it has syntax error and I'm not sure if the code goes through all k to check the first statement and then check the second one in case the first one is not satistfied:

for k in reversed(data.index[:-1]):
if (data['speed'][k]<5 and data['speed'][k-1]<5):
    print(k)
break
elif data['speed'][k]<5:
    print(k)
break

the outcome of this should be 3, since the first statement is not satisfied Thank you for your help

Your break statement indentation is not correct. The code is always breaking the loop at the first break . The code should be like this:

import pandas as pd
z={'speed':[2.2, 2.74, 5.1, 9.1, 0.5]}
data=pd.DataFrame(data=z)

found = 0

for k in range(len(data['speed']) - 1, 0, -1):
    if (data['speed'][k]<5 and data['speed'][k-1]<5):
       print(k)
       found = 1
       break
    
if found == 0:
    for k in range(len(data['speed']) - 1, -1, -1):
        if data['speed'][k]<5:
           print(k)
           break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM