Home > Mobile >  Python: Combine for loop in while loop and iterate rows in a data
Python: Combine for loop in while loop and iterate rows in a data

Time:12-15

I would like to iterate rows of data and print the final row after reaching a condition. My code looks like this

D_sum = 4.39e-05
count = 0
while D_sum < 1:
   for row in df.iterrows():
       count  = 1
       D_sum  = D_sum
       print('count', count)
       print('D_sum', D_sum)
       print('row', row)
       break  # When i write break the loop is executing correct but, its not printing final row. Its printing first row of data. 

If I don't write Break, the loop is continuing and ending after certain iterations.

I tried to write this code

count = 0
flag = True
while flag:
    for row in df.iterrows():
        count  = 1
        D_sum  = (df[['Di']].sum()).values
        print('count:', count)
        print('D_sum', D_sum)
        print(row)
if D_sum == 1:
   flag = False

But this also continuing until certain iterations (Infinite loop) Please help me correcting the code in python

CodePudding user response:

D_sum = 4.39e-05
count = 0
for row in df.iterrows():
    count  = 1
    D_sum  = D_sum
    print('count', count)
    print('D_sum', D_sum)
    # Check your condition here 
    if D_sum >= 1:
       print('row', row)
       break 
  • Related